Unit II Notes C

Download as pdf or txt
Download as pdf or txt
You are on page 1of 51

24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

UNIT II - Managing simple Input and Output operations - Operators and Expressions -
Decision Making: Branching statements, looping statements - Function: Declaration,
Definition - Passing arguments by value - Recursion - Storage classes.

2.1 MANAGING SIMPLE INPUT AND OUTPUT OPERATIONS


Input and Output Statements
In „C‟ language, there are two types of input and output statements. They are:
 Unformatted I/O statements

 Formatted I/O statements

(I) Unformatted Input / Output Statements


In unformatted I/O statements, no need to specify the type & size of the data. It arranges
the data in any format.
(a) getchar()
The getchar( ) is an input function that reads a single character from the standard input device (
keyboard ).
Syntax:
char variable;
variable = getchar ( );
Example:
char ch;
ch = getchar ( );

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

b) putchar()
The putchar( ) is an output function that writes a single character on the standard output device (
monitor ).
Syntax
putchar (variable);
Program :
# include<stdio.h>
#include<conio.h>
void main ( )

{
char ch;
printf (“Enter any one character : ”);
ch = getchar ( );
printf (“The character you typed is ”);
putchar(ch);
}
Output :
Enter any one character : S
The character you typed is S

c) gets()
This function is used to accept a string from standard input device until ENTER key is pressed.
Syntax
String_variable = gets();

d) puts()
This function is used to display a string to the standard output device.
Syntax
puts (String_variable)

Program :
# include<stdio.h>

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

#include<conio.h>
void main ( )
{
char name[20];
printf (“Enter your name : ”);
name = gets( );
printf (“Your name is : ”);
puts(name);
}

Output :
Enter your name : Anand
Your name is : Anand

e) getc()
The getc( ) is an input function that reads a single character from the standard input device (
keyboard ).
Syntax:
char variable;
variable = getc( );
Example:
char ch;
ch = getc( );

f) putc()
The putc( ) is an output function that writes a single character on the standard output device (
monitor ).
Syntax
putc(variable);

Program :
# include<stdio.h>
#include<conio.h>

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

void main ( )
{
char ch;
printf (“Enter any one character : ”);
ch = getc( );
printf (“The character you typed is ”);
putc(ch);
}
Output :
Enter any one character : S
The character you typed is S

(II) Formatted I/O Statements


In unformatted I/O statements, we need to specify the type & size of the data. It arranges the data
in particular format.
(a) scanf ()
Input data can be read from standard input device (keyboard) using scanf ( ) function.
Syntax
scanf (“Control String”, &var1, &var2, . . .);
Example
scanf (“%d %d”, &a, &b);
Control String:
Control string specifies the type of data to be read and its size. The following list represents the
possible control strings.
%c - To read single character
%s - To read a string
%d - To read an integer
%f - To read a floating point number
Rules for scanf()
 Each variable name must be preceded by symbol (&).

 The control string and variables data type should match each other.

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

(b) printf ( )
Output data can be displayed in the standard output device (monitor) using printf( ) function.
Syntax
printf (“Control String”, var1, var2, . . .);

Example
printf (“%d %d”, a, b);
printf (“Factorial = %d”, fact);

Rules for printf()


 The control string and variables data type should match each other.

 The variable must be separated by commas and need not be preceded with „&‟ symbol.
Program:
# include<stdio.h>
#include<conio.h>
void main ( )
{
int A, B, C;
printf (“Enter values for A and B : ”);
scanf (“%d %d”, &A, &B);
C = A + B;
printf(“Sum is %d”, C);
getch();
}
Output:
Enter values of A and B : 4 3
Sum is 7
(c) fscanf
This function is used in file processing to read data from a file.
(d) fprintf
This function is used in file processing to write data into a file.
The fscanf() & fprintf() are similar to scanf and printf except that they are used in file processing.

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

2.2 OPERATORS AND EXPRESSIONS


(I) OPERATORS
Operator is a symbol that performs the operation on one or more operands. C Language provides
the following operators:
i. Arithmetic operators

ii. Relational operators

iii. Logical operators

iv. Assignment operators

v. Increment and Decrement operators

vi. Conditional operators

