C_Unit2
C_Unit2
Programming in C
UNIT_II
1) Explain about different types of operators in C language?
Example : x = a + b
Here the value of a + b is evaluated and substituted to the variable x
❖ Relational Operators: Relational operators are used to compare two operands.The result
of relational operator returns a boolean value i.e, true/false.Relational expressions are
used in decision making statements of C language such as if, while and for statements to
decide the course of action of a running program.
Syntax: exp1 relational operator exp2
Where exp1 and exp2 are expressions, which may be simple constants,
variables or combination of them.
❖ Logical Operators : C has the following logical operators, they compare or evaluate
logical
and relational expressions.
⚫ Logical AND (&&) : This operator is used to evaluate 2 conditions or expressions with
relational operators simultaneously. If both the expressions to the left and to the right of the
logical operator is true then the whole compound expression is true.
Example : a > b && x = = 10
⚫ Logical NOT (!) :The logical not operator takes single expression and evaluates to true if
the expression is false and evaluates to false if the expression is true. In
other words it just reverses the value of the expression.
For example : ! (x >= y) the NOT expression evaluates to true only if the value of x is
neither greater than or equal to y
❖ Bitwise Operators
C has a distinction of supporting special operators known as bitwise operators for
manipulation data at bit level. A bitwise operator operates on each bit of data. Those
operators are used for testing, complementing or shifting bits to the right on left.
Bitwise operators may not be applied to a float or double.
❖ Unary Opertaor: The increment and decrement operators are one of the unary operators
which are very useful in C language. They are extensively used in for and while loops.
The syntax of the operators is given below
➢ ++ variable name
➢ variable name++
➢ – –variable name
➢ variable name– –
✓ The increment operator ++ adds the value 1 to the current value of operand and the
decrement operator – – subtracts the value 1 from the current value of operand.
The ternary operator works as follows exp1 is evaluated first. If the expression is true then
exp2 is evaluated & its value becomes the value of the expression. If exp1 is false, exp3 is
evaluated and its value becomes the value of the expression
Eg: a = 10;
b = 15;
x = (a > b) ? a : b
❖ Simple if Statement: This is the most simple form of decision control statement. In this
form, a set of statements are executed only if the condition given with if evaluates to true.
Its general syntax and flow chart is as under:-
if(condition)
{
Statements ;
}
#include<stdio.h>
#include<conio.h>
void main()
{
int num;
clrscr();
printf(“enter the number”);
scanf(“%d”,&num);
if(num<0)
{
printf(“the entered number is negative”);
}
getch();
}
}
❖ if- else statement :- This is a bi-directional control statement. This statement is used to
test a condition and take one of the two possible actions. If the condition evaluates to true
then one statement (or block of statements) is executed otherwise other statement (or
block of statements) is executed.
The general form and flow chart of if-else statement is as under:-
if(condition)
{
block of statements;
}
else
{
block of statements;
}
#include<stdio.h>
#include<conio.h>
void main()
{
int num1,num2 ;
clrscr();
printf(“enter the two numbers”);
scanf(“%d %d”,&num1,&num2);
if(num1>num2)
{
printf(“the number %d is big”,num1);
}
else
{
printf(“the number %d is big”,num2);
}
getch();
}
❖ Nested if-else:- If we have if-else statement within either the body of an if statement or
the body of else statement or in the body of both if and else, then this is known as
nesting of if else statement.
The general form of nested if-else statement is as follows:-
if(condition1)
{
if(condition2)
statements;
else
statements;
}
else
{
if(condition3)
Statements;
else
Statements;
}
#include<stdio.h>
#include<conio.h>
void main()
{
int a, b,c,large;
printf(“enter the three numbers”);
scanf(“%d%d%d”,&a,&b,&c);
if(a>b)
{
if(a>c)
large=a;
else
large=c;
else }
{
if(b>c)
large=b; else
large=c;
}
printf(“largest number is %d”,large);
getch();
}
❖ Else if ladder:-This is a type of nesting in which there is an if-else statement in every
else part except the last else part. This type of nesting is called else if ladder.
The general syntax and flow chart of else if ladder is as follows:-
if(condition1)
statementA;
else if(condition2)
statementB;
else if(condition3)
statementC;
else
statementD;
❖ Switch case statement :- Switch case statements are a substitute for long if statements
and has more flexibility and a clearer format than else-if ladder. This statement is used to
select one out of the several numbers of alternatives present in a block. This selection
statement successively tests the value of an expression against a list of integer or
character constants. When a match is found, the statements associated with that constant
are executed.
The general syntax of switch case statement is as follows:-
switch(expression)
{
case constant1: statements;
case constant2: statements;
case constant3: statements;
………………………
………………………
case constantN: statements;
default : statement;
}
Here switch, case and default are keywords. The expression following the switch
keyword must give an integer value. This expression can be any integer or character variable,
or a function call that returns an integer.
Iterations or loops are used when we want to execute a statement or block of statements
several times. The repetition of loops is controlled with the help of a test condition. The
statements in the loop keep on executing repetitively until the test condition becomes false.
There are the following three types of loops:-
1. While loop
2. Do-while loop
3. For loop
⚫ While loop : - It is the fundamental looping statement in C. It is suited for the problems
where it is not known in advance that how many times a statement or block of statements
will be executed.
The general syntax of while loop is as under:
While(condition)
{
Statement(s);
}
Firstly the condition given with while is evaluated. If the condition evaluates to true then the
statements given in the body of the loop are executed. After the execution of all the
statements the condition is again checked and if it again evaluates to true then the statements
given in the body of the loop are again executed. In this way the statements are executed
again and again until the condition given evaluates to false.
#include<stdio.h>
#include<conio.h>
int main()
{ int num=1; //initializing the variable
while(num<=10) //while loop with condition
{ printf("%d\n",num);
num++; //incrementing operation
} return 0;
}
⚫ do-while loop :- The do-while statement is also used for looping. It is similar to while
loop and is used for the problems where it is not known in advance that how many times
the statement or block of statements will be executed. However, unlike while loop, in
case of do-while, firstly the statements inside the loop body are executed and then the
condition is evaluated. As a result of which this loop is executed at least once even if the
condition is initially false. After that the loop is repeated until the condition evaluates to
false. test loop. Since in this loop the condition is tested after the execution of the loop, it
is also known as post
The general syntax of do-while loop is as follows:-
do
{
Statement(s);
}while(condition);
⚫ For loop :- The general syntax of for loop consists of three expressions separated by
semicolons. It is given as follows:-
for(expression1;expression2;expression3)
{
Statement(s);
}
Here the expression1 is the initialization expression,expression2 is the test expression and
expression3 is the update expression.
✓ Expression1 is executed only once when the loop starts and is used to initialize the loop
variables.
✓ Expression2 is a condition and is tested before each iteration of the loop.
✓ Expression3 is a condition and is tested before each iteration of the loop. is an update
expression and is executed each time after the body of the loop is executed.
//Eg for for loop:
#include<stdio.h>
void main( )
{
int x;
for(x = 1; x <= 10; x++)
{
printf("%d\t", x);
}
}
Jump statements are used to transfer the control from one part of the program to another part.
The various jump statements in C are as under:-
1. break statement
2. continue statement
3. goto statement
⚫ break statement:- break statement is used inside the loops or switch statement. This
statement causes an immediate exit from the loop or the switch case block in which it
appears.
It can be written as
break;
✓ when break statement is encountered, loop is terminated and the control is transferred to
the statement immediately after the loop.
✓ If breakstatement is written inside a nested loop structure then it causes exit from the
innermost loop.
✓ In Switch case , it is used as the last statement of every case except the last one. When
executed, it transfers the control out of switch case and the execution of the program
continues from the statement following switch statement.
Switch(expression)
{
case1: statement-1;
break;
case2: statement-2;
break;
case3: statement-3;
break;
.
.
.
.
case n: statement-n;
break;
default: statement-d;
}
#include<stdio.h>
void main( )
{
int n;
for(n=1;n<=5;n++)
{
if(n==3)
{
printf(“I understand the use of break \n”);
break;
}
printf(“Number = %d \n”,n);
}
printf(“Out of for loop \n”);
}
Output:
Number = 1
Number = 2
I understand the use of break
Out of for loop
⚫ continue statement :- The continue statement is used inside the body of the loop
statement when we want to go to the next iteration of the loop after skipping some of the
statements of the loop.
The continue statement is written as under:
continue;
✓ It is generally used with a condition. When a continue statement is encountered all the
remaining statements (statements after continue) in the current iteration are not executed
and the loop continues with the next iteration.
✓ The difference between break and continue is that when a break statement is
encountered the loop terminates and the control is transferred to the next statement
following the loop, but when a continue statement is encountered the loop is not
terminated and the control is transferred to the beginning of the loop.
#include<Stdio.h>
void main( )
{
int n;
for(n=1;n<=5;n++)
{
if(n == 3)
{
printf(“Welcome”);
continue;
}
printf(“Number = %d\n”,n);
}
printf(“Out of the loop”);
}
Output :
Number = 1
Number =2
Welcome
Number =4
Number = 5
Out of for loop
In c, we can divide a large program into the basic building blocks known as function.
The function contains the set of programming statements enclosed by { }. A function can
be called multiple times to provide reusability and modularity to the C program.
Advantages of Function:
✓ By using functions, we can avoid rewriting same logic/code again and again in a program.
✓ We can call C functions any number of times in a program and from any place in a
program.
✓ We can track a large C program easily when it is divided into multiple functions.
✓ Reusability is the main achievement of C functions.
✓ However, Function calling is always a overhead in a C program.
➢ Function call: Function can be called from anywhere in the program. The
parameter list must not differ in function calling and function declaration. We
must pass the same number of functions as it is declared in the function
declaration.
Types of Functions :
There are two types of functions in C programming:
✓ Library Functions: are the functions which are declared in the C header files such
as scanf( ), printf( ), gets( ), puts( ), ceil( ), floor( ) etc.
✓ User-defined functions: are the functions which are created by the C
programmer, so that he/she can use it many times. It reduces the complexity of a
big program and optimizes the code.
⚫ User defined Functions: The function whose definiton is defined by the user is called
as User defined function.
✓ Different aspects of function calling:A function may or may not accept any argument.
It may or may not return any value. Based on these facts, There are four different aspects
of function calls.
➢ function without arguments and without return value
➢ function without arguments and with return value
➢ function with arguments and without return value
➢ function with arguments and with return value
⚫ The fucntion call is known as “Calling function” and the function definition is called
“Called function”.
◆ Function without arguments and without return value : In this type of function there is
no data transfer between calling function and called function.
//Eg:
#include<stdio.h>
void sum( );
void main( )
{
printf("\n Going to calculate the sum of two numbers:");
sum( );
}
void sum( )
{
int a,b;
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
printf("The sum is %d",a+b);
}
Output :
Going to calculate the sum of two numbers:
Enter two numbers: 10
24
The sum is 34
◆ function with arguments and without return value: In this type of functions there is
data transfer from calling fucntion to called function but there is no data transfer from
called function to calling function.
//Eg:
#include<stdio.h>
void average(int, int, int, int, int);
void main( )
{
int a,b,c,d,e;
printf("\nGoing to calculate the average of five numbers:");
printf("\nEnter five numbers:");
scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);
average(a,b,c,d,e);
}
void average(int a, int b, int c, int d, int e)
{
float avg;
avg = (a+b+c+d+e)/5;
printf("The average of given five numbers : %f",avg);
}
Output:
Going to calculate the average of five numbers:
Enter five numbers:10
20
30
40
50
The average of given five numbers : 30.000000
◆ function without arguments and with return value: In this type of functions there is no
data transfer from calling funtion to called function but there is data transfer from called
fucntion to calling function.
//Eg:
#include<stdio.h>
int sum( );
void main( )
{
int result;
printf("\nGoing to calculate the sum of two numbers:");
result = sum( );
printf("The sum is :%d",result);
}
int sum( )
{
int a,b;
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
return a+b;
}
Output :
Going to calculate the sum of two numbers:
Enter two numbers:10
24
The sum is :34
◆ function with arguments and with return value: In this type of fucntions there is data
transfer from calling fucntion to called function and also from called function to calling
function.
//Eg:
#include<stdio.h>
int sum(int, int);
void main( )
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("\nThe sum is : %d",result);
}
int sum(int a, int b)
{
return a+b;
}
Output:
Going to calculate the sum of two numbers:
Enter two numbers:10
20
The sum is : 30
Downward Communication:
➢ In this type of inter function communication, the data is transferred from calling function
to called function but not from called function to calling function.
➢ The functions with parameters and without return value are considered under downward
communication.
➢ In the case of downward communication, the execution control jumps from calling
function to called function along with parameters and executes the function
definition,and finally comes back to the calling function without any return value.
//Eg:
#include<stdio.h>
#include<conio.h>
void main( ){
int num1, num2 ;
void addition(int, int) ; // function declaration
clrscr( ) ;
num1 = 10 ;
num2 = 20 ;
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
addition(num1, num2) ; // calling function
getch() ;
}
void addition(int a, int b) // called function
{
printf("SUM = %d", a+b) ;
}
Upward Communication:
➢ In this type of inter-function communication, the data is transferred from called function
to calling-function but not from calling-function to called-function.
➢ The functions without parameters and with return value are considered under upward
communication.
➢ In the case of upward communication, the execution control jumps from calling-function
to called-function without parameters and executes the function definition, and finally
comes back to the calling function along with a return value.
Bi - Directional Communication:
➢ In this type of inter-function communication, the data is transferred from calling-function
to called function and also from called function to calling-function.
➢ The functions with parameters and with return value are considered under bi-directional
communication.
➢ In the case of bi-directional communication, the execution control jumps from calling-
function to called function along with parameters and executes the function definition
and finally comes back to the calling function along with a return value.
//Eg: Functions with arguments and with return type
Call by Value: The copy of actual parameter value are copied to formal parameters and
these formal parameters are used in called function.
The changes made in the formal parameters does not effect the values of actual
parameters.
The parameters which are declared in calling function those are actual parameters.
The parameters which are declared in called function those are formal parameters.
The main drawback is if we perform any modifications on formal arguments then those
arguments will not effect to formal arguments.
//Eg:
#include<stdio.h>
#include<conio.h>
void main( )
{
int num1,num2;
void swap(int,int); //function declaration
clrscr( );
num1= 10;
num2= 20;
printf(“\n Before swap: num1=%d,num2=%d”,num1,num2);
swap(num1,num2); //calling function
printf(“\n After swap:num1=%d,num2=%d”,num1,num2);
getch( );
}
void swap(int a,int b) //called function
{
int temp;
temp=a;
a=b;
b=temp;
}
Call by reference: The address of the actual arhuments are passed to the formal
arguments.A pointer variable should be declared.The actual and formal arguments store
in same memory location.
Here formal argument is alter to the actual argument, it means formal arguments calls the
actual arguments.
//Eg:
#include<stdio.h>
#include<conio.h>
void main( )
{
int num1,num2;
void swap(int *,int *); //fucntion declaration
clrscr( );
num1= 10;
num2 = 20;
printf(“\n Before swap:num1=%d,num2=%d”,num1,num2);
swap(&num1,&num2); //calling function
printf(“After swap:num1=%d,num2=%d”,num1,num2);
getch( );
}
void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
//Eg:
#include<stdio.h>
#include<conio.h>
int factoraial(int);
int mian( )
{
int fact,n;
printf(“Enter any positive integer:”);
scanf(“%d”,&n);
fact=factorial(n);
printf(“Factorial of %d is %d\n”,n,fact);
return 0;
}
int factorial(int n)
{
int temp;
if(n == 0)
return 1;
else
temp= n*factorual(n-1); //recursive function
return temp;
}
Features:
✓ Storage-memory location
✓ Default initial value:-unpredictable value or garbage value.
✓ Scope:-local to the block or function in which variable is defined.
✓ Life time:-Till the control remains within function or block in which it is defined. It
terminates when function is released.
//Eg:
Avoid incr( );
void main( )
{
incr( );
incr( );
incr( );
}
void incr( )
{
auto int a =0;
printf(“\n a= %d”,a);
a++;
}uto
Output: a=0
a=0
a=0
❖ External Storage class: These variables are declared before the main( ) method.We can
use these variable in entire program.Also called as global variables.
Eg: extern int a;
Features:
✓ Storage-memory location
✓ Default initial value:-zero
✓ Scope:-global
✓ Life time:--as long as program execution remains it retains.
//Eg: void incr( );
int a = 10;
void main( ){
printf(“a=%d”,a);
incr( );
}
void incr( )
{
a= a+30;
printf(“Increment a=%d”,a);
}
Output: a=10
a=40
❖ static storage class: Variables are declared inside a function in which they are used.
Eg: static int a;
Features:
✓ Storage-memory location
✓ Default initial value:-zero
✓ Scope:-local to the block or function in which it is defined.
✓ Life time:--value of the variable persist or remain between different function call.
❖ Register Storage class: Declared inside a function in which they are used.
Eg: register int c;
Features:
✓ Storage-CPU register.
✓ Default initial value:-garbage value
✓ Scope:-local to the function or block in which it is defined.
✓ Life time:--till controls remains within function or blocks in which it is defined.
//Eg:
int main( )
{
register int i;
for(i=0;i<5000;i++)
printf(“%d\t”,i);
}
Output: 1 2 3 4 -------- 4999
❖ volatile: It is used ot create variables whose value cannot be changes in the program
explicitly but can be changed by any external device or hardware.