C Language Thursday, September 1, 2011 Avik Dhupar
Overview of C C is developed by Dennis Ritchie C is a structured programming language C supports functions that enables easy maintainability of code, by breaking large file into smaller modules Comments in C provides easy readability C is a powerful language Thursday, September 1, 2011
Program structure A sample C Program #include<stdio.h> int main() { --other statements // Comments after double slash } Thursday, September 1, 2011
Header files 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 Thursday, September 1, 2011
Main function 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 Thursday, September 1, 2011
Writing the first program #include<stdio.h> int main() { printf(“Hello”); return 0; } This program prints Hello on the screen when we execute it Thursday, September 1, 2011
Running a C Program 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. Thursday, September 1, 2011
Comments in C Single line comment // (double slash) Termination of comment is by pressing enter key Multi line comment /*….  …… .*/ This can span over to multiple lines Thursday, September 1, 2011
Data types in C Primitive data types int, float, double, char Aggregate data types Arrays come under this category Arrays can contain collection of int or float or char or double data User defined data types Structures and enum fall under this category. Thursday, September 1, 2011
Variables 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 Thursday, September 1, 2011
Variable names- Rules 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. Thursday, September 1, 2011
Input and Output Input scanf(“%d”, & a); Gets an integer value from the user and stores it under the name “a” Output printf(“%d”,a); Prints the value present in variable a on the screen Thursday, September 1, 2011
For loops 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”); } Thursday, September 1, 2011
While loop The syntax for while loop while(condn) { statements; } Eg: a=10; while(a != 0) Output: 10987654321 { printf(“%d”,a); a--; } Thursday, September 1, 2011
Do While loop 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) Thursday, September 1, 2011
Conditional statements if (condition)   { stmt 1; //Executes if Condition is true } else { stmt 2; //Executes if condition is false } Thursday, September 1, 2011
Conditional statement 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; } Thursday, September 1, 2011
Operators Arithmetic (+,-,*,/,%) Relational (<,>,<=,>=,==,!=) Logical (&&,||,!) Bitwise (&,|) Assignment (=) Compound assignment(+=,*=,-=,/=,%=,&=,|=) Shift (right shift >>, left shift <<) Thursday, September 1, 2011
String functions 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 Thursday, September 1, 2011
Numeric functions pow(n,x) – evaluates n^x ceil(1.3) – Returns 2 floor(1.3) – Returns 1 abs(num) – Returns absolute value log(x)  - Logarithmic value sin(x) cos(x) tan(x) Thursday, September 1, 2011
Procedures Procedure is a function whose return type is void Functions will have return types int, char, double, float or even structs and arrays Return type is the data type of the value that is returned to the calling point after the called function execution completes Thursday, September 1, 2011
Functions and Parameters Syntax of function Declaration section <<Returntype>> funname(parameter list); Definition section <<Returntype>> funname(parameter list) { body of the function } Function Call Funname(parameter); Thursday, September 1, 2011
Example function #include<stdio.h> void fun(int a); //declaration int main() { fun(10); //Call } void fun(int x) //definition { printf(“%d”,x); } Thursday, September 1, 2011
Actual and Formal parameters Actual parameters are those that are used during a function call Formal parameters are those that are used in function definition and function declaration Thursday, September 1, 2011
Arrays Arrays fall under aggregate data type Aggregate – More than 1 Arrays are collection of data that belong to same data type Arrays are collection of homogeneous data Array elements can be accessed by its position in the array called as index Thursday, September 1, 2011
Arrays Array index starts with zero The last index in an array is num – 1 where num is the no of elements in a array int a[5] is an array that stores 5 integers a[0] is the first element where as a[4] is the fifth element We can also have arrays with more than one dimension float a[5][5] is a two dimensional array. It can store 5x5 = 25 floating point numbers The bounds are a[0][0] to a[4][4] Thursday, September 1, 2011
Structures 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; Thursday, September 1, 2011
Structures struct Person { int id; char name[5]; }P1; P1.id = 1; P1.name = “vasu”; Thursday, September 1, 2011
Type def 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. Thursday, September 1, 2011
Pointers Pointer is a special variable that stores address of another variable Addresses are integers. Hence pointer stores integer data Size of pointer = size of int Pointer that stores address of integer variable is called as integer pointer and is declared as int *ip; Thursday, September 1, 2011
Pointers Pointers that store address of a double, char and float are called as double pointer, character pointer and float pointer respectively. char *cp float *fp double *dp; Assigning value to a pointer int *ip = &a; //a is an int already declared Thursday, September 1, 2011
Examples int a; a=10; //a stores 10 int *ip; ip = &a; //ip stores address of a (say 1000) ip : fetches 1000 *ip  :  fetches 10 * Is called as dereferencing operator Thursday, September 1, 2011
Call by Value Calling a function with parameters passed  as values int a=10; void fun(int a) fun(a); { defn; } Here fun(a) is a call by value. Any modification done with in the function is local to it and will not be effected outside the function Thursday, September 1, 2011
Call by reference Calling a function by passing pointers as parameters (address of variables is passed instead of variables) int a=1; void fun(int *x) fun(&a); { defn; } Any modification done to variable a will effect outside the function also Thursday, September 1, 2011
Example program – Call by value #include<stdio.h> void main() { int a=10; printf(“%d”,a); a=10 fun(a); printf(“%d”,a); a=10 } void fun(int x) { printf(“%d”,x) x=10 x++; printf(“%d”,x); x=11 } Thursday, September 1, 2011
Explanation Thursday, September 1, 2011
Example Program – Call by reference #include<stdio.h> void main() { int a=10; printf(“%d”,a); a=10 fun(a); printf(“%d”,a); a=11 } void fun(int x) { printf(“%d”,x) x=10 x++; printf(“%d”,x); x=11 } Thursday, September 1, 2011
Explanation a and x are referring to same location. So value will be over written. Thursday, September 1, 2011
Conclusion Call by value => copying value of variable in another variable. So any change made in the copy will not affect the original location. Call by reference => Creating link for the parameter to the original location. Since the address is same, changes to the parameter will refer to original location and the value will be over written. Thursday, September 1, 2011

