Date post: | 26-Nov-2014 |
Category: |
Documents |
Upload: | deepakangadi |
View: | 764 times |
Download: | 1 times |
Introduction to C Program
•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.
There exist three important areas in typical C Program such as:
1. Include Block
2. Function Block
3. Main Block
# .
# .
# .
include stdio h
include math h Include Block
include string h
()
{
}
main
Main Block
Sample program: Printing a Message
main() Function name { start of the
program ………… ………… Program
statements…………
} end of the program
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 !
Constants, Variables and Data Types
• The characters in C are grouped into the following categories:
• Letters, Digits, Special characters and White spaces.
Alphabets A,B,…….Y,ZA,b,…….y,z
Digits 0,1,2,3,4,5,6,7,8,9
Special Symbols ~ ‘ ! @ # % ^ & * () _ - + = | \ { } [ ] : ; “ ‘ < > , . ? /
Types of C Constants
C Constants
Primary Constants Secondary Constants
Integer ConstantReal Constant
Character Constant
ArrayPointer
StructureUnion
Enum etc.
Rules for constructing Integer Constraints
• An integer constant must have at least one digit.• It must not have a decimal point.• It could be either positive or negative.• If no sign precedes an integer constant it is
assumed to be positive.• No commas or blanks are allowed within an
integer constant.• The allowable range for integer constant is
-32768 to +32767.
Rules for constructing Real Constraints
• A real constant must have at least one digit.• It must have a decimal point.• It could be either positive or negative.• No commas or blanks are allowed within a real
constant.• Default sign is positive.
Ex:
426.0
-32.76
-48.5792
Rules for constructing Character Constraints
• The mantissa part and the exponential part should be separated by a letter e.
• The mantissa part may have a positive or negative sign.
• Default sign of mantissa part is positive.• The exponent must have at least one digit which
must be a positive or negative integer. Default sign in positive.
• Range of real constants expresses in exponential form is -3.4e38 to 3.4e38
Ex: +3.2e-5 4.1e8
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 TypesC 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.
Size and Range of data types on a 16-bitType Size(bits) Range
Char or singed char 8 -128 to 127
Unsinged char 8 0 to 255
Int or singed int 16 -32,768 to 32,767
Unsinged int 16 0 to 65535
Short int or singed short int 8 -128 to 127
Unsinged short int 8 0 to 255
Long int or singed long int 32 -2,147,483,648 to 2,147,48
Unsinged long int 32 0 to 4,294,967,295
float 32 3.4E-38 to 3.4+38
double 64 1.7E-308 to 1.7E+308
Long double 80 3.4E -4932 to 1.1E+4932
Declaration of Variables
• data-type v1,v2,….vn; v1,v2……vn 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.
Declaration of storage class• Variables in C can have not only data type but also storage class that
provides information about their location and visibility. • The storage class decides the portion of the program within which
the variables are recognized.
Ex: int m;
main() function1()
{ {
int i; int i;
float balance; float sum;
………. ………..
function1(); }
}
the variable m which has been declared before main is called global variable
• 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.
Storage classes:• auto, register, static and extern. Example: auto int count; register char ch;
static int x; extern long total;• static and external (extern) variables are automatically
initialized to zero. • Automatic (auto) variables contain undefined values
(known as garbage) unless they are initialized explicitly.
Storage class Meaning
auto Local variable known only to the function in which it is declared. Default is auto.
static Local variable which exists and retains its value even after the control is transferred to the calling function.
extern Global variable known to all function in the file.
register Local variable which is stored in the register.
Assigning values to variables• Variable_name = constant; Ex: balance = 75.84;• an assignment statement implies that the value of the
variable on the left of the equal sign is set equal to the value of the quantity on the right.
Ex: year = year+1;
data_type variable_name = constsnt;
Ex: double balance = 75.84;
Initialization : the process of giving initial values to variables is called initialization.
p = q = s =0; (multiple assignments)
Program: main()
{
float x, p;
double y, q;
Unsigned k;
int m=54321;
long int n= 1234567890;
x=1.234567890000;
y=9.87654321; output:
k=54321;
p=q=1.0; (garbage value)
Printf(“m=%d\n”,m); m= -11215 (16 bit, max store 32767)
Print(“n=%ld\n”,n); n= 1234567890
Printf(“x=%.12lf\n”,x); x= 1.234567880630
Printf(“x=%f\n”,x); x= 1.234568
Printf(“y=%.12lf\n”,y); y=9.876543210000
Printf(“x=%lf\n”,x); y=9.876543
Printf(“y=%u p=%f q=%.12lf\n”,k,p,q); } k=5432 p=1.000000
q=1.000000000000
Reading Data from KeyboardSyntax: scanf(“control string”, &variable1,&variable2,……..);
Ex: scanf(“%d”, &number);
main()
{
int number;
printf(“enter an integer number\n”);
scanf(“%d”, &number);
if(number < 100)
printf(“your number is smaller than 100”);
else
printf(“your number contains more than two digits”);
}
Managing Input and Output Operations
Reading a character:
getchar: Reading a single character can be done by using the function getchar.
syntax: variable_name = getchar();
Ex: char name;
name = getchar();
Will assign the character ‘H’ to the variable name when we press the key H on the keyboard. Since getchar is a function, it requires a set of parentheses as shown.
#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”);
}
Character Test FunctionFunction Test
isalnum(c) Is c an alphanumeric character?
isalpha(c) Is c an alphabetic character?
isdigit(c) Is c a digit ?
islower(c) Is c lower case letter ?
isprint(c) Is c a printable character ?
ispunct(c) Is c a punctuation mark ?
isspace(c) Is c a white space character ?
isupper(c) Is c an upper case letter ?
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
Commonly used scanf Format codesCode Meaning
%c read a single character%d read a decimal integer%e read a floating point value%f read a floating point value%h read a shot integer%i read a decimal, hexadecimal or octal integer%o read an octal integer%s read a string%u read an unsigned decimal integer %x read a hexadecimal integer%[….] read a string of word(s)
Formatted outputPrintf(“control string”, arg1, arg2,……….,argn);Output of Integer Numbers: Format Output
printf(“%d”, 9876)
printf(“%6d”, 9876)
printf(“%-6d”, 9876)
printf(“%06d”, 9876)
9 8 7 6
9 8 7 6
9 8 7 6
0 0 9 8 7 6
Output of Real Numbers: y=98.7654 Format Output
printf(“%7.4f”, y)
printf(“%7.2f”, y)
printf(“%-7.2f”, y)
printf(“%f”, y)
Printf(“%10.2e”,y)
Printf(“%-10.2e”,y)
. 79 8 7
6 59 8 . 7 4
79 8 . 7
6 59 8 . 7 4
e +9 . 8 8 0 1
0 18 8 e +.9
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);
}
Operators and Expressions
C operators can be classified into a number of categories. They include:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators
Arithmetic operatorsOperator Meaning
+ Addition or unary plus
- Subtraction or unary minus
* Multiplication
/ Division
% Modulo division
Integer Arithmetic: if a=14 and b=4a-b = 10 a+b = 18 a*b = 16 a/b = 3 a%b = 2During 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 operatorsOperator 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|| Meaning logical OR! Meaning logical NOT
Ex: a>b && x==10
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
Statement with shorthand operator
a=a+1 a+=1a=a-1 a-=1a=a*(n+1) a*=n+1a=a/(n+1) a/=n+1a=a%b a%=b
#define N 100
#define A 2
main()
{
int a; output:
a= A; 2
while(a<N) 4
{ 16
printf(“%d”,a);
a * = a;
}
}
Increment and Decrement operators
C allows two very useful operators. ++ and –
The operator ++ ads 1 to the operand, while – subtracts 1.
++m; is equivalent to m=m+1;
--m; is equivalent to m=m-1;
Ex: m=5; y=++m;
the value of y and m would be 6.
m=5; y=m++
the value of y would be 5 and m would be 6.
A prefix operator first adds 1 to the operand and then the result is assigned to the variable on left.
A postfix operator first assigns the value to the variable on left and then increments the operand.
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: a=10; b=15;
x=(a>b)?a:b;
In this example, x will be assigned the value of b.
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 Tokens Operator Class
Precedence
Associates
(type) casts unary 14 right-to-left
* / % multiplicative binary 13 left-to-right
+ - additive binary 12 left-to-right
<< >> left, right shift binary 11 left-to-right
< <= > >= relational binary 10 left-to-right
== != equality/ineq. binary 9 left-to-right
& bitwise and binary 8 left-to-right
^ bitwise xor binary 7 left-to-right
| bitwise or binary 6 left-to-right
&& logical and binary 5 left-to-right
|| logical or binary 4 left-to-right
?: conditional ternary 3 right-to-left
= += -=*= /= %=&= ^= |=<<= >>=
assignment binary 2 right-to-left
, sequential eval. binary 1 left-to-right
Operator precedence
Tokens Operator ClassPreced
enceAssociates
names,literals simple tokens primary
16
n/a
a[k] subscripting postfix left-to-right
f(...) function call postfix left-to-right
. direct selection postfix left-to-right
-> indirect selection postfix left to right
++ -- increment, decrement postfix left-to-right
(type){init} compound literal postfix left-to-right
++ -- increment, decrement prefix
15
right-to-left
sizeof size unary right-to-left
~ bitwise not unary right-to-left
! logical not unary right-to-left
- + negation, plus unary right-to-left
& address of unary right-to-left
*indirection
(dereference)unary 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)
The Decision Control structure
The if statement :If(this condition is true) execute this statement;
Ex: main(){ int num;
printf(“ enter a number less than 10”); scanf(“%d”, &num); if(num <=10 ) printf(“ less than 10”); (single statement with in if)}
Multiple statements within if
/* Calculation of bonus*/
main()
{
int bonus, cy, yoj, yr_of_ser;
printf(“Enter current year and year of joining”);
scanf(“%d%d”, &cy, %yoj);
yr_of_ser = cy-yoj;
If(yr_of_ser > 3)
{
bonus = 2500; Multiple statements printf(“ bonus = RS. %d”, bonus); within if
}
}
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;
d. if(condition) {
do this; and this;
} else
{ do this; and this;}
e. if(condition)
do this; else
{ if(condition)
do this; else
{ do this; and this;}
}
Write a program to calculate the division obtained by the student.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”);
else
{
if(per >=50)
printf(“ second division”);
else
{
if(per >=40)
printf(“ third division”);
else
printf(“Fail”);
}
}
}
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”);
}
The Loop Control Structure
1. While Loop
2. Do-While Loop
3. For Loop
4. Nested for Loop
• Loops involves repeating some portion of the program either a specified number of times or until a particular condition is being satisfied
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 Loop Control Structure
Example B: main() { int i=0;
while (++i <=10) printf(“%d”, i);
}
In the statement while( ++i <= 10), first incrementation of I takes place, then the comparison of value of I with 10 is performed.
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.
Program Example 1:#include<stdio.h> main()
{ while (4<1)printf(”Here there”);
}
• 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.
For Loop• 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;
}
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.
c. main()
{
int i = 1;
for(; i<=10; )
{
printf(“%d”, i);
i=i+1;
}
}• Here, neither the initialisation, nor the incrementation is
done in the for statement, 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.
Nested for LoopProgram Example:
#include<stdio.h> output:
main() R=1 c=1 sum =2
{ R=1 c=2 sum =3
int r,c,sum; R=2 c=1 sum =3
for (r =1; r<=3; r++) R=2 c=1 sum =4
{ R=3 c=1 sum =4
for (c=1; c<=2; c++) R=3 c=2 sum =5
{
sum = r + c;
printf(“r=%d c=%d sum=%d”, r, c, sum);
}
}
}
• 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.
The break Statement• We want to jump out of a loop instantly, without
waiting to get back to the conditional test. The keyword break allows us to do this.
• A break is usually associated with an if.
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.
The continue Statement• In some programming situations we want to take
the control to the beginning of the loop, bypassing the statements inside the loop which have not yet been executed.
• A continue is usually associated with an if.
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)
The switch Multiple-Selection Structure
• switch– Useful when variable or expression is tested for multiple
values– Consists of a series of case labels and an optional default
case– break is (almost always) necessary
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
Declaration of many functions
main( )
{ engg()
printf(“I am in main”); {
poly( ); printf( “I am in engineering ”);
engg( ); }
agri( ); agri()
} {
poly( ) printf( “I am inagri ”);
{ }
printf(“I am in polytechnic”);
}
main() {
printf(“I am in main”);italy();printf(“ iam finally back in main”); output:
} I am In mainItaly() I am in italy{ I am in brazilprintf(“I am in italy”); I am in argentina brazil(); I am back in italyprintf(“I am back in italy”); iam finally back in main}brazil(){
printf(“I am in brazil”);argentina();
}argentina(){
printf(“I am in argentina ”);}
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.
fun( ){
statement1; statement2; statement3;
}
• 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.
Passing values between functionsThe values that we pass to the function called as function arguments.e.g. main( )
{ int i=10, j=12, k=20;
calsum(i,j,k);}
calsum(int x, int y, int z){
Printf(“Sum is : % d”, (x+y+z));}
Output: 42i, j, k are actual arguments
x, y, z are formal arguments
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
{
int z;z = (x + y) +1;return(z);
}
• 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 unlesstype 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
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.
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 C’s ‘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 i‘s address)
6485 3276
3 6485
Ex: main(){
int i=3; output: int *j; address of i = 6485
j=&i; address of i = 6485
printf(“address of i=%u”, &i); address of j = 3276
printf(“address of i=%u”, j); value of j = 6485
printf(“address of j=%u”, &j); value of i = 3
printf(“value of j= %u”, j); value of i = 3
printf(“value of i= %d”, i); value of i = 3
printf(“value of i= %d”, *(&i));
printf(“value of i= %d”, *j);
}
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 =70int 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); }
output:interchange(x1,y1) *x=70 *y=50 int *x1,*y1; x=70 y=50 { int z1; z1=*x1; *x1=*y1; *y1=z1; printf(“*x=%d *y=%d”,x1,y1); }
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) { output :int x,y; Enter the integer whose factorial value you want if(n==0) 3return 1; x=n-1; The factorial value is 6 y=fact(x);return n*y; }
void main() {int x;
printf(“\nEnter the integer whose factorial value you want “);scanf(“%d”,&x);printf(“\nThe factorial value is:-%d”,fact(x)); }