SlideShare a Scribd company logo
C language
• Currently, the most commonly-used
language for embedded systems
• “High-level assembly”
• Very portable: compilers exist for virtually
every processor
• Easy-to-understand compilation
• Produces efficient code
• Fairly concise
C language
• Developed between 1969 and 1973 along
with Unix
• Due mostly to Dennis Ritchie
• Designed for systems programming
– Operating systems
– Utility programs
– Compilers
– Filters
• Evolved from B, which evolved from BCPL
#include<stdio.h>
int main()
{
--other statements
}
• The files that are specified in the include
section is called as header file
• These are precompiled files that has some
functions defined in them
• We can call those functions in our program
by supplying parameters
• Header file is given an extension .h
• C Source file is given an extension .c
• This is the entry point of a program
• When a file is executed, the start point is the
main function
• From main function the flow goes as per the
programmers choice.
• There may or may not be other functions
written by user in a program
• Main function is compulsory for any c
program
#include<stdio.h>
int main()
{
printf(“Hello”);
return 0;
}
• This program prints Hello on the screen
when we execute it
• Type a program
• Save it
• Compile the program – This will generate an
exe file (executable)
• Run the program (Actually the exe created out
of compilation will run and not the .c file)
• In different compiler we have different option
for compiling and running. We give only the
concepts.
• Single line comment
– // (double slash)
– Termination of comment is by pressing enter
key
• Multi line comment
/*….
…….*/
This can span over to multiple lines
C language
• arithmetic: + – * / %
• comparison: == != < <= > >=
• bitwise logical: & | ^ ~
• shifting: << >>
• lazy logical: && || !
• conditional: ? :
• assignment: = += -=
• increment/decrement: ++ --
• sequencing: ,
• pointer: * -> & []
• and: &
• or: |
• xor: ^
• not: ~
• left shift: <<
• right shift: >>
• Useful for bit-field manipulations
#define MASK 0x040
if (a & MASK) { … } /* Check bits */
c |= MASK; /* Set bits */
c &= ~MASK; /* Clear bits */
d = (a & MASK) >> 4; /* Select field */
• Syntax:
condition ? result1 : result2
If the condition is true, result1 is returned
else result2 is returned.
• 10==5 ? 11: 12
10!=5 ? 4 : 3
12>8 ? a : b
C language
• A data type defines a collection of data
objects and a set of predefined operations
on those objects.
C language
• Variables are data that will keep on changing
• Declaration
<<Data type>> <<variable name>>;
int a;
• Definition
<<varname>>=<<value>>;
a=10;
• Usage
<<varname>>
a=a+1; //increments the value of a by 1
• Should not be a reserved word like int etc..
• Should start with a letter or an
underscore(_)
• Can contain letters, numbers or underscore.
• No other special characters are allowed
including space
• Variable names are case sensitive
– A and a are different.
• char ch;
• int i;
• i = ‘a’; /* i is now 97 */
• ch = 65; /* ch is now ‘A’ */
• ch = ch + 1; /* ch is now ‘B’ */
• ch++; /* ch is now ‘C’ */
• if(‘a’ <= ch && ch <= ‘z’)
• for(ch = ‘A’; ch <= ‘Z’; ch++)
C language
• The syntax of for loop is
for(initialisation;condition checking;increment)
{
set of statements
}
Eg: Program to print Hello 10 times
for(I=0;I<10;I++)
{
printf(“Hello”);
}
• The syntax of do while loop
do
{
set of statements
}while(condn);
Eg:
i=10; Output:
do 10987654321
{
printf(“%d”,i);
i--;
}while(i!=0)
if (condition)
{
stmt 1; //Executes if Condition is true
}
else
{
stmt 2; //Executes if condition is false
}
switch(var)
{
case 1: //if var=1 this case executes
stmt;
break;
case 2: //if var=2 this case executes
stmt;
break;
default: //if var is something else this will execute
stmt;
}
• When the break statement is executed
inside a loop-statement, the loop-statement
is terminated immediately
• The execution of the program will continue
with the statement following the loop-
statement
• Syntax :
break;
C language
•When the continue statement is executed
inside a loop-statement, the program will
skip over the remainder of the loop-body
to the end of the loop.
•Syntax
Continue;
C language
C language
• Array
– Group of consecutive memory locations
– Same name and type
• To refer to an element, specify
– Array name
– Position number
• Format:
arrayname[ position number ]
– First element at position 0
– n element array named c:
• c[ 0 ], c[ 1 ]...c[ n – 1 ]
C language
• When declaring arrays, specify
– Name
– Type of array
– Number of elements
arrayType arrayName[ numberOfElements ];
– Examples:
int c[ 10 ];
float myArray[ 3284 ];
• Declaring multiple arrays of same type
– Format similar to regular variables
– Example:
int b[ 100 ], x[ 27 ];
• Initializers
int n[ 5 ] = { 1, 2, 3, 4, 5 };
– If not enough initializers, rightmost elements
become 0
int n[ 5 ] = { 0 }
• All elements 0
– If too many a syntax error is produced syntax error
– C arrays have no bounds checking
• If size omitted, initializers determine it
int n[ ] = { 1, 2, 3, 4, 5 };
– 5 initializers, therefore 5 element array
• Initialization
– int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
– Initializers grouped by row in braces
– If not enough, unspecified elements set to zero
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };
• Referencing elements
– Specify row, then column
printf( "%d", b[ 0 ][ 1 ] );
1 2
3 4
1 0
3 4
So far we have used one-dimensional (1D) arrays,
but we can also use arrays with 2 or more
dimensions. 2D arrays essentially correspond to
matrices.
Example:
• int A; // single variable
• int B[6]; // 1D array
• int C[3][4]; // 2D array (matrix)
• int D[3][4][5]; // 3D array
• int E[3][4][5][3]; // 4D array
• //etc
C language
C language
• A string is a sequence of characters treated
as a group
• array can be of any length
• end of string is indicated by a delimiter, the
zero character ‘0’
"A String" A 0gnirtS
• String literal values are represented by sequences
of characters between double quotes (“)
• Examples
– “” - empty string
– “hello”
• “a” versus ‘a’
– ‘a’ is a single character value (stored in 1 byte) as the
ASCII value for a
– “a” is an array with two characters, the first is a, the
second is the character value 0
• Allocate an array of a size large enough to hold the
string (plus 1 extra value for the delimiter)
• Examples (with initialization):
char str1[6] = “Hello”;
char str2[] = “Hello”;
char *str3 = “Hello”;
char str4[6] = {‘H’,’e’,’l’,’l’,’o’,’0’};
• C provides a wide range of string functions for
performing different string tasks
• Examples
– strlen(str) – To find length of string str
– strrev(str) – Reverses the string str as rts
– strcat(str1,str2) – Appends str2 to str1 and returns str1
– strcpy(st1,st2) – copies the content of st2 to st1
– strcmp(s1,s2) – Compares the two string s1 and s2
– strcmpi(s1,s2) – Case insensitive comparison of strings
• Functions come from the utility library string.h
– #include <string.h> to use
C language
• A pointer is a variable whose value is the
address of another variable, i.e., direct
address of the memory location. Like any
variable or constant, you must declare a
pointer before you can use it to store any
variable address. The general form of a
pointer variable declaration is:
• type *var-name;
• There are few important operations, which we
will do with the help of pointers very
frequently.
• we define a pointer variable
• assign the address of a variable to a pointer
• finally access the value at the address
available in the pointer variable. This is done
by using unary operator * that returns the
value of the variable located at the address
specified by its operand. Following example
makes use of these operations:
C language
C language
• Functions
– Modularize a program
– All variables declared inside functions are local variables
• Known only in function defined
– Parameters
• Communicate information between functions
• Local variables
• Benefits of functions
– Divide and conquer
• Manageable program development
– Software reusability
• Use existing functions as building blocks for new programs
• Abstraction - hide internal details (library functions)
– Avoid code repetition
• Function definition format
return-value-type function-name( parameter-list )
{
declarations and statements
}
– Function-name: any valid identifier
– Return-value-type: data type of the result (default
int)
• void – indicates that the function returns nothing
– Parameter-list: comma separated list, declares
parameters
• A type must be listed explicitly for each parameter unless,
the parameter is of type int
• Function definition format (continued)
return-value-type function-name( parameter-list )
{
declarations and statements
}
– Declarations and statements: function body (block)
• Variables can be declared inside blocks (can be nested)
• Functions can not be defined inside other functions
– Returning control
• If nothing returned
– return;
– or, until reaches right brace
• If something returned
– return expression;
• Call by value
– Copy of argument passed to function
– Changes in function do not effect original
– Use when function does not need to modify
argument
• Avoids accidental changes
• Call by reference
– Passes original argument
– Changes in function effect original
– Only used with trusted functions
• Recursive functions
– Functions that call themselves
– Can only solve a base case
– Divide a problem up into
• What it can do
• What it cannot do
– What it cannot do resembles original problem
– The function launches a new copy of itself (recursion step) to
solve what it cannot do
– Eventually base case gets solved
• Gets plugged in, works its way up and solves whole
problem
• Example: factorials
– 5! = 5 * 4 * 3 * 2 * 1
– Notice that
• 5! = 5 * 4!
• 4! = 4 * 3! ...
– Can compute factorials recursively
– Solve base case (1! = 0! = 1) then plug in
• 2! = 2 * 1! = 2 * 1 = 2;
• 3! = 3 * 2! = 3 * 2 = 6;
C language
• A structure is a collection of variables under
a single name. These variables can be of
different types, and each has a name which
is used to select it from the structure. A
structure is a convenient way of grouping
several pieces of related information
together.
• Structures are user defined data types
• It is a collection of heterogeneous data
• It can have integer, float, double or character
data in it
• We can also have array of structures
struct <<structname>>
{
members;
}element;
We can access element.members;
•Compound data:
•A date is
– an int month and
– an int day and
– an int year
• The typedef operator is used for creating
alias of a data type
• For example I have this statement
typedef int integer;
Now I can use integer in place of int
i.e instead of declaring int a;, I can use
integer a;
This is applied for structures too.
• typedef struct student
• {
• int id;
• Char name[10];
• }s;
• Now I can put
• s s1,s2;
• A union value doesn’t “know” which case it
contains
•Choices:
•An element is
– an int i or
– a char c
union AnElt {
int i;
char c;
} elt1, elt2;
elt1.i = 4;
elt2.c = ’a’;
elt2.i = 0xDEADBEEF;
if (elt1 currently has a char) …
C language
Symbolic constants
#define PI 3.1415926535
Macros with arguments for emulating inlining
#define min(x,y) ((x) < (y) ? (x) :
(y))
Conditional compilation
#ifdef __STDC__
File inclusion for sharing of declarations
#include “myheaders.h”
Header file dependencies usually form a directed acyclic
graph (DAG)
How do you avoid defining things twice?
Convention: surround each header (.h) file with a
conditional:
#ifndef __MYHEADER_H__
#define __MYHEADER_H__
/* Declarations */
#endif
C language