Basics of C programming

  • 1.
    C Language Thursday,September 1, 2011 Avik Dhupar
  • 2.
    Overview of CC is developed by Dennis Ritchie C is a structured programming language C supports functions that enables easy maintainability of code, by breaking large file into smaller modules Comments in C provides easy readability C is a powerful language Thursday, September 1, 2011
  • 3.
    Program structure Asample C Program #include<stdio.h> int main() { --other statements // Comments after double slash } Thursday, September 1, 2011
  • 4.
    Header files Thefiles 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 Thursday, September 1, 2011
  • 5.
    Main function Thisis 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 Thursday, September 1, 2011
  • 6.
    Writing the firstprogram #include<stdio.h> int main() { printf(“Hello”); return 0; } This program prints Hello on the screen when we execute it Thursday, September 1, 2011
  • 7.
    Running a CProgram 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. Thursday, September 1, 2011
  • 8.
    Comments in CSingle line comment // (double slash) Termination of comment is by pressing enter key Multi line comment /*…. …… .*/ This can span over to multiple lines Thursday, September 1, 2011
  • 9.
    Data types inC Primitive data types int, float, double, char Aggregate data types Arrays come under this category Arrays can contain collection of int or float or char or double data User defined data types Structures and enum fall under this category. Thursday, September 1, 2011
  • 10.
    Variables Variables aredata 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 Thursday, September 1, 2011
  • 11.
    Variable names- RulesShould 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. Thursday, September 1, 2011
  • 12.
    Input and OutputInput scanf(“%d”, & a); Gets an integer value from the user and stores it under the name “a” Output printf(“%d”,a); Prints the value present in variable a on the screen Thursday, September 1, 2011
  • 13.
    For loops Thesyntax 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”); } Thursday, September 1, 2011
  • 14.
    While loop Thesyntax for while loop while(condn) { statements; } Eg: a=10; while(a != 0) Output: 10987654321 { printf(“%d”,a); a--; } Thursday, September 1, 2011
  • 15.
    Do While loopThe syntax of do while loop do { set of statements }while(condn); Eg: i=10; Output: do 10987654321 { printf(“%d”,i); i--; }while(i!=0) Thursday, September 1, 2011
  • 16.
    Conditional statements if(condition) { stmt 1; //Executes if Condition is true } else { stmt 2; //Executes if condition is false } Thursday, September 1, 2011
  • 17.
    Conditional statement 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; } Thursday, September 1, 2011
  • 18.
    Operators Arithmetic (+,-,*,/,%)Relational (<,>,<=,>=,==,!=) Logical (&&,||,!) Bitwise (&,|) Assignment (=) Compound assignment(+=,*=,-=,/=,%=,&=,|=) Shift (right shift >>, left shift <<) Thursday, September 1, 2011
  • 19.
    String functions 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 Thursday, September 1, 2011
  • 20.
    Numeric functions pow(n,x)– evaluates n^x ceil(1.3) – Returns 2 floor(1.3) – Returns 1 abs(num) – Returns absolute value log(x) - Logarithmic value sin(x) cos(x) tan(x) Thursday, September 1, 2011
  • 21.
    Procedures Procedure isa function whose return type is void Functions will have return types int, char, double, float or even structs and arrays Return type is the data type of the value that is returned to the calling point after the called function execution completes Thursday, September 1, 2011
  • 22.
    Functions and ParametersSyntax of function Declaration section <<Returntype>> funname(parameter list); Definition section <<Returntype>> funname(parameter list) { body of the function } Function Call Funname(parameter); Thursday, September 1, 2011
  • 23.
    Example function #include<stdio.h>void fun(int a); //declaration int main() { fun(10); //Call } void fun(int x) //definition { printf(“%d”,x); } Thursday, September 1, 2011
  • 24.
    Actual and Formalparameters Actual parameters are those that are used during a function call Formal parameters are those that are used in function definition and function declaration Thursday, September 1, 2011
  • 25.
    Arrays Arrays fallunder aggregate data type Aggregate – More than 1 Arrays are collection of data that belong to same data type Arrays are collection of homogeneous data Array elements can be accessed by its position in the array called as index Thursday, September 1, 2011
  • 26.
    Arrays Array indexstarts with zero The last index in an array is num – 1 where num is the no of elements in a array int a[5] is an array that stores 5 integers a[0] is the first element where as a[4] is the fifth element We can also have arrays with more than one dimension float a[5][5] is a two dimensional array. It can store 5x5 = 25 floating point numbers The bounds are a[0][0] to a[4][4] Thursday, September 1, 2011
  • 27.
    Structures Structures areuser 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; Thursday, September 1, 2011
  • 28.
    Structures struct Person{ int id; char name[5]; }P1; P1.id = 1; P1.name = “vasu”; Thursday, September 1, 2011
  • 29.
    Type def Thetypedef 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. Thursday, September 1, 2011
  • 30.
    Pointers Pointer isa special variable that stores address of another variable Addresses are integers. Hence pointer stores integer data Size of pointer = size of int Pointer that stores address of integer variable is called as integer pointer and is declared as int *ip; Thursday, September 1, 2011
  • 31.
    Pointers Pointers thatstore address of a double, char and float are called as double pointer, character pointer and float pointer respectively. char *cp float *fp double *dp; Assigning value to a pointer int *ip = &a; //a is an int already declared Thursday, September 1, 2011
  • 32.
    Examples int a;a=10; //a stores 10 int *ip; ip = &a; //ip stores address of a (say 1000) ip : fetches 1000 *ip : fetches 10 * Is called as dereferencing operator Thursday, September 1, 2011
  • 33.
    Call by ValueCalling a function with parameters passed as values int a=10; void fun(int a) fun(a); { defn; } Here fun(a) is a call by value. Any modification done with in the function is local to it and will not be effected outside the function Thursday, September 1, 2011
  • 34.
    Call by referenceCalling a function by passing pointers as parameters (address of variables is passed instead of variables) int a=1; void fun(int *x) fun(&a); { defn; } Any modification done to variable a will effect outside the function also Thursday, September 1, 2011
  • 35.
    Example program –Call by value #include<stdio.h> void main() { int a=10; printf(“%d”,a); a=10 fun(a); printf(“%d”,a); a=10 } void fun(int x) { printf(“%d”,x) x=10 x++; printf(“%d”,x); x=11 } Thursday, September 1, 2011
  • 36.
  • 37.
    Example Program –Call by reference #include<stdio.h> void main() { int a=10; printf(“%d”,a); a=10 fun(a); printf(“%d”,a); a=11 } void fun(int x) { printf(“%d”,x) x=10 x++; printf(“%d”,x); x=11 } Thursday, September 1, 2011
  • 38.
    Explanation a andx are referring to same location. So value will be over written. Thursday, September 1, 2011
  • 39.
    Conclusion Call byvalue => copying value of variable in another variable. So any change made in the copy will not affect the original location. Call by reference => Creating link for the parameter to the original location. Since the address is same, changes to the parameter will refer to original location and the value will be over written. Thursday, September 1, 2011

Editor's Notes

  • #11 We can also declare and define a variable in single shot like this. int a=10;
  • #13 Format specifiers %d is the format specifier. This informs to the compiler that the incoming value is an integer value. Other data types can be specified as follows: %c – character %f – float %lf – double %s – character array (string) Printf and scanf are defined under the header file stdio.h
  • #16 While – Entry controlled loop Do While – Exit controlled loop
  • #20 Header file to be included is string.h
  • #21 Header file to be included math.h
  • #29 For assigning more values we need to create an array of structure element like this Struct Person { Int id; Char name[5]; }P[10]; P[0].id = 1; P[0].name = “saran”; P[1].id = 2; P[1].name = “arya”; And so on till P[9]
  • #30 typedef struct student { int id; Char name[10]; }s; Now I can put s s1,s2; Instead of struct student s1,s2; //In case typedef is missed in struct definition as below struct student { int id; char name[10]; };