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
Create PDF files without this message by purchasing novaPDF printer ([Link]
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”
Create PDF files without this message by purchasing novaPDF printer ([Link]
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
{
Create PDF files without this message by purchasing novaPDF printer ([Link]
printf("Student is Fail");
}
}
Output :
Student is Pass
Flowchart : If Else Statement
Create PDF files without this message by purchasing novaPDF printer ([Link]
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");
}
Create PDF files without this message by purchasing novaPDF printer ([Link]
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.
Create PDF files without this message by purchasing novaPDF printer ([Link]
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:
Create PDF files without this message by purchasing novaPDF printer ([Link]
*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;
}
}
Create PDF files without this message by purchasing novaPDF printer ([Link]
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
Loop
Initialization , Incrementation and Condition steps are on different Line.
Create PDF files without this message by purchasing novaPDF printer ([Link]
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;
do
{
Create PDF files without this message by purchasing novaPDF printer ([Link]
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:
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.
Create PDF files without this message by purchasing novaPDF printer ([Link]
Different Ways of Using For Loop in C Programming
In order to do certain actions multiple times, we use loop control statements. For loop can be
implemented in different verities of using for loop –
Single Statement inside For Loop
Multiple Statements inside ForLoop
No Statement inside For Loop
Semicolon at the end of For Loop
Multiple Initialization Statement inside For
Missing Initialization in For Loop
Missing Increment/Decrement Statement
Infinite For Loop
Condition with no Conditional Operator.
Create PDF files without this message by purchasing novaPDF printer ([Link]
Way2: Multiple Statements inside For Loop
for(i=0;i<5;i++)
{
printf("Statement1");
printf("Statement2");
printf("Statement3");
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.
Create PDF files without this message by purchasing novaPDF printer ([Link]
Way5: Multiple Initialization Statement inside For
for(i=0,j=0;i<5;i++)
{
statement1; statement2; statement3;
}
Multiple initialization statements must be seperated by Comma in for loop.
Create PDF files without this message by purchasing novaPDF printer ([Link]
Infinite for loop must have breaking condition in order to break for loop. otherwise it will cause
overflow of stack.
Form Comment
Create PDF files without this message by purchasing novaPDF printer ([Link]
JUMP STATEMENTS:
Break statement
Break Statement Simply Terminate Loop and takes control out of the loop.
Create PDF files without this message by purchasing novaPDF printer ([Link]
Way 2 : Nested for
Create PDF files without this message by purchasing novaPDF printer ([Link]
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
while
Create PDF files without this message by purchasing novaPDF printer ([Link]
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 .
Create PDF files without this message by purchasing novaPDF printer ([Link]
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
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.
Create PDF files without this message by purchasing novaPDF printer ([Link]
One Dimensional Array
An Array of elements is called 1 dimensional, which stores data in column or row form. Example: int
ar[5];
This above array is called one dimensional array because it will store all the elements in column or in
row form
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++)
{
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]);
}
Create PDF files without this message by purchasing novaPDF printer ([Link]
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.
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.
Create PDF files without this message by purchasing novaPDF printer ([Link]
3.) Function definition:
The process of writing a code for performing any specific task is called function defination. Syntax:
<return type><function name>(<type of arguments>)
{
<statement-1>
<statement-2>
return(<vlaue>)
}
Example: program based upon function:
WAP to compute cube of a no. using function.
#include<stdio.h>
#include<conio.h>
void main()
{
int c,n;
int cube(int);
printf("Enter a no.");
scanf("%d",&n);
c=cube(n);
printf("cube of a no. is=%d",c);
}
int cube(int n)
{
Int c=n*n*n; return(c);
}
Create PDF files without this message by purchasing novaPDF printer ([Link]
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.
Create PDF files without this message by purchasing novaPDF printer ([Link]
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
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.
Create PDF files without this message by purchasing novaPDF printer ([Link]
2.) Call by value.
In this method of parameter passing, duplicate values of parameters are passed from calling program
to function defination.
Thus,
Any change made in function would not be reflected back to the calling program.
Create PDF files without this message by purchasing novaPDF printer ([Link]
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
Create PDF files without this message by purchasing novaPDF printer ([Link]
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
Example
void main()
{
auto mum = 20 ;
{
Create PDF files without this message by purchasing novaPDF printer ([Link]
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
Features :
Storage Memory
Example
int num = 75 ;
void display();
Create PDF files without this message by purchasing novaPDF printer ([Link]
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
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
Create PDF files without this message by purchasing novaPDF printer ([Link]
#include <stdio.h>
return0;
}
Create PDF files without this message by purchasing novaPDF printer ([Link]
{
int num1,num2;
register int sum;
return(0);
}
Explanation of program
Refer below animation which depicts the register storage classes –
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
Create PDF files without this message by purchasing novaPDF printer ([Link]
memory of microprocessor is fixed and limited.
Keyword Register
Keyword Register
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.
Create PDF files without this message by purchasing novaPDF printer ([Link]
[Link] Preprocessor Syntax Description
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
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
Create PDF files without this message by purchasing novaPDF printer ([Link]
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 );
printf("value of letter_sequence : %s \n", letter_sequence); printf("value of backslash_char : %c \n",
backslash_char);
} OUTPUT:
Create PDF files without this message by purchasing novaPDF printer ([Link]
#include <stdio.h> #define RAJU 100
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:
Create PDF files without this message by purchasing novaPDF printer ([Link]
OUTPUT:
OUTPUT:
Create PDF files without this message by purchasing novaPDF printer ([Link]
OUTPUT:
int main()
{
printf ( "\n Now we are in main function" ); return0;
}
void function1( )
{
printf("\nFunction1 is called before main function call");
}
void function2( )
{
printf ( "\nFunction2 is called just before end of " \ "main function" ) ;"
}
OUTPUT:
Create PDF files without this message by purchasing novaPDF printer ([Link]
MORE ON PRAGMA DIRECTIVE IN C:
2
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.
Create PDF files without this message by purchasing novaPDF printer ([Link]
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.
# 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);
}
Create PDF files without this message by purchasing novaPDF printer ([Link]
Character Library Functions:
“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
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.
Create PDF files without this message by purchasing novaPDF printer ([Link]
These String functions are:
strlen()
strupr()
strlwr()
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.
Create PDF files without this message by purchasing novaPDF printer ([Link]
Example: char str=―gaurav
strlwr(str);
printf(The Lowercase of the string is:%s ,str);
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);
Create PDF files without this message by purchasing novaPDF printer ([Link]
strcpy()
This string function is basically used for the purpose of copying one string into another string. char
str1= ―Gaurav;
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);
Create PDF files without this message by purchasing novaPDF printer ([Link]
printf(\n 2. Reverse the string‖);
printf(\n 3. Copy one string into another string‖);
printf(\n [Link] length of string‖);
printf(Enter string‖);
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.‖);
}
Create PDF files without this message by purchasing novaPDF printer ([Link]