vii. Bitwise operators

viii. Special operators

i) Arithmetic Operators:
Arithmetic operations like addition, subtraction, multiplication, division etc can be performed by
using arithmetic operators.

Program
#include<stdio.h>
#include<conio.h>
void main()

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

{
int a =15;
int b=10;
int add,sub,mul,div,mod;
add = a+b;

sub = a-b;
mul=a*b;
div= a/b;
mod= a%b;
printf( “addition=%d”,add);
prtintf(“subtraction=%d”,sub);
printf”multiplication=%d”,mul);
printf(“division=%d”,div);
printf(“modulo=%d”,mod);
getch();
}
Output:
Addition= 25
Subtraction=5
Multiplication=150
Division=1
Modulo=5
ii) Relational Operators:
 Relational operators are used to compare two or more operands.

 We use relational expression in if, for and while statements.

 Relational expressions return either True (1) or False (0).

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a =15;
int b=10;
printf( “a<b:%d”,a<b);
prtintf(“a<=b:%d”,a<=b);
printf”a>b:%d”,a>b);
printf(“a>=b:%d”,a>=b);
printf(“a==b:%d”,a==b);
printf(“a!=b:%d”,a!=b);
getch();
}
Output
a<b: 0
a<=b:0
a>b:1
a>=b:1
a==b:0
a!=b:1

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

iii) Logical Operators:


 Logical operators are used to combine the results of two or more relational expressions.

 Logical NOT is a unary operator that negates the logical value of its single operand.
 Logical NOT convert a 1 to 0, and 0 to 1.

 Logical AND produces 1 if both operands are 1, otherwise produce 0.

 Logical OR produces 0 if both operands are 0, otherwise it produces 1.

iv) Assignment Operator:


Assignment operator ‘=’ is used to assign a constant or a value of an expression or a value of a
variable to other variable.
Syntax
Variable = expression (or) value

(v) Increment and Decrement Operators (unary):


 increment (++) - Adds one to the variables

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

 decrement (--) - Subtract one from the variable

Example:
a=10;
++a =11
a++ =10
--a =9
a-- =10

vi) Conditional Operator (or) Ternary Operator:


?: is known as conditional operator. It is equivalent to simple if then else statement. It checks the
condition and executes the exp1 if condition is true otherwise it execute exp2.

Syntax
condition ? exp1 : exp 2;

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a = 5
int b = 3

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

int max;
max = a > b ? a : b ;
printf(“Maximum is %d”, max);
getch();
}
Output:
Maximum is 5
In this example, it checks the condition „a > b‟, if it is true, then the value of „a‟ is assigned to
„max‟, otherwise the value of „b‟ is assigned to „max‟.

vii) Bitwise Operators:


 Bitwise operators are used to calculate the data at bit level.

 It operates on integers only.

Bitwise AND ( & )


This operator compare the operands in corresponding bits position and produces 1 if both
operand bits are 1, otherwise produces 0.
Bitwise OR ( | )
This operator compare the operands in corresponding bits position and produces 0 if both
operand bits are 0, otherwise produces 1.
Bitwise XOR (^ )
This operator compare the operands in corresponding bits position and produces 1 if both
operand bits are same, otherwise produces 0.
viii) Special Operators: (Miscellanous Operator)

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

C language supports some of the special operators.

Comma Operator: It is used to separate elements.


Example :
int X, Y;

sizeof Operator: It is used to return the size of the data type or variable.
Example :
sizeof(Y);

Member Selection Operators: It is used to refer structure or union member element.


Program
#include<stdio.h>
#include<conio.h>
void main()
{
int Y;
printf (“Size of Y is %d”, sizeof(Y));
getch();
}
Output:
Size of Y is 2

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

(II) OPERATORS: PRECEDENCE AND ASSOCIATIVITY


An operator is a special symbol that is used to perform particular mathematical or logical
computations like addition, multiplication, comparison and so on. The value of operator is applied
to be called operands.
Precedence and Associativity are two characteristics of operators that determine the evaluation
order of subexpressions in absence of brackets.
Precedence of operators
The precedence rule is used to determine the order of application of operators in evaluating
sub expressions. The operator with the highest precedence is operated first. Parenthesis operator
has the highest priority.
Associativity of operators
The associativity rule is applied when two or more operators are having same precedence
in the sub expression.
 An operator can be left-to-right associative or right-to-left associative.

 All operators with same precedence have same associativity

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