More Related Content

PPT
Introduction to HDLs
PPT
Clanguage
PDF
Verilog HDL- 2
PDF
VHDL- data types
PDF
Compiler Construction | Lecture 12 | Virtual Machines
PPT
Chapter Eight(3)
PPT
Chapter Seven(2)
PDF
Compiler Construction | Lecture 13 | Code Generation
Introduction to HDLs
Clanguage
Verilog HDL- 2
VHDL- data types
Compiler Construction | Lecture 12 | Virtual Machines
Chapter Eight(3)
Chapter Seven(2)
Compiler Construction | Lecture 13 | Code Generation

What's hot (20)

PPTX
Verilogspk1
PDF
Compiler Construction | Lecture 10 | Data-Flow Analysis
PPTX
Introduction of flex
PPTX
Hardware Description Language
PPT
C language
PDF
Verilog
PPT
Lex (lexical analyzer)
PDF
CS4200 2019 | Lecture 4 | Syntactic Services
PPT
Digital Circuit Verification Hardware Descriptive Language Verilog
PPTX
Learn c++ Programming Language
PPS
C++ Language
PDF
An Introductory course on Verilog HDL-Verilog hdl ppr
PDF
Compiler Construction | Lecture 3 | Syntactic Editor Services
PDF
C Programming - Refresher - Part III
PPT
Lex and Yacc ppt
DOC
C language
PDF
CS4200 2019 | Lecture 3 | Parsing
PPTX
Tokens expressionsin C++
PPTX
Introduction of bison
PPTX
Yacc (yet another compiler compiler)
Verilogspk1
Compiler Construction | Lecture 10 | Data-Flow Analysis
Introduction of flex
Hardware Description Language
C language
Verilog
Lex (lexical analyzer)
CS4200 2019 | Lecture 4 | Syntactic Services
Digital Circuit Verification Hardware Descriptive Language Verilog
Learn c++ Programming Language
C++ Language
An Introductory course on Verilog HDL-Verilog hdl ppr
Compiler Construction | Lecture 3 | Syntactic Editor Services
C Programming - Refresher - Part III
Lex and Yacc ppt
C language
CS4200 2019 | Lecture 3 | Parsing
Tokens expressionsin C++
Introduction of bison
Yacc (yet another compiler compiler)
Ad

