PROGRAMMING in C UNIT-2 notes
PROGRAMMING in C UNIT-2 notes
DECISION STATEMENTS
If statement:
Syntax :
if(expression) statement1;
Explanation :
Expression is Boolean Expression
It may have true or false value
Meaning of If Statement :
It Checks whether the given Expression is Boolean or not!
If Expression is True Then it executes the statement otherwise jumps to next instruction
CSE, MAIT
Sample Program Code :
void main()
{
int a=5,b=6,c;
c=a+b;
if (c==11)
printf("Execute me 1");
printf("Execute me 2");
}
Output :
Execute me1
If Statement:
if(conditional)
{
Statement No1
Statement No2
Statement No3
.
.
.
Statement No N
}
Note :
More than One Conditions can be Written inside If statement.
1. Opening and Closing Braces are required only when ―Code after if statement occupies multiple
lines.
if(conditional) Statement No 1
Statement No2
Statement No3
In the above example only Statement 1 is a part of if Statement.
Code will be executed if condition statement is True.
Non-Zero Number Inside if means “TRUE Condition”
CSE, MAIT
if(100)
printf("True Condition");
if-else Statement :
We can use if-else statement in c programming so that we can check any condition and depending on
the outcome of the condition we can follow appropriate path. We have true path as well as false path.
Syntax :
if(expression)
{
statement1;
statement2;
}
else
{
statement1;
statement2;
}
next_statement;
Explanation :
If expression is True then Statement1 and Statement2 are executed Otherwise Statement3 and
Statement4 are executed.
Sample Program on if-else Statement :
void main()
{
int marks=50;
if(marks>=40)
{
printf("Student is Pass");
}
else
{
CSE, MAIT
printf("Student is Fail");
}
}
Output :
Student is Pass
Flowchart : If Else Statement
CSE, MAIT
True Block will be executed if condition is True. Else Part executed if Condition Statement is False.
else
{
printf("False Block");
}
Consider Example 2 with Explanation :
More than One Conditions can be Written inside If statement.
int num1 = 20;
int num2 = 40;
if(num1 = = 20 && num2 = = 40)
{
printf("True Block");
}
Opening and Closing Braces are required only when Code after if statement occupies multiple lines.
Code will be executed if condition statement is True. Non-Zero Number Inside
if means “TRUE Condition”
If-Else Statement :
if(conditional)
{
//True code
}
else
{
//False code
}
Note :
Consider Following Example
int num = 20;
if(num = =20)
{
printf("True Block");
}
CSE, MAIT
else
{
printf("False Block");
}
If part Executed if Condition Statement is True. if(num == 20)
{
printf("True Block");
}
True Block will be executed if condition is True. Else Part executed if Condition Statement is False.
else
{
printf("False Block");
}
More than One Conditions can be Written inside If statement. int num1 = 20;
int num2 = 40;
if(num1 == 20 && num2 == 40)
{
printf("True Block");
}
Opening and Closing Braces are required only when ―Code‖ after if statement occupies multiple lines.
Code will be executed if condition statement is True. Non-Zero Number Inside if means “TRUE
Condition”
Switch statement
Why we should use Switch Case?
One of the classic problem encountered in nested if-else / else-if ladder is called problem of
Confusion.
It occurs when no matching else is available for if.
As the number of alternatives increases the Complexity of program increases drastically.
To overcome this, C Provide a multi-way decision statement called Switch Statement.
CSE, MAIT
See how difficult is this scenario?
if(Condition 1)
Statement 1 else
{
Statement 2
if(condition 2)
{
if(condition 3)
statement 3 else
if(condition 4)
{
statement 4
}
}
else
{
statement 5
}
}
First Look of Switch Case
switch(expression)
{
case value1 : body1 break;
case value2 : body2 break;
case value3 : body3 break;
default :
default-body break;
}
next-statement;
Flow Diagram:
CSE, MAIT
*Steps are Shown in Circles.
How it works?
Switch case checks the value of expression/variable against the list of case values and when
the match is found ,the block of statement associated with that case is executed
Expression should be Integer Expression / Character
Break statement takes control out of thecase.
Break Statement is Optional. #include<stdio.h>
void main()
{
int roll = 3 ; switch ( roll )
{
case 1:
printf ( " I am Pankaj "); break;
case 2:
printf ( " I am Nikhil "); break;
case 3:
printf ( " I am John "); break;
default :
printf ( "No student found"); break;
}
}
CSE, MAIT
As explained earlier –
3 is assigned to integer variable roll
On line 5 switch case decides – We have to execute block of code specified in 3rd case―.
Switch Case executes code from top to bottom.
It will now enter into first Case [i.e case 1:]
It will validate Case number with variable Roll. If no match found then it will jump to Next Case..
When it finds matching case it will execute block of code specified in that case.
incrementation;
}
Note :
For Single Line of Code – Opening and Closing braces are not needed. While (1) is used for Infinite
CSE, MAIT
Loop
Initialization , Incrementation and Condition steps are on different Line.
While Loop is also Entry Controlled Loop.[i.e conditions are checked if found true then and then only
code is executed ]
EXAMPLE:
#include <stdio.h>
int main () {
/* local variable definition */
int a = 10;
/* while loop execution */
while( a < 20 ) {
printf("value of a: %d\n", a);
a++;
}
return 0;
}
OUTPUT:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Do while:
Do-While Loop Syntax : initialization;
CSE, MAIT
do
{
incrementation;
}while(condition);
Note :
It is Exit Controlled Loop.
Initialization , Incrementation and Condition steps are on different Line.
It is also called Bottom Tested [i.e Condition is tested at bottom and Body has to execute at least once
]
EXAMPLE:
#include <stdio.h>
int main () {
/* local variable definition */
int a = 10;
/* do loop execution */
do {
printf("value of a: %d\n", a);
a = a + 1;
}while( a < 20 );
return 0;
}
For statement:
CSE, MAIT
We have already seen the basics of Looping Statement in C. C Language provides us different kind of
looping statements such as For loop, while loop and do-while loop. In this chapter we will be learning
different flavors of for loop statement.
CSE, MAIT
Above code snippet will print Hello word 5 times. We have single statement inside for loop body.
No need to wrap printf inside opening and closing curly block. Curly Block is Optional.
if(condition)
{
}
}
If we have block of code that is to be executed multiple times then we can use curly braces to wrap
multiple statement in for loop.
Way 3 : No Statement inside For Loop
for(i=0;i<5;i++)
{
}
This is body less for loop. It is used to increment value of ―i. This verity of for loop is not used
generally.
At the end of above for loop value of i will be 5.
CSE, MAIT
This is perfectly legal statement in C Programming. This statement is similar to bodyless for loop.
(Way 3)
CSE, MAIT
statement1; statement2; statement3;
if(breaking condition) break;
i++;
}
Infinite for loop must have breaking condition in order to break for loop. otherwise it will cause
overflow of stack.
Form Comment
CSE, MAIT
JUMP STATEMENTS:
Break statement
Break Statement Simply Terminate Loop and takes control out of the loop.
CSE, MAIT
Way 2 : Nested for
CSE, MAIT
Way 4 : While Loop
Continue statement:
loop
{
continue;
//code
}
Note :
It is used for skipping part of Loop.
Continue causes the remaining code inside a loop block to be skipped and causes execution to jump to
the top of the loop block
for
CSE, MAIT
while
do-while
Goto statement:
goto label;
label :
Whenever goto keyword encountered then it causes the program to continue on the line , so long as it
is in the scope .
CSE, MAIT
ARRAYS:
What is an array?
An array is a collection of similar datatype that are used to allocate memory in a sequential manner.
Syntax : <data type><array name>[<size of an array>]
Subscript or indexing: A subscript is property of an array that distinguishes all its stored elements
because all the elements in an array having the same name (i.e. the array name). so to distinguish
these, we use subscripting or indexing option.
e.g. int ar[20];
First element will be: int ar[0]; Second element will be: int ar[1]; Third element will be: int ar[2];
Fourth element will be: int ar[3]; Fifth element will be: int ar[4]; Sixth element will be: int ar[5]; So
on……………………
Last element will be: int ar[19];
NOTE: An array always starts from 0 indexing.
Example: int ar[20];
This above array will store 20 integer type values from 0 to 19. Advantage of an array:
Multiple elements are stored under a single unit.
Searching is fast because all the elements are stored in a sequence.
Types of Array
CSE, MAIT
Static Array
DynamicArray.
Static Array
An array with fixed size is said to be a static array. Types of static array:
One Dimensional Array
Two Dimensional Array.
Multi Dimensional Array.
Two DimensionalArray.
An array of an array is said to be 2 dimensional array , which stores data in column and row form
Example: int ar[4][5];
This above array is called two dimensional array because it will store all the elements in column and
in row form
NOTE: In above example of two dimensional array, we have 4 rows and 5 columns. NOTE: In above
example of two dimensional array, we have total of 20 elements.
Dynamic Array.
This type of array also does not exist in c and c++. Example: Program based upon array:
Question: WAP to store marks in 5 subjects for a student. Display marks in 2nd and 5thsubject.
#include<stdio.h>
#include<conio.h> void main()
{
int ar[5]; int i;
for(i=0;i<5;i++)
CSE, MAIT
{
printf(\n Enter marks in ,i, subject);
scanf(%d,&ar[i]);
}
printf(Marks in 2ndsubject is:,ar[1]);
printf(Marks in 5thsubject is:,ar[4]);
}
FUNCTIONS:
A function is itself a block of code which can solve simple or complex task/calculations.
A function performs calculations on the data provided to it is called "parameter" or "argument". A
function always returns single value result.
Types of function:
Built in functions (Library functions)
a.) Inputting Functions.
b.) Outputting functions.
Parts of a function:
Function declaration/Prototype/Syntax.
Function Calling.
Function Definition.
CSE, MAIT
1.)Function Declaration:
Syntax: <return type ><function name>(<type of argument>)
The declaration of function name, its argument and return type is called function declaration.
CSE, MAIT
int cube(int n)
{
Int c=n*n*n; return(c);
}
scanf("%d",&n);
f=fact(n);
printf("The factorial of a no. is:=%d",f);
}
int fact(int n);
int f=1;
{
for(int i=n;i>=n;i--)
{
f=f*i;
}
return(f);
}
Recursion
Firstly, what is nested function?
When a function invokes another function then it is called nested function. But,
When a function invokes itself then it is called recursion.
NOTE: In recursion, we must include a terminating condition so that it won't execute to infinite time.
CSE, MAIT
Example: program based upon recursion:
WAP to compute factorial of a no. using Recursion:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,f;
int fact(int) ;
printf("Enter a no.");
scanf("%d",&n);
f=fact(n);
printf("The factorial of a no. is:=%d",f);
}
int fact(int n)
int f=1;
{
if(n=0)
return(f);
else
return(n*fact(n-1));
}
Passing parameters to a function:
Firstly, what are parameters?
parameters are the values that are passed to a function for processing.
a.) ActualParameters:
These are the parameters which are used in main() function for function calling. Syntax: <variable
CSE, MAIT
name>=<function name><actual argument>
Example: f=fact(n);
b.) Formal Parameters.
These are the parameters which are used in function defination for processing.
Methods of parameters passing:
1.) Call by reference. 2.) Call by value.
1.) Call by reference:
In this method of parameter passing , original values of variables are passed from calling program to
function.
Thus,
Any change made in the function can be reflected back to the calling program.
CSE, MAIT
}
void swap(int x, int y)
{
int t;
t=x;
x=y;
y=t;
}
STORAGE CLASSES
Every Variable in a program has memory associated with it.
Memory Requirement of Variables is different for different types of variables. In C, Memory is
allocated & released at different places
Term Definition
Storage Class Manner in which memory is allocated by the Compiler for Variable
Different Storage Classes
CSE, MAIT
storage classes are declared inside main memory whereas variables declared with keyword register are
stored inside the CPU Register.
Scope of Variable
Scope of Variable tells compile about the visibility of Variable in the block. Variable may have Block
Scope, Local Scope and External Scope. A scope is the context within a computer program in which a
variable name or other identifier is valid and can be used, or within which a declaration has effect.
Default Initial Value of the Variable
Whenever we declare a Variable in C, garbage value is assigned to the variable. Garbage Value may
be considered as initial value of the variable. C Programming have different storage classes which has
different initial values such as Global Variable have Initial Value as 0 while the Local auto variable
have default initial garbage value.
Lifetime of variable
Lifetime of the = Time Of variable Declaration - Time of Variable Destruction
Suppose we have declared variable inside main function then variable will be destroyed only when the
control comes out of the main .i.e end of the program.
Storage Memory
CSE, MAIT
Scope Local / Block Scope
Example
void main()
{
auto mum = 20 ;
{
auto num = 60 ;
printf("nNum : %d",num);
}
printf("nNum : %d",num);
}
Output :
Num :60
Num :20
Note :
Two variables are declared in different blocks , so they are treated as different variables
External ( extern ) storage class in C Programming
Variables of this storage class are Global variables
Global Variables are declared outside the function and are accessible to all functions in the program
Generally , External variables are declared again in the function using keyword extern In order to
Explicit declaration of variable use ‘extern’ keyword
extern int num1 ; // Explicit Declaration
CSE, MAIT
Features :
Storage Memory
Example
int num = 75 ;
void display();
void main()
{
extern int num ;
printf("nNum : %d",num);
display();
}
void display()
{
extern int num ;
printf("nNum : %d",num);
}
Output :
Num :75
Num :75
Note :
Declaration within the function indicates that the function uses external variable
CSE, MAIT
Functions belonging to same source code , does not require declaration (no need to write extern) If
variable is defined outside the source code , then declaration using extern keyword is required
#include <stdio.h>
return0;
}
int num1,num2;
register int sum;
return(0);
}
Explanation of program
Refer below animation which depicts the register storage classes –
CSE, MAIT
In the above program we have declared two variables num1,num2. These two variables are stored in
RAM.
Another variable is declared which is stored in register variable. Register variables are stored in the
register of the microprocessor. Thus memory access will be faster than other variables.
If we try to declare more register variables then it can treat variables as Auto storage variables as
memory of microprocessor is fixed and limited.
Keyword Register
Keyword Register
CSE, MAIT
Life Local to the block in which variable is declared.
Preprocessor directives
Before a C program is compiled in a compiler, source code is processed by a program called
preprocessor. This process is called preprocessing.
Commands used in preprocessor are called preprocessor directives and they begin with ―#‖ symbol.
Below is the list of preprocessor directives that C language offers.
1 Macro #define
The source code of the
file ―file_name‖ is
included in the main
program at the specified
place
Header file #include
inclusion <file_name>
2
CSE, MAIT
Set of commands are
included or excluded in
source program before
compilation with respect
#ifdef, #endif, #if,
to the condition
#else,#ifndef
Conditional
compilation
3
#undef is used to
undefine a defined
macro variable.
#Pragma is used to
call a function before
and after main
Other function in a C
4 directives #undef, #pragma program
A program in C language involves into different processes. Below diagram will help you to
understand all the processes that a C program comes across.
void main()
{
printf("value of height : %d \n", height ); printf("value of number : %f \n", number ); printf("value of
letter : %c \n", letter );
CSE, MAIT
printf("value of letter_sequence : %s \n", letter_sequence); printf("value of backslash_char : %c \n",
backslash_char);
} OUTPUT:
int main()
{
#ifdef RAJU
printf("RAJU is defined. So, this line will be added in " \ "this C file\n");
#else
printf("RAJU is not defined\n"); #endif
return0;
}
OUTPUT:
CSE, MAIT
EXAMPLE PROGRAM FOR #IFNDEF AND #ENDIF INC:
#ifndef exactly acts as reverse as #ifdef directive. If particular macro is not defined, ―If clause
statements are included in source file.
Otherwise, else clause statements are included in source file for compilation and execution.
OUTPUT:
OUTPUT:
OUTPUT:
int main()
{
printf ( "\n Now we are in main function" ); return0;
CSE, MAIT
}
void function1( )
{
printf("\nFunction1 is called before main function call");
}
void function2( )
{
printf ( "\nFunction2 is called just before end of " \ "main function" ) ;"
}
OUTPUT:
CSE, MAIT
If function doesn‘t return a value, then
warnings are suppressed by this
directive while compiling.
STRINGS
What is String?
A string is a collection of characters.
A string is also called as an array of characters.
A String must access by %s access specifier in c andc++.
A string is always terminated with \0 (Null) character.
Example of string:
A string always recognized in double quotes.
A string also consider space as acharacter.
Example: Priyank Saxena
The above string contains 14 characters.
Example: Char ar[20]
The above example will store 19 character with 1 null character. Example: Program based
upon String.
WAP to accept a complete string (first name and last name) and display hello message in the
output.
CSE, MAIT
# include<stdio.h>
#include<conio.h>
#include<string.h>
void main ()
{
char str1[20];
char str2[20];
printf(“Enter First Name”);
scanf(“%s”,&str1);
printf(“Enter last Name”);
scanf(“%s”,&str2);
puts(str1);
puts(str2);
}
“ctype.h” header file support all the below functions in C language. Click on each function name
below for detail description and example programs.
Functions Description
CSE, MAIT
isalnum() Checks whether character is alphanumeric
String Functions in C:
Our c language provides us lot of string functions for manipulating the string. All the string functions
are available in string.h header file.
CSE, MAIT
strcmp()
strcat()
strcpy()
strrev()
strlen()
This string function is basically used for the purpose of computing the ength of string.
strupr()
This string function is basically used for the purpose of converting the case sensitiveness of the string
i.e. it converts string case sensitiveness into uppercase.
strlwr()
This string function is basically used for the purpose of converting the case sensitiveness of the string
i.e it converts string case sensitiveness into lowercase.
CSE, MAIT
strcmp()
This string function is basically used for the purpose of comparing two string. This string function
compares two strings character by characters.
Thus it gives result in three cases:
Case 1: if first string > than second string then, result will be true.
Case 2: if first string < than second string then, result will be false.
Case 3: if first string = = to second string then, result will be zero.
Example:
char str1=―Gaurav;
char str2=―Arora;
char str3=strcmp(str1,str2);
printf(―%s,str3);
strcat()
This string function is used for the purpose of concatenating two strings ie.(merging two or more
strings)
Example:
char str1 = ―Gaurav;
char str2 = ―Arora;
char str3[30];
str3=strcat(str1,str2);
printf(%s,str3);
strcpy()
This string function is basically used for the purpose of copying one string into another string. char
str1= ―Gaurav;
CSE, MAIT
char str2[20];
str2 = strcpy(str2,str1);
printf(%s,str2);
strrev()
This string function is basically used for the purpose of reversing the string.
char str1= ―Gaurav;
char str2[20];
str2= strrev(str2,str1);
printf(%s,str2);
CSE, MAIT
scanf(%s, &str);
printf(Enter your choice);
scanf(%d,&opt);
switch(opt)
{
case1: strupr(str);
printf(The string in uppercase is :%s ,str);
break;
case2:
strrev(str);
printf(―The reverse of string is : %s‖,str); break;
case3: strcpy(str1,str);
printf(―New copied string is : %s‖,str1); break;
case4: len=strlen(str);
printf(―The length of the string is : %s‖,len); break;
default: printf(―Ypuhave entered awrongchoice.‖);
}
CSE, MAIT