Arithmetic Operator Precedance


Arithmetic evaluation is carried out using two phases from left to right.
 During the first phase, highest priority operators are evaluated.

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

 In the second phase, lowest priority operators are evaluated.

Example:
Result= 6+4/ 2.
Phase1: (4/2 operation is evaluated first)
Result= 6+2
Phase2: (6+2 operation is evaluated next)
Result= 8
Program
#include<stdio.h>
#include<conio.h>
void main()
{
Result= 6+4/ 2;
printf(“Result=%d”,Result);
getch();
}
Output
Result= 8

(III) EXPRESSIONS
An expression is a sequence of operators and operands that specifies the computation. An
operand can be a variable, constant or a function call. An operator is a symbol that is used to write
a mathematical, logical or relational expression.
Simple Expression
An expression that has only one operator is known as simple expression.
Example:
X=a+b;

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

X=++a;

Compound Expression
An expression that has more than one operator is known as compound expression.
Example:
X=a+b*c/f;
Arithmetic Expression
An expression consisting of arithmetic operators is known as arithmetic expression.
Example:
X=a+b;
Logical Expression
An expression consisting of logical operators is known as Logical expression.
Example:
X=a>b;
Program
#include<stdio.h>
#include<conio.h>
void main()
{
Result= 6+4/ 2;
printf(“Result=%d”,Result);
getch();
}
Output
Result= 8

2.3 DECISION MAKING STATEMENTS


The order in which the program statements are executed is known as flow of control. Decision
making statements alters the default flow of control. There are 2 types of decision making
statements. They are,

 Conditional Branching Statements


 Unconditional Branching Statements

(I) Conditional Branching Statements

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

In conditional branching, program control is transferred from one point to another based
upon the outcome of the condition. The conditional branching statements are:
a) if Statement

b) if-else Statement

c) Nested if Statement

d) if else if else statement

e) switch Statement

a) Simple if Statement
It check the given condition in if statement. If it is true then it will execute the body of if
statement, otherwise it skipped the body of if statement.
Syntax:
if (condition)
{
Statement block
}
Flow Chart:

Program : Program To Check Whether The Number Is Positive

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

# include<stdio.h>
#include<conio.h>
void main ( )
{
int a;
printf (“\n Enter a number : ”);
scanf (“%d”, &a);
if ( a > 0)
printf (“The given number is positive number”);
getch();
}
Output
Enter a number :7
The given number is positive number

b) if - else Statement
It is a two way branching statement. If the condition is true then the True part statement will be
executed.If the condition is false then the False part statement will be executed.
Flowchart:

Syntax:
if ( condition)

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

True part Statement


}
else
{
False part Statement
}

Program: Check Whether the Number Is Odd Or Even


# include<stdio.h>
#include<conio.h>
void main ( )
{
int n, r;
printf (“\n Enter a Number:”);
scanf (“%d”, &n);
r = n % 2;
if ( r == 0 )
printf (“Given Number is Even”);
else
printf (“Given Number is Odd”);
getch();
}
Output:
Enter a Number: 6
Given Number is Even

c) Nested if Statement
The if statement within another if statement is called as nested if statement.
Syntax:
if ( condition1 )
{
if ( condition2)

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

{
Inner if True part Statement
}
else
{
Inner if False part Statement
}
}
else
{
Outer if False part Statement
}
It checks the condition1 and if it is true it check the inner if condition2. This type of nested if is
useful when a series of decisions are involved.

Program :
# include<stdio.h>
#include<conio.h>
void main ( )
{
int Mark;
printf (“Give your Mark”);
scanf (“%d”, &Mark);
if ( Mark < 50 )
printf(“Failed”);
else
{
if ( Mark < 60 )
printf(“Second Class”);
else
printf (“First Class”);
}

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

getch();
}
Output
Give your mark : 68
First class

d) if-else if- else statement


If the else part of if statement contain another if statement, then the else and the if statement can
be combined. It is called else if ladder.

