Class Presentation 1
Class Presentation 1
In 1960, at Cambridge University at USA, a powerful and basic language was developed known as B language. Original name of B-Language is Basic Combined Programming Language (BCPL). Afterwards the BCPL was renamed as C Language. Dennis Ritchie had developed C-Language in 1972 at Bell-Laboratories in USA.
# include stdio.h # include math.h Include Block # include string .h main() { Main Block }
main() { /* . Printing begins..*/ printf(I see, I remember); printf(I see,\n I remember !); /* . Printing ends..*/ } Output: I see, I remember I see I remember !
Types of C Constants
C Constants
Primary Constants
Secondary Constants
C Keywords
auto double if static break struct case else int static case enum long switch char extern near typedef const float register union continue far return unsinged default for short void do goto signed while
C Data Types
C supports three classes of data types: 1. Primary data types. 2. Derived data types. 3. User defined data types. Primary data types 1. Integer type: signed : int, short int, long int. unsigned: unsinged int, unsinged short int, unsinged long int. 2. Character type: char, singed char, unsinged char. 3. Floating point type: float, double, long double.
Declaration of Variables
data-type v1,v2,.vn; v1,v2vn are the names of variables, variables are separated by commas. A declaration statement must end with a semicolon. Example: int count; int number, total; (multiple) double ratio;
Derived data types such as arrays, functions, structures and pointers. User Defined type declaration 1. typedef type identifier; where type refers to an existing data type and identifier refers to the new name given to the data type. Example: typedef int units; typedef float marks; 2. enum identifier {value1, value2, ..value n} The identifier is a user defined enumerated data type which can be used to declare variables that can have one of the values enclosed with in the braces.
Global variable can be used in all the functions in the program. It need not be declared in other functions. A global variable is also known as an external variable. The variable i, balance and sum are called local variables because they are declared inside function. Local variables are visible and meaningful only inside the function in which they are declared. They are not known to other functions. Note: i has been declared in both the functions, any change in the value of i in one function does not effect its value in the other.
register
Program: main() { float x, p; double y, q; Unsigned k; int m=54321; long int n= 1234567890; x=1.234567890000; y=9.87654321; k=54321; p=q=1.0; Printf(m=%d\n,m); Print(n=%ld\n,n); Printf(x=%.12lf\n,x); Printf(x=%f\n,x); Printf(y=%.12lf\n,y); Printf(x=%lf\n,x); Printf(y=%u p=%f q=%.12lf\n,k,p,q);
output: (garbage value) m= -11215 (16 bit, max store 32767) n= 1234567890 x= 1.234567880630 x= 1.234568 y=9.876543210000 y=9.876543 } k=5432 p=1.000000
#include<stdio.h> main() { char answer; printf(would you like to know my name?\n) printf(Type Y for yes and N for No:); answer = getchar(); if(answer = = Y || answer == y) printf(\n My name is BUSY BEE\n); else printf(\n you are good for nothing); }
islower(c)
isprint(c) ispunct(c) isspace(c) isupper(c)
Writing a Character
Syntax: putchar (variable_name);
Where variable_name is a type char variable containing a character. This statement displays the character contained in the variable_name at the terminal. Ex: answer =Y; putchar (answer);
#include<stdio.h> #include<ctype.h> main() { char alphabet; printf(enter an alphabet); putchar(\n); /* move to next line */ alphabet = getchar(); if(islower(alphabet)) putchar(toupper(alphabet)); /* Reverse and display */ else putchar(tolower(alphabet)); /* Reverse and display */ Output: 1. Enter an alphabet 2. Enter an alphabet a Q A q
%c %d %e %f %h %i %o %s %u %x %*.+
read a single character read a decimal integer read a floating point value read a floating point value read a shot integer read a decimal, hexadecimal or octal integer read an octal integer read a string read an unsigned decimal integer read a hexadecimal integer read a string of word(s)
Formatted output
Printf(control string, arg1, arg2,.,argn); Output of Integer Numbers: Format Output 9 8 7 6 printf(%d, 9876) 9 8 7 6 printf(%6d, 9876) 9 8 7 6 printf(%-6d, 9876) 0 0 9 8 7 6 printf(%06d, 9876)
Output of Real Numbers: y=98.7654 Format printf(%7.4f, y) printf(%7.2f, y) printf(%-7.2f, y) printf(%f, y) Printf(%10.2e,y) Printf(%-10.2e,y)
Output
9 8 . 7 6 5 4 9 8 . 7 7
9 8 . 7 7
9 8 . 7 6 5 4 9 . 8 8 e + 0 1 9 . 8 8 e + 0 1
Printing of a Single Character: for character print %c is used. for string print %s is used.
main() { char x = A; char name[20] = ANIL KUMAR GUPTA; printf(output of characters); printf(%c\n%3c\n%5c\n, x,x,x); printf(output of strings); printf(%s\n, name); printf(%20s\n, name); printf(%20.10s\n, name); printf(%.5s\n, name); printf(%-20.10s\n, name); }
Arithmetic operators
Operator Meaning
+ -
*
/ %
Multiplication
Division Modulo division
Integer Arithmetic: if a=14 and b=4 a-b = 10 a+b = 18 a*b = 16 a/b = 3 a%b = 2 During integer division, if both the operands are of the same sign, the result is truncated towards zero. If one of them is negative, the direction of truncation is implementation dependent. 6/7 =0 and -6/-7=0 but -6/7 may be zero or -1 (Machine dependent)
Similarly, during modulo division, the sign of the result is always the sign of the first operand. -14%3 = -2 -14% -3 = -2 14%-3 = 2 Real Arithmetic: if x, y and z are floats, x=6.0/7.0 = 0.857143 y=1.0/3.0 = 0.333333 z= -2.0/3.0 = -0.666667 Mixed-mode Arithmetic : When one of the operands is real and the other is integer, the expression is called a mixed mode arithmetic expression. If either operand is of the real type, then only the real operation is performed and the result is always a real number. 15/10.0 = 1.5 15/10 = 1
Relational operators
Operator Meaning
Is less than Is less than or equal to Is greater than Is greater than or equal to Is equal to Is not equal to
Logical operators
&& Meaning logical AND
|| !
OR NOT
Ex:
Relative precedence of the relational and logical operators is as follows: Highest ! >, >= , < , <= == , != && Lowest ||
Assignment Operators
Assignment operators are used to assign the result of an expression to a variable.
Statement with simple assignment operator a=a+1 a=a-1 a=a*(n+1) a=a/(n+1) a=a%b
output: 2 4 16
Conditional operators
Syntax: exp1? exp2 : exp3 exp1 is evaluated first.
If it is nonzero(true), then the expression exp2 is evaluated and becomes the value of the expression . If exp1 is false, exp3 is evaluated and its value becomes the value of the expression
Ex:
Bitwise operators
These operators are used for testing the bits, or shifting them right or left. Bitwise operators may not be applied to float or double .
Operator & | Meaning Bitwise AND Bitwise OR
^
<< >>
Bitwise exclusive OR
Shift left Shift right
Special operators
The comma operator:
The comma operator can be used to link the related expressions together. Ex: value =(x=10, y=5, x+y); The sizeof operator: The sizeof is a compile time operator and, when used with an operand, it returns the number of bytes the operand occupies. Ex: m=sizeof(sum);
Operator Precedence
Precedence Associates Operator (type) * / % + << >> < <= > >= == != & Tokens Class casts multiplicative additive left, right shift relational equality/ineq. bitwise and unary binary binary binary binary binary binary 14 13 12 11 10 9 8 right-to-left left-to-right left-to-right left-to-right left-to-right left-to-right left-to-right
^
| && || ?: = += -= *= /= %= &= ^= |= <<= >>= ,
bitwise xor
bitwise or logical and logical or conditional
binary
binary binary binary ternary
7
6 5 4 3
left-to-right
left-to-right left-to-right left-to-right right-to-left
assignment
binary
right-to-left
sequential eval.
binary
left-to-right
Operator precedence
Precedence Associates Operator names, literals a[k] f(...) . -> ++ -(type){init} ++ -Tokens sizeof ~ ! Class
simple tokens subscripting function call direct selection indirect selection increment, decrement compound literal increment, decrement size bitwise not logical not
primary postfix postfix postfix postfix postfix postfix prefix unary unary unary 15 16
n/a left-to-right left-to-right left-to-right left to right left-to-right left-to-right right-to-left right-to-left right-to-left right-to-left
- +
& *
negation, plus
address of indirection (dereference)
unary
unary unary
right-to-left
right-to-left right-to-left
Casting Operator
Convert from one data type to another data type. Ex: main() { int i=10; float g=50.56; i=g; /* i=(int)g here float value convert to integer*/ printf(%d, i); } Output: 50 (int), (float), (char), (double)
If else statement
/* calculation of gross salary*/ main() { float bs, gs, da, hra; printf(Enter basic salary); scanf(%f, &bs); if(bs<1500) { hra = bs * 10/100; da = bs * 90/100; } else { hra = 500; da = bs*98/100; } gs = bs+hra+da; printf(gross salary=Rs.%f, gs); }
/*Nested if elses */ main() { int i; printf(enter either 1 or 2); scanf(%d, &i); if(i==1) printf(enter 1); else { if(i==2) printf(enter 2); else printf(HI); } }
Forms of if
a. if (condition) do this; b. if(condition) { do this; and this; } c. if(condition) do this; else do this;
Using Logical operators main() { int m1,m2,m3,m4,m5,per; printf(enter marks in five subjects); scanf(%d%d%d%d%d, &m1,&m2,&m3,&m4,&m5); per=(m1+m2+m3+m4+m5)/5; if(per > = 60) printf( first division); if((per > = 50) && (per < 60) ) printf( second division); if((per > = 40) && (per < 50) ) printf( third division); if(per < 40) printf(Fail); }
1.While statement The While loop assists in the program where you want to carry out an activity for a certain number of times. Example:- calculating gross salaries of ten people or converting temperatures from centigrade to Fahrenheit for 15 different cities Syntax: While (condition) { Statement; }
PROGRAM EXAMPLE: #include <stdio.h> main() { int p,n,count; float r,si; count = 1; while (count <=3) { printf("The values of p, n and r); scanf(%d%d%f, &p,&n,&r); si = p * n* r/100; printf( "Simple interest= %f , si); count = count+1; }
The condition to be tested may use the relational operators: Example:1. While (I <= 10) 2. While (I <=10 && j <=15) 3. While (j >10 && (b <15 || c<20) While(i<=10) i=i+1; is same as While(i<=10) { i=i+1; }
The do-While Loop Syntax: do { this; and this; and this; and this; }while (this condition is true); The do-While loop execute its statements at least once even if the condition fails for the first time.
If the condition fails the printf will not be executed even once.
Program Example 2: #include<stdio.h> main() { do { printf(Hello there); }while(4<1); } In this program the printf would be executed once, since first the body of the loop is executed and then the condition is tested.
The for loop specifies three elements about the loop in one single line. Setting a loop counter to an initial value. Testing the loop counter to determine whether its value has reached the number of repetitions desired. Increasing the value of loop counter each time the program segment within the loop has been executed. Syntax: for (initialize counter; test counter; increment counter) { do this; and this; }
For Loop
Program example: Calculate the simple interest: #include <stdio.h> main() { int p,n,count; float r,si; for (count = 1; count <=3; count = count + 1) { printf("The values of p, n and r); scanf(%d%d%f, &p,&n,&r); si = p * n* r/100; printf( "Simple interest= %f , si); }
a. main() { int i; for(i=1; i<=10;) { printf(%d, i); i=i+1; } } Here, the incrementation is done within the body of the for loop and not in the for statement.
b. main() { int i = 1; for(; i<=10; i=i+1) { printf(%d, i); } } Here, the initialisation is done in the declaration statement itself, but still the semicolon before the condition necessary.
d. main() { int i; for(i=0; i++<10; ) { printf(%d, i); } } Here, the comparison as well as the incrementation is done through the same statement, i++ < 10.
#include<stdio.h> main() { int r,c,sum; for (r =1; r<=3; r++) { for (c=1; c<=2; c++) {
output: R=1 c=1 sum =2 R=1 c=2 sum =3 R=2 c=1 sum =3 R=2 c=1 sum =4 R=3 c=1 sum =4 R=3 c=2 sum =5
Multiple initialisations in the for loop for( i=1, j=2; j<=10; j++)
The Odd Loop : /* Execution of a loop an unknown number of times*/ #include <stdio.h> main() { char another =y; int num; while(another == y) { printf(Enter a number); scanf(%d, # printf(Square of %d is %d, num , num * num); printf(Do you want to enter another number y/n); scanf(%c, &another); } } In this program the while loop would keep getting executing till the user continuous to answer y.
main() { int i=1, j=1; while(i++<=100) { while(j++<=200) { if(j==150) break; else printf(%d\n %d\n",i,j); } } } In this program when j equals 150, break takes the control outside the inner while only, since it is placed inside the inner while.
main() output: { 1 2 int i, j; 2 1 for (i =1; i<=2; i++) { for (j =1; j<=2; j++) { if(i==j) continue; printf(%d%d, i,j); } } } when the value of i equals that of j, the continue statement takes the control to the for loop(inner) bypassing rest of the statements pending ececution in the for loop(inner)
switch ( integer expression ) { case constant1 : statement(s) break ; case constant2 : statement(s) break ; ... default : statement(s) break ; }
The last statement of each case in the switch should almost always be a break. The break causes program control to jump to the closing brace of the switch structure. Without the break, the code flows into the next case. This is almost never what you want. A switch statement will compile without a default case, but always consider using one.
switch ( day ) { case 0: printf (Sunday\n) ; break ; case 1: printf (Monday\n) ; break ; case 2: printf (Tuesday\n) ; break ; case 3: printf (Wednesday\n) ; break ; case 4: printf (Thursday\n) ; break ; case 5: printf (Friday\n) ; break ; case 6: printf (Saturday\n) ; break ; default: printf (Error -- invalid day.\n) ; break ; }
/* This program associates a letter grade with a message appropriate to the score. */ #include <stdio.h> int main ( ) { char grade ; printf ("Enter your current letter grade\n") ; grade = getchar ( ) ; switch (grade) { case ('a') : case ('A') : printf ("Good Job!\n") ; case ('b') : case ('B') : printf ("Pretty good.\n") ;
case ('c') : case ('C') : printf ("Better get to work.\n") ; case ('d') : case ('D') : printf ("You are in trouble.\n") ; default : printf ("You are failing!!\n") ; /* End of switch-case structure */ } /* End of main program /* The following results are produced when the user enters an "A" as input to the program prompt. */ Good Job! Pretty good. Better get to work. You are in trouble. You are failing! }
The problems with the previous program can be corrected by use of the break statement. It can be used in either a repetition structure or a selection structure to break out of (that is, to exit from) the structure. The syntax is:
break ;
The following program is the previous one with the addition of the break statements.
#include <stdio.h> main ( ) { int i=2; switch(i) { case 1: printf(I am in case 1); break; case 2: printf(I am in case 2); break; case 3: printf(I am in case 3); break; default: printf(I am in default); } } Output : I am in case 2
Functions
What is a Function? Function is a self contained block of statements that perform a coherent task of some kind. Every C program can be a thought of the collection of functions. main( ) is also a function. Any c program contains at least one function. If a program contains only one function, it must be main(). There is no limit on the number of functions that might be present in a c program. Each function in a program is called in the sequence specified by the function call in main().
Types of Functions Library functions. These are the in -built functions of C library. These are already defined in header files. e.g. printf( ); is a function which is used to print at output. It is defined in stdio.h file . User defined functions. Programmer can create their own function in C to perform specific task.
User defined functions #include<stdio.h> main() { message(); printf(cry, and you stop the monotony); } message() { printf(smile, and the world smiles with you); } Output: smile, and the world smiles with you cry, and you stop the monotony
main() {
output: I am In main I am in italy I am in brazil I am in argentina I am back in italy iam finally back in main
Summarization
C Program is a collection of one or more functions. A function gets called when its name is followed by a semicolon. e.g. main( ) { fun( ); } fun( ) { Statement1; statement2; statement3; }
A function is defined when function name is followed by a pair of braces in which one or more statements present.
Any function can be called by any other function. main( ) { printf(II am in main); fun( ); } fun( ) { Printf(I am in fun); main( ); } This will run in infinity.
A function can be called by number of times. e.g. main( ) { printf(I am in main); fun( ); fun( ); fun( ); } fun( ) { printf(I am in fun); }
A function can call itself, it is called as a recursion e.g. main ( ) { printf(I am in main); main( ); } A function can be called from another function but can not be defined in another function. It should be defined outside of the main.
The order in which the functions are defined in a program and the order in which they get called need not necessarily be same. main() { message1(); message2(); } message2() { printf(smile, and the world smiles with you); } message1(); { printf(cry, and you stop the monotony); }
Why use functions? Writing functions avoids rewriting of the same code again and again in the program. Using a function it becomes easier to write program to keep track of what they are doing.
Returning a value
The keyword return to used to return value from function which is present in the parenthesis of return. executing return statement it immediately transfers control back to the main program. main( ) { int a = 30, j = 14; int k; k =addin(a, j); Printf(%d, k); } int addin(int x, int y) output: 45
{
There is no restriction on the number of return statements that may be present in a function. Also, the return statement need not always be present at the end of the called function. Ex: fun() { char ch; printf(enter any alphabet); scanf(%c,&ch); if(ch>=65 && ch<=90) return (ch); else return (ch+32); } In this function different return statements will be executed depending on whether ch is capital or not.
Whenever the control returns from the function some value is definitely returned. It should be accepted in the calling program. e.g. int sum; sum = calsum(a,b,c);
here the value returned by calsum must be of type int. Some valid return statements. return a; /*a is a variable name */ return (23); return (15.32); return (v); return; If you are not returning any value from a function they it should be declared as void. (void is a keyword). e.g. void display( ) display is not returning any value.
A function can return only one value at a time. Thus, the following statements are invalid. return(a,b); return(x,12); Any C function by default returns an integer value. More specifically, whenever a call is made to a function, the compiler assumes that this function would return value of type int.
Declaring Functions Requires prototype & function itself a. Prototype (before function itself) Tells compiler 1. number & type of arguments passed in 2. Type of value returned E.g., int maximum (int, int); or int maximum (int a, int b); /* a & b are ignored by the compiler */
Function itself Format: type function_name (parameter list); Parameter list > type and name Must return a value of specified type unless type is void. Must be declared before it is used Function call Must include appropriate arguments
#include <stdio.h> int maximum (int, int); Function prototype. int maximum (int a, int b) { if (a > b) return a; else return b; } void main () { int x, y, z; printf (Enter 2 intergers: ); scanf (%d %d, &x, &y); z = maximum(x,y); printf(\nThe maximum is %d\n,z); }
Call by value and call by Reference An introduction to Pointers: Ex: int i = 3; This declaration tells the c compiler to: 1. Reserve space in memory to hold the integer value. 2. Associate the name I with this memory location. 3. Store the value 3 at this location. i location name 3 value at location 6485 location number The computer has selected memory location 6485 as the place to store the value 3. the location number 6485 is not fixed for value 3.
We can print this address number through the following program: main() { int i = 3; Printf(address of i=%u, &i); printf(value of i= %d, i); } Output: address of i = 6485 value of i = 3; & used in this statement is Cs address of operator. The expression &i returns the address of the variable i.
The other pointer operator available in C is * called value at address operator. It gives the value stored at a particular address. The value at address operator is also called indirection operator. Ex: main() { int i=3; Printf(address of i=%u, &i); printf(value of i= %d, i); printf(value of i= %d,*(& i)); } Output: address of i = 6485 value of i = 3; value of i = 3;
the printing the value of *(&i) is same as printing the value of i. the expression &i gives the address of the variable i. this address can be collected in a variable, by saying, j=&i; j is not an ordinary variable like any other integer variable. It is a variable which contains the address of other variable. i j (j value is is address)
3 6485
6485
3276
Ex: main() { int i=3; int *j; j=&i; printf(address of i=%u, &i); printf(address of i=%u, j); printf(address of j=%u, &j); printf(value of j= %u, j); printf(value of i= %d, i); printf(value of i= %d, *(&i)); printf(value of i= %d, *j); }
output: address of i = 6485 address of i = 6485 address of j = 3276 value of j = 6485 value of i = 3 value of i = 3 value of i = 3
Back to Function calls Arguments can generally be passed to function in one of the two ways: 1. sending the values of the arguments 2. sending the addresses of the arguments In the first method the value of each of actual arguments in the calling function is copied into corresponding formal arguments of the called function. With this method the changes made to the formal arguments in the called function have no effect on the values of actual arguments in the calling function
/* interchange the values */ main() { int x=50, y=70; interchange(x,y); printf(x=%d y=%d,x,y); } interchange(x1,y1) output: int x1,y1; x1 = 70 y1= 50 { x = 50 y =70 int z1; z1=x1; x1=y1; y1=z1; printf(x1=%d y1=%d,x1,y1); }
In second method (call by reference) the address of actual arguments in the calling function are copied into formal arguments of the called function. This means that using these addresses we would have an access to the actual arguments and here we would be able to manipulate them.
main() { int x=50, y=70; interchange(&x,&y); printf(x=%d y=%d,x,y); } interchange(x1,y1) int *x1,*y1; { int z1; z1=*x1; *x1=*y1; *y1=z1; printf(*x=%d *y=%d,x1,y1); } output: *x=70 *y=50 x=70 y=50
Recursion
A function is called recursive if a statement with in the body of a function calls the same function. Sometimes called circular definition, recursion is thus the process of defining something in terms of itself.
int fact(int n) { int x,y; if(n==0) return 1; x=n-1; y=fact(x); return n*y; } output : Enter the integer whose factorial value you want 3 The factorial value is 6
void main() { int x; printf(\nEnter the integer whose factorial value you want ); scanf(%d,&x); printf(\nThe factorial value is:-%d,fact(x)); }