Viewers also liked (11)

PDF
Java Applet and Graphics
PPT
Computer Organization and Assembly Language
PPTX
Data representation
PPTX
Fingerprint Attendance System - the hand-held device for classroom attendance
PPT
[1] Data Representation
PDF
15.project attendence managemnt system
PPT
fingerprint classification systems Henry and NCIC
PPT
Assembly Language Lecture 1
PPT
Assembly Language Basics
PPTX
Fingerprint
PPT
Assembly language programming(unit 4)
Java Applet and Graphics
Computer Organization and Assembly Language
Data representation
Fingerprint Attendance System - the hand-held device for classroom attendance
[1] Data Representation
15.project attendence managemnt system
fingerprint classification systems Henry and NCIC
Assembly Language Lecture 1
Assembly Language Basics
Fingerprint
Assembly language programming(unit 4)
Ad

Similar to C language (20)

PPT
02 functions, variables, basic input and output of c++
PPTX
PPTX
PPTX
Introduction of function in c programming.pptx
PPTX
Functions
PDF
(3) cpp procedural programming
PDF
Data Structure - Lecture 2 - Recursion Stack Queue.pdf
PPTX
Review of C programming language.pptx...
PPT
85ec7 session2 c++
PPTX
Introduction to C ++.pptx
PPTX
CH.4FUNCTIONS IN C (1).pptx
PPT
C programming
PPT
Data types and Operators
PDF
Functions-.pdf
PPTX
Advance topics of C language
PPT
funcrttionadl asfkjoefweno alsdfjoweefwf
PPT
Introduction to c
PPT
c-functions.ppt
PPT
c-functions.ppt
02 functions, variables, basic input and output of c++
Introduction of function in c programming.pptx
Functions
(3) cpp procedural programming
Data Structure - Lecture 2 - Recursion Stack Queue.pdf
Review of C programming language.pptx...
85ec7 session2 c++
Introduction to C ++.pptx
CH.4FUNCTIONS IN C (1).pptx
C programming
Data types and Operators
Functions-.pdf
Advance topics of C language
funcrttionadl asfkjoefweno alsdfjoweefwf
Introduction to c
c-functions.ppt
c-functions.ppt