Syntax :
if ( condition1 )
Statement block 1
else if ( condition2)
Statement block 2
else if ( condition3 )

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

Statement block 3
else
Statement block 4

If the condition1 evaluated is true, the statement block1 is executed. If the condition2 is
true, then statement block2 is executed and so on. If none of the conditions are true, then the
statement block4 is executed.

Program : Find Largest Among Three Numbers


# include<stdio.h>
#include<conio.h>
void main ( )
{
int a, b, c;
printf (“Enter three numbers : ”);
scanf (“%d %d %d”, &a, &b, &c);
if (a > b) && (a > c)
printf(“Biggest Number is %d”, a);
else if (b > c)
printf(“Biggest Number is %d”, b);
else
printf (“Biggest Number is %d”, c);
getch();
}
Output :
Enter three numbers : 40 -50 35
Biggest Number is 40

e) switch Statement
It is a multiway branching statement. It first evaluates the expression in switch statement.
That result is compared with each case value one by one. Whenever a match found, it execute the
statements given in the corresponding case statement.If none of the case value matches with the
result it executes the default section.

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

Syntax:
switch (Expression)
{
case value 1:
Statement block 1
break;

case value 2:
Statement block 2
break;
...
case value n:
Statement block n
break;
default:

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

Default Statement block }

Writing Switch Statement


The expression used in switch statement must be an integer or a character data.

The case labels must be character or integer constant.

Each case block must be terminated by break statement. Otherwise, all statements that are
followed by matched cases are executed.

The default clause is optional & usually placed at the end.

The case keyword must terminate with colon ( : )

No two case constants are identical.

Program : Perform Arithmetic Operation Using Switch statement


# include<stdio.h>
#include<conio.h>
void main ( )
{
float value1, value2;
char operator;
printf (“Type your expression : ”);
scanf (“%f %c %f”, &value1, &operator, &value2);
switch(operator)
{
case „+‟ :
printf (“%f”, value1 + value2);
break;case „-‟ :

printf (“%f”, value1 - value2);


break;
case „*‟ :
printf (“%f”, value1 * value2);
break;
case „/‟ :

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

printf (“%f”, value1 / value2);


break;
default :
printf (“unknown operator”);
}
getch();
}
Output
Type your expression: 10 + 5
15

(II) Unconditional Branching Statement


In an unconditional branching, program control is transfer from one point to another
without checking the condition. Following are the unconditional branching statements.
i) goto
ii) break
iii) continue
iv) return

i) goto Statement
 C‟ provides the goto statement to transfer control unconditionally from one place to
another place in the program.
 The goto statement can move the program control almost anywhere in the program.

 The goto statement requires a label.

Program : Check Whether the Given Number is Prime or Not Using goto & return.
# include<stdio.h>

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

# include<conio.h>
void main ( )
{
int No, i;
printf (“Give the number : ”);
scanf (“%d” , &No);
for ( i = 2 ; i <= No / 2; i++ )
{
if ( No / i == 0 )
goto stop;
}
printf (“ Given Number is a Prime Number”);
return;
stop : printf (“ Given Number is not a Prime Number”);
}
Output:
Give the number : 17
Given Number is a Prime Number

ii) break Statement


 It is used within a looping statement or switch statement.

 The break statement is used to terminate the loop.

 In switch statement each case block must be terminated with break statement to exit from
switch.

Syntax:

break;
Example:
Refer switch example program.
iii) continue Statement
 It is used within looping statements.

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

 When the continue statement is used inside the loop, it skip the statements which are
available after this statement in the loop and go for the next iteration.

Syntax:
continue;

Program : Display 1 To 10 Except 5


# include<stdio.h>
#include<conio.h>
void main ( )
{
int i;
for (i =1; i <= 10; i++ )
{
if ( i == 5 )
continue;
printf (“ %d ”, i);
getch();
}
Output:
1 2 3 4 6 7 8 9 10

return Statement
A return statement terminates the execution of a function and returns the control to the calling
function.
The general form of a return statement is
return;

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

OR
return expression;
OR
return(expression);

2.4 LOOPING STATEMENTS


 The loop is defined as the block of statements which are repeatedly executed for a specified
number of times or until a particular condition is satisfied.

 If there is a single statement in the loop, the blocking braces is not necessary. If more than
one statement in the loop then the loop statements must be placed within braces.
The following are the loop statements in „C‟.
a) for

b) while

c) do – while
a) for Loop
We use for loop when we know exactly how many times the loop statements are repeated.
Syntax:
for (initialization; condition; incrementing / decrementing)
{
Statements
}
Initialization:
It has the initial value for the counter variable. In a for loop, initialization is executed first.
It is executed only once i.e., for the first iteration only.
Condition:
The condition represents a test expression.

Incrementing / decrementing:
After completing every iteration, the counter variable must be increased or decreased. Otherwise
it may leads to an infinite loop.
Flowchart

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

Program: Print the Sum of the Series 1 + 2 + 3 + 4 . . . up to N terms


#include<stdio.h>
#include<conio.h>
void main ( )
{
int i, sum = 0, n;
printf (“Enter the number of terms”);
scanf (“%d”, &n);
for (i = 1; i <= n; i++ )
sum = sum+ i;
printf (“ Sum = %d”, sum);
getch();
}

Output
Enter the number of terms 5
Sum=15

b) while Loop
while loop is a pre testing loop. The conditional expression is tested before the body is
executed. If the condition is true the loop will be repeated otherwise stop the iteration. If the very
first time itself the condition failed the loop will not be executed at least one time.

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

Syntax:
while (condition)
{
Body of the loop
}
Flowchart:

Program: Print the Sum of the Series 1 + 2 + 3 + 4 . . . up to N terms


#include<stdio.h>
#include<conio.h>

void main ( )
{
int i, sum = 0, n;
printf (“Enter the number of terms”);
scanf (“%d”, &n);
i=1;
while( i <= n)
{
sum = sum+ i;
i++;

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

}
printf (“ Sum = %d”, sum);
getch();
}
Output
Enter the number of terms 5
Sum=15

c) do…while Loop
It is an exit checking loop. In do...while loop the test condition is given at the end of the
loop. Therefore the body of the loop will be executed at least once. If the test condition is true,
then repeat the body of the loop otherwise exit from loop.
Syntax:
do
{
Body of loop statements
} while (test expression);

Program: Print the Sum of the Series 1 + 2 + 3 + 4 . . . up to N terms


#include<stdio.h>
#include<conio.h>
void main ( )

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

{
int i, sum = 0, n;
printf (“Enter the number of terms”);
scanf (“%d”, &n);
i=1;
do
{
sum = sum+ i;
i++;
} while( i <= n);
printf (“ Sum = %d”, sum);
getch();
}

Output
Enter the number of terms 5
Sum=15

2.5 INTRODUCTION TO FUNCTION


Function is defined as the block of organized, reusable code that is used to perform the
specific action. A function is a subprogram of one or more statements that performs a specific task
when called.
Advantages of Functions:
1. Code reusability

2. Better readability

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

3. Reduction in code redundancy

4. Easy to debug & test.


Classification of functions:
a) Based on who develops the function

b) Based on the function prototype


a) Based on the function prototype
Function prototype is a declaration statement that identify function with function name,
data type, a list of a arguments
b) Based on who develops the function
There are two types.
Library functions

User-defined functions

Elements of user defined function (or) Steps in writing a function in a program


1. Function Declaration (Prototype declaration)
2. Function Call

3. Function Definition

1. FUNCTION PROTOTYPE
Function prototype is a declaration statement that identifies function with function name,
data type, a list of a arguments. All the function need to be declared before they are used. (i.e.
called)
Syntax: returntype functionname (parameter list);

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

 Return type – data type of return value. It can be int, float, double, char, void etc.
 Function name – name of the function
 Parameter type list –It is a comma separated list of parameter types.

Example:
int add(int a, int b);
Function declaration must be terminated with a semicolon(;).
Types of function prototypes:
1. Function with no arguments and no return values
2. Function with arguments and no return values
3. Function with arguments and one return values
4. Function with no arguments and with return values

Prototype 1: Function with no arguments and no return values


 This function doesn‟t accept any input and doesn‟t return any result.

 These are not flexible.


Program
#include<stdio.h>
#include<conio.h>
void show(); //function prototype
void main()

void show( ) //function definition


{
printf(“Hai \n”);
}
Output:
Hai

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

Prototype 2: Function with arguments and no return values


Arguments are passed through the calling function. The called function operates on the
values but no result is sent back.
Program
#include<stdio.h>
#include<conio.h>
void show(int);
void main()
{
int a;
printf(“Enter the value for a \n”);
scanf(“%d”, &a);
show(a);
getch();
}
void show(int x)
{
printf(“Value =%d”, x);
}

Output:
Enter the value for a: 10
Value = 10

Prototype 3: Function with arguments and return values


 Arguments are passed through the calling function

 The called function operates on the values.


 The result is returned back to the calling function.
Program
#include<stdio.h>
#include<conio.h>
float circlearea(int);
void main()
{

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

int r;
float area;
printf(“Enter the radius \n”);
scanf(“%d”,&r);
area=circlearea(r);
printf(“Area of a circle =%d\n”, area);
getch();
}
int circlearea(int r1)
{
return 3.14 * r1 * r1;
}
Output:
Enter the radius
2
Area of circle = 12.000

Prototype 4: Function with no arguments and with return values


 This function doesn‟t accept any input and doesn‟t return any result.
 The result is returned back to the calling function.
Program
#include<stdio.h>
#include<conio.h>
float circlearea();
void main()

{
float area;
area=circlearea();
printf(“Area of a circle =%d\n”, area);
getch();
}
int circlearea()

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

{
int r=2;
return 3.14 * r * r;
}
Output:
Enter the radius
2
Area of circle = 12.000

2. FUNCTION DEFINITION
It is also known as function implementation. When the function is defined, space is
allocated for that function in memory.
Syntax
returntype functionname (parameter list)
{
statements;
return (value);
}
Example
int abc(int, int, int) // Function declaration
void main()
{
int x,y,z;
abc(x,y,z) // Function Call


}
int abc(int i, int j, int k) // Function definition
{
…….
….
return (value);
}

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

Every function definition consists of 2 parts:


a) Header of the function

b) Body of the function

a) Header of the function


The header of the function is not terminated with a semicolon. The return type and the
number & types of parameters must be same in both function header & function declaration.
Syntax:
returntype functionname (parameter list)
Where,
 Return type – data type of return value. It can be int, float, double, char, void etc.

 Function name – name of the function

 Parameter type list –It is a comma separated list of parameter types.


b) Body of the function
 It consists of a set of statements enclosed within curly braces.

 The return statement is used to return the result of the called function to the calling function.

Program:
#include<stdio.h>
#include<conio.h>
float circlearea(int); //function prototype
void main()
{
int r;

float area;
printf(“Enter the radius \n”);
scanf(“%d”,&r);
area=circlearea(r); //function call
printf(“Area of circle =%f\n”, area);
getch();

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

}
float circlearea(int r1)
{
return 3.14 * r1 * r1; //function definition
}
Output:
Enter the radius
2
Area of circle = 12.000

3. FUNCTION CALL
Function call is used to invoke the function. So the program control is transferred to that
function. A function can be called by using its name & actual parameters.
Function call should be terminated by a semicolon ( ; ).
Syntax:
Functionname(argumentlist);
Example
int abc(int, int, int) // Function declaration
void main()
{
int x,y,z;
abc(x,y,z) // Function Call


}

int abc(int i, int j, int k) // Function definition


{
…….
….
return (value);
}

Calling function – The function that calls a function is known as a calling function.
Called function – The function that has been called is known as a called function.
Actual arguments – The arguments of the calling function are called as actual arguments.

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

Formal arguments – The arguments of called function are called as formal arguments.

Steps for function Execution:


1. After the execution of the function call statement, the program control is transferred to the called
function.

2. The execution of the calling function is suspended and the called function starts execution.

3. After the execution of the called function, the program control returns to the calling function
and the calling function resumes its execution.

Program:
#include<stdio.h>
#include<conio.h>
float circlearea(int); //function prototype
void main()
{
int r;
float area;
printf(“Enter the radius \n”);
scanf(“%d”,&r);
area=circlearea(r); //function call
printf(“Area of a circle =%f\n”, area);
getch();
}

float circlearea(int r1)


{
return 3.14 * r1 * r1; //function definition
}
Output:
Enter the radius
2
Area of circle = 12.000

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

ARGUMENTS
Argument is the value, supply to function call. This value is assigned to corresponding
parameter in the function definition. Arguments are specified within a pair of paranthesis,
separated by commas.
Types of arguments
i) Required arguments
ii) Keyword arguments
iii) Default arguments
iv) Variable-Length arguments
i) Required arguments
Required arguments are the arguments passed to a function in correct positional order. Here
number of arguments in function call should match exactly with function definition.
Example Program:
def sum(a,b):
c=a+b
return c
print(“The sum is:”,sum(6,4))
Output:
The sum is:10

(ii) Keyword arguments


The keyword arguments are related to function call. Here caller identifies arguments by parameter
name.
Example Program:
def sum(a,b):
c=a+b
return c
print(“The sum is:”,sum(a=5,b=10))
Output:
The sum is:15

iii) Default arguments

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

Default argument is an argument that assume default value if value is not provided in function call.
Example Program:
def sum(a,b):
c=a+b
return c
print(“The sum is:”,sum(a=5))
Output:
The sum is:15

iv)Variable-Length arguments
Variable-Length arguments are arguments that makes function call with any number of arguments.
Here (*) is placed before the name of the variable.
Example Program:
def greeting(*name):
print(“Hai”,name)
greeting(“Welcome”)
greeting(“Welcome”,”Hello”)
Output:
Hai Welcome
Hai Welcome Hello

2.6 PASSING ARGUMENTS BY VALUE


(i) Call by Value (Pass by Value )
While calling a function, the values of actual parameters are passed to the formal
parameters. Therefore the called function works on the copy and not on original values of actual
parameters.
When arguments are passed by value, C allocates separate memory for formal arguments
and copy the actual argument value in that location. Therefore the changes made on formal
parameters will not affect the actual parameter.

Syntax for call by value:


function_name(arguments list);

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
void swap(int ,int);
a=10;
b=20;
printf("\n Before swapping: a = %d and b = %d",a,b);
swap(a, b);
printf("\n After swapping: a= %d and b= %d",a,b);

getch();
}
void swap(int x,int y)
{
int temp;
temp=x;
x=y;
y=temp;
printf(“\n In Swap, x=%d and y=%d”, x,y);
}
Output:
Before swapping: a =10 and b =20
In Swap, x=20 and y=10
After swapping: a =10 and b = 20

Explanation:
In the above program, before calling the swap function, the value of a is 10 and the value of b is
20. During the function call, the values of a and b are passed to x and y. In the swap function, the
values of x and y are swapped. Now, x has the value 20 and y has the value 10. But this change
does not get reflected in the value of a and b.

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

(ii) Call by Reference (Pass by Reference )


In this method, the address of the actual argument, in the calling function are copied into
the formal arguments of the called function. That is the actual & formal arguments refer same
memory location. Therefore the changes made on formal parameters will affect the actual
parameter of the calling function.

Example:
#include<stdio.h>
#include<conio.h>
void swap(int *, int *)
void main()
{
int a = 10, b = 20;
printf(“Before swap a = %d, b = %d \n”, a,b);
swap (&a, &b);
printf(“After swap a = %d, b = %d”, a, b);
getch();
}
void swap (int *x, int *y)
{
int temp;
temp = *x;

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

*x = *y;
*y = temp;
printf(“\n In Swap, x=%d and y=%d”, *x,*y);
}
Output:
Before swap a = 10, b = 20
In Swap, x=20 and y=10
After swap a = 20, b = 10

Explanation:
In the above program, before calling the swap function, the value of a is 10 and the value of b is
20. During the function call, the references of a and b are passed to x and y. In the swap function,
the values of x and y are swapped. Now, x has the value 20 and y has the value 10. This change
gets reflected in the value of a and b.

2.7 RECURSION
Recursion is defined as the function that calls itself repeatedly until condition is reached.
But while using recursion, programmers need to be careful to define an exit condition from the
function; otherwise it will go into an infinite loop.
Syntax:
Function1()
{

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

Function1();
}

Example:
Calculating the factorial of a number
Fact (n)= n*fact(n-1);
6! = 6*fact(n);
6! = 6 *5*fact(4)
6! = 6 * 5 * 4 *fact(3)
6! = 6 * 5 * 4 * 3 *fact(2)
6! =6 *5 * 4 * 3 *2 * fact(1)
6! = 6 *5 * 4 * 3 *2 * 1
6!=120

Advantage of recursion
Recursion makes program elegant and cleaner.
All algorithms can be defined recursively which makes it easier to visualize and prove.
Reduce unnecessary calling of function
Easy to solve complex problems

Direct Recursion:
A function is directly recursive if it calls itself.
A( )
{
….
A( ); // call to itself
….
}

Indirect Recursion:
Function calls another function, which in turn calls the original function.
A( )
{

B( );

}

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

B( )
{

A( );// function B calls A

}
Linear Recursion - It makes only one recursive call.
Binary Recursion - It calls itself twice.
N-ary recursion - It calls itself n times.

Program 1 : Find factorial using recursion


#include<stdio.h>
#include<conio.h>
int fact(int);
void main()
{
int n, Result;
printf(“\n Enter any number:”);
scanf(“%d”, &n);
Result = fact(n);
printf (“Factorial value = %d”, Result);
getch();
}
int fact (int x)
{
if (x == 0)
return 1;
else
return x * fact(x – 1);
}
Output:
Enter any number: 4
Factorial value = 24

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

Program 2 : Generate the Fibonacci Series Using Recursive Function


#include<stdio.h>
#include<conio.h>
int fib(int val);
void main ()
{
int i, n;
printf(“Enter the number”);

scanf (“%d”, &n);


printf(“\n Fibonacci sequence:”);
for (i = 0 , i < n, i++)
printf(“%d ”, fib(i));
getch();
}
int fib (int n)
{
if (n== 0)
{
return 0;
}
else if (n == 1)
{
return 1;
}
else
return fib(n – 1) + fib (n– 2);
}
Output
Enter the number: 6
Fibonacci sequence : 0 1 1 2 3 5

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

2.8 STORAGE CLASSES


A storage class defines the scope and life-time of variables and functions within a C
Program. It determines the part of memory.

In C, There are 4 storage classes. They are,


1. Automatic Storage class

2. External Storage class

3. Static Storage class

4. Register Storage class

(i) Automatic Storage class: auto


The auto storage class is the default storage class for all local variables. It is the temporary memory
space.
Scope: Variable defined with auto storage class is local to the function in which they are defined.
Default Initial Value: Any random value i.e garbage value.
Lifetime: Till the end of the function/method block where the variable is defined.

Syntax:
auto datatype var1,var2,…..,varn;
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
// or

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

auto int a; //Both are same


….
}

(ii) External or Global Storage class: extern


It is the external storage class for all global variables. It is declared out of the main function.
Scope: Global i.e everywhere in the program.
Default initial value: 0(zero).
Lifetime: Till the program doesn't finish its execution, we can access global variables.
Syntax:
extern datatype var1,var2,…..,varn;
Example
#include<stdio.h>
#include<conio.h>
extern int a; // global variable
void main()
{
…..
}

(iii) Static Storage class : static


The static storage class is the default storage class for all global variables. It is the
permanent memory space. It is declared out of the main function.

Scope: Local to the block in which the variable is defined


Default initial value: 0(Zero).
Lifetime: Till the whole program doesn't finish its execution.
Syntax:
static datatype var1,var2,…..,varn;
Example
#include<stdio.h>
#include<conio.h>
static int a; // both are same

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT II

//or
int a;
void main()
{
…..
}

(iv) Register Storage class: register


It is the special storage area within the computer‟s central processing unit.
Scope: Local to the function in which it is declared.
Default initial value: Any random value i.e garbage value
Lifetime: Till the end of function/method block, in which the variable is defined.
Syntax:
register datatype var1,var2,…..,varn;
Example
#include<stdio.h>
#include<conio.h>
void main()
{
register int a;
register int b;
…..
}

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY

You might also like