More from Robo India (20)

PPTX
Robot Motions
PDF
Servo Based 5 Axis Robotic Arm Project Report
PDF
A project report on energy meter monitoring online using wireless transmissio...
PDF
A project report on wireless energy meter reading using x bee
PDF
PC Based Industrial Automation With AVR Atmega 16 - Project Report
PDF
Indian Banks Taglines and Punch Lines
PPTX
Evaluation of dynamics | Gyroscope, Accelerometer, Inertia Measuring Unit and...
PDF
Understanding GPS & NMEA Messages and Algo to extract Information from NMEA.
PPTX
Relay and AVR Atmel Atmega 16
PPTX
DTMF - Dual Tone Multi Frequency Signaling and AVR Atmel Atmega16multi-freque...
PPTX
Servo motor and AVR Atmel Atmega 16
PPTX
IR Sensor Working and Concepts
PPTX
Digital and Analog IR Sensor Working and Cocepts
PPTX
ADC - Analog to Digital Conversion on AVR microcontroller Atmega16
PPTX
LCD Theory and Working Principles
PPTX
Led Theory and Working Principles
PPTX
Fundamentals of embedded system and electronics
PPTX
Single bit oprations in avr microcontroller
PPTX
Input Output programming in AVR microcontroller
PDF
Marketing to youth
Robot Motions
Servo Based 5 Axis Robotic Arm Project Report
A project report on energy meter monitoring online using wireless transmissio...
A project report on wireless energy meter reading using x bee
PC Based Industrial Automation With AVR Atmega 16 - Project Report
Indian Banks Taglines and Punch Lines
Evaluation of dynamics | Gyroscope, Accelerometer, Inertia Measuring Unit and...
Understanding GPS & NMEA Messages and Algo to extract Information from NMEA.
Relay and AVR Atmel Atmega 16
DTMF - Dual Tone Multi Frequency Signaling and AVR Atmel Atmega16multi-freque...
Servo motor and AVR Atmel Atmega 16
IR Sensor Working and Concepts
Digital and Analog IR Sensor Working and Cocepts
ADC - Analog to Digital Conversion on AVR microcontroller Atmega16
LCD Theory and Working Principles
Led Theory and Working Principles
Fundamentals of embedded system and electronics
Single bit oprations in avr microcontroller
Input Output programming in AVR microcontroller
Marketing to youth

Recently uploaded (20)

PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
PPH.pptx obstetrics and gynecology in nursing
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
Cell Structure & Organelles in detailed.
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Classroom Observation Tools for Teachers
PDF
01-Introduction-to-Information-Management.pdf
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
Cell Types and Its function , kingdom of life
PDF
Complications of Minimal Access Surgery at WLH
PDF
Pre independence Education in Inndia.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPTX
Institutional Correction lecture only . . .
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PPTX
Pharma ospi slides which help in ospi learning
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Pharmacology of Heart Failure /Pharmacotherapy of CHF
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPH.pptx obstetrics and gynecology in nursing
Final Presentation General Medicine 03-08-2024.pptx
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Cell Structure & Organelles in detailed.
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Classroom Observation Tools for Teachers
01-Introduction-to-Information-Management.pdf
Anesthesia in Laparoscopic Surgery in India
Microbial disease of the cardiovascular and lymphatic systems
Cell Types and Its function , kingdom of life
Complications of Minimal Access Surgery at WLH
Pre independence Education in Inndia.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Institutional Correction lecture only . . .
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
Pharma ospi slides which help in ospi learning
human mycosis Human fungal infections are called human mycosis..pptx

C language

  • 2. • Currently, the most commonly-used language for embedded systems • “High-level assembly” • Very portable: compilers exist for virtually every processor • Easy-to-understand compilation • Produces efficient code • Fairly concise
  • 4. • Developed between 1969 and 1973 along with Unix • Due mostly to Dennis Ritchie • Designed for systems programming – Operating systems – Utility programs – Compilers – Filters • Evolved from B, which evolved from BCPL
  • 6. • The files that are specified in the include section is called as header file • These are precompiled files that has some functions defined in them • We can call those functions in our program by supplying parameters • Header file is given an extension .h • C Source file is given an extension .c
  • 7. • This is the entry point of a program • When a file is executed, the start point is the main function • From main function the flow goes as per the programmers choice. • There may or may not be other functions written by user in a program • Main function is compulsory for any c program
  • 8. #include<stdio.h> int main() { printf(“Hello”); return 0; } • This program prints Hello on the screen when we execute it
  • 9. • Type a program • Save it • Compile the program – This will generate an exe file (executable) • Run the program (Actually the exe created out of compilation will run and not the .c file) • In different compiler we have different option for compiling and running. We give only the concepts.
  • 10. • Single line comment – // (double slash) – Termination of comment is by pressing enter key • Multi line comment /*…. …….*/ This can span over to multiple lines
  • 12. • arithmetic: + – * / % • comparison: == != < <= > >= • bitwise logical: & | ^ ~ • shifting: << >> • lazy logical: && || ! • conditional: ? : • assignment: = += -= • increment/decrement: ++ -- • sequencing: , • pointer: * -> & []
  • 13. • and: & • or: | • xor: ^ • not: ~ • left shift: << • right shift: >> • Useful for bit-field manipulations #define MASK 0x040 if (a & MASK) { … } /* Check bits */ c |= MASK; /* Set bits */ c &= ~MASK; /* Clear bits */ d = (a & MASK) >> 4; /* Select field */
  • 14. • Syntax: condition ? result1 : result2 If the condition is true, result1 is returned else result2 is returned. • 10==5 ? 11: 12 10!=5 ? 4 : 3 12>8 ? a : b
  • 16. • A data type defines a collection of data objects and a set of predefined operations on those objects.
  • 18. • Variables are data that will keep on changing • Declaration <<Data type>> <<variable name>>; int a; • Definition <<varname>>=<<value>>; a=10; • Usage <<varname>> a=a+1; //increments the value of a by 1
  • 19. • Should not be a reserved word like int etc.. • Should start with a letter or an underscore(_) • Can contain letters, numbers or underscore. • No other special characters are allowed including space • Variable names are case sensitive – A and a are different.
  • 20. • char ch; • int i; • i = ‘a’; /* i is now 97 */ • ch = 65; /* ch is now ‘A’ */ • ch = ch + 1; /* ch is now ‘B’ */ • ch++; /* ch is now ‘C’ */ • if(‘a’ <= ch && ch <= ‘z’) • for(ch = ‘A’; ch <= ‘Z’; ch++)
  • 22. • The syntax of for loop is for(initialisation;condition checking;increment) { set of statements } Eg: Program to print Hello 10 times for(I=0;I<10;I++) { printf(“Hello”); }
  • 23. • The syntax of do while loop do { set of statements }while(condn); Eg: i=10; Output: do 10987654321 { printf(“%d”,i); i--; }while(i!=0)
  • 24. if (condition) { stmt 1; //Executes if Condition is true } else { stmt 2; //Executes if condition is false }
  • 25. switch(var) { case 1: //if var=1 this case executes stmt; break; case 2: //if var=2 this case executes stmt; break; default: //if var is something else this will execute stmt; }
  • 26. • When the break statement is executed inside a loop-statement, the loop-statement is terminated immediately • The execution of the program will continue with the statement following the loop- statement • Syntax : break;
  • 28. •When the continue statement is executed inside a loop-statement, the program will skip over the remainder of the loop-body to the end of the loop. •Syntax Continue;
  • 31. • Array – Group of consecutive memory locations – Same name and type • To refer to an element, specify – Array name – Position number • Format: arrayname[ position number ] – First element at position 0 – n element array named c: • c[ 0 ], c[ 1 ]...c[ n – 1 ]
  • 33. • When declaring arrays, specify – Name – Type of array – Number of elements arrayType arrayName[ numberOfElements ]; – Examples: int c[ 10 ]; float myArray[ 3284 ]; • Declaring multiple arrays of same type – Format similar to regular variables – Example: int b[ 100 ], x[ 27 ];
  • 34. • Initializers int n[ 5 ] = { 1, 2, 3, 4, 5 }; – If not enough initializers, rightmost elements become 0 int n[ 5 ] = { 0 } • All elements 0 – If too many a syntax error is produced syntax error – C arrays have no bounds checking • If size omitted, initializers determine it int n[ ] = { 1, 2, 3, 4, 5 }; – 5 initializers, therefore 5 element array
  • 35. • Initialization – int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; – Initializers grouped by row in braces – If not enough, unspecified elements set to zero int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } }; • Referencing elements – Specify row, then column printf( "%d", b[ 0 ][ 1 ] ); 1 2 3 4 1 0 3 4
  • 36. So far we have used one-dimensional (1D) arrays, but we can also use arrays with 2 or more dimensions. 2D arrays essentially correspond to matrices. Example: • int A; // single variable • int B[6]; // 1D array • int C[3][4]; // 2D array (matrix) • int D[3][4][5]; // 3D array • int E[3][4][5][3]; // 4D array • //etc
  • 39. • A string is a sequence of characters treated as a group • array can be of any length • end of string is indicated by a delimiter, the zero character ‘0’ "A String" A 0gnirtS
  • 40. • String literal values are represented by sequences of characters between double quotes (“) • Examples – “” - empty string – “hello” • “a” versus ‘a’ – ‘a’ is a single character value (stored in 1 byte) as the ASCII value for a – “a” is an array with two characters, the first is a, the second is the character value 0
  • 41. • Allocate an array of a size large enough to hold the string (plus 1 extra value for the delimiter) • Examples (with initialization): char str1[6] = “Hello”; char str2[] = “Hello”; char *str3 = “Hello”; char str4[6] = {‘H’,’e’,’l’,’l’,’o’,’0’};
  • 42. • C provides a wide range of string functions for performing different string tasks • Examples – strlen(str) – To find length of string str – strrev(str) – Reverses the string str as rts – strcat(str1,str2) – Appends str2 to str1 and returns str1 – strcpy(st1,st2) – copies the content of st2 to st1 – strcmp(s1,s2) – Compares the two string s1 and s2 – strcmpi(s1,s2) – Case insensitive comparison of strings • Functions come from the utility library string.h – #include <string.h> to use
  • 44. • A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before you can use it to store any variable address. The general form of a pointer variable declaration is: • type *var-name;
  • 45. • There are few important operations, which we will do with the help of pointers very frequently. • we define a pointer variable • assign the address of a variable to a pointer • finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand. Following example makes use of these operations:
  • 48. • Functions – Modularize a program – All variables declared inside functions are local variables • Known only in function defined – Parameters • Communicate information between functions • Local variables • Benefits of functions – Divide and conquer • Manageable program development – Software reusability • Use existing functions as building blocks for new programs • Abstraction - hide internal details (library functions) – Avoid code repetition
  • 49. • Function definition format return-value-type function-name( parameter-list ) { declarations and statements } – Function-name: any valid identifier – Return-value-type: data type of the result (default int) • void – indicates that the function returns nothing – Parameter-list: comma separated list, declares parameters • A type must be listed explicitly for each parameter unless, the parameter is of type int
  • 50. • Function definition format (continued) return-value-type function-name( parameter-list ) { declarations and statements } – Declarations and statements: function body (block) • Variables can be declared inside blocks (can be nested) • Functions can not be defined inside other functions – Returning control • If nothing returned – return; – or, until reaches right brace • If something returned – return expression;
  • 51. • Call by value – Copy of argument passed to function – Changes in function do not effect original – Use when function does not need to modify argument • Avoids accidental changes • Call by reference – Passes original argument – Changes in function effect original – Only used with trusted functions
  • 52. • Recursive functions – Functions that call themselves – Can only solve a base case – Divide a problem up into • What it can do • What it cannot do – What it cannot do resembles original problem – The function launches a new copy of itself (recursion step) to solve what it cannot do – Eventually base case gets solved • Gets plugged in, works its way up and solves whole problem
  • 53. • Example: factorials – 5! = 5 * 4 * 3 * 2 * 1 – Notice that • 5! = 5 * 4! • 4! = 4 * 3! ... – Can compute factorials recursively – Solve base case (1! = 0! = 1) then plug in • 2! = 2 * 1! = 2 * 1 = 2; • 3! = 3 * 2! = 3 * 2 = 6;
  • 55. • A structure is a collection of variables under a single name. These variables can be of different types, and each has a name which is used to select it from the structure. A structure is a convenient way of grouping several pieces of related information together.
  • 56. • Structures are user defined data types • It is a collection of heterogeneous data • It can have integer, float, double or character data in it • We can also have array of structures struct <<structname>> { members; }element; We can access element.members;
  • 57. •Compound data: •A date is – an int month and – an int day and – an int year
  • 58. • The typedef operator is used for creating alias of a data type • For example I have this statement typedef int integer; Now I can use integer in place of int i.e instead of declaring int a;, I can use integer a; This is applied for structures too.
  • 59. • typedef struct student • { • int id; • Char name[10]; • }s; • Now I can put • s s1,s2;
  • 60. • A union value doesn’t “know” which case it contains •Choices: •An element is – an int i or – a char c union AnElt { int i; char c; } elt1, elt2; elt1.i = 4; elt2.c = ’a’; elt2.i = 0xDEADBEEF; if (elt1 currently has a char) …
  • 62. Symbolic constants #define PI 3.1415926535 Macros with arguments for emulating inlining #define min(x,y) ((x) < (y) ? (x) : (y)) Conditional compilation #ifdef __STDC__ File inclusion for sharing of declarations #include “myheaders.h”
  • 63. Header file dependencies usually form a directed acyclic graph (DAG) How do you avoid defining things twice? Convention: surround each header (.h) file with a conditional: #ifndef __MYHEADER_H__ #define __MYHEADER_H__ /* Declarations */ #endif