Unit 2
Unit 2
Programming in C
STATEMENTS
A statement causes the computer to carry out some definite action. There are three
different classes of statements in C:
.
Selection Statement/Conditional
Statements/Decision Making Statements
.
Simple if statement.
#include<stdio.h>
main()
{
int a=15,b=20;
if(b>a)
{
printf("b is greater");
}
}
Output
b is greater
.
If-else statement
#include <stdio.h>
int main()
{ int number;
printf("Enter an integer: ");
scanf("%d",&number);
// True if remainder is 0
if( number%2 == 0 )
printf("%d is an even integer.",number);
else
printf("%d is an odd integer.",number);
return 0;
}
Output
Enter an integer: 7
7 is an odd integer
.
Nested if-else statement
int var1, var2;
printf("Input the value of var1:");
scanf("%d", &var1);
printf("Input the value of var2:");
scanf("%d",&var2);
if (var1 !=var2)
{
printf("var1 is not equal to var2");
//Below – if-else is nested inside another if
block
if (var1 >var2)
{
printf("var1 is greater than var2");
}
else
{
printf("var2 is greater than var1");
}
}
else{
printf("var1 is equal to var2");
. }
Else if ladder
#include<stdio.h>
Syntax : if( condition-1) #include<conio.h>
{ void main(){
statement-1; int number=0;
} clrscr();
else if(condition-2) printf("enter a number:");
{ scanf("%d",&number);
statement-2; if(number==10){
} printf("number is equals to 10");
else if(condition-3) }
{ else if(number==50){
statement-3; printf("number is equal to 50");
} }
else if(condition-n) else if(number==100){
{ printf("number is equal to 100");
statement-n; }
} else{
else printf("number is not equal to 10, 50 or 100");
{ }
default-statement; getch();
} }
.statement-x;
Points to Remember
1. In if statement, a single statement can be included without enclosing it into curly
braces { }
int a = 5;
if(a > 4)
printf("success");
No curly braces are required in the above case, but if we have more than one
statement inside if condition, then we must enclose them inside curly braces.
5. == must be used for comparison in the expression of if condition, if you use = the
expression will always return true, because it performs assignment not comparison.
if(a==7)
6. Other than 0(zero), all other values are considered as true.
7. if(27)
8. printf("hello");
In above example, hello will be printed.
.
Switch statement
#include<stdio.h> #include<stdio.h>
main() main()
{ {
int a=15,b=20; int a=15,b=20; // b=15 and a=20 same
if(b>a) answer
{ if(b>a);
printf("b is greater"); {
} printf("b is greater");
} }
Output }
b is greater Output
b is greater
Switch statement
Syntax:
switch(expression)
{
case value-1:
statement/block-1;
break;
case value-2:
statement/block t-2;
break;
case value-3:
statement/block -3;
break;
case value-4:
statement/block -4;
break;
default:
default- statement/block t;
break; }}
Switch statement
#include<stdio.h> printf("You chose Two");
int main() break;
{ case 3:
int a; printf("You chose Three");
printf("Please enter a no between 1 and 5: break;
"); case 4:
scanf("%d",&a); printf("You chose Four");
switch(a) break;
{ case 5: printf("You chose Five.");
case 1: break;
printf("You chose One"); default :
break; printf("Invalid Choice. Enter a no between
case 2: 1 and 5"); break;
}}
Switch statement
Switch statement
1 : while loop
2 : do-while loop
3 : for loop
Iterative/Repetitive loops
Example:
For Loop:
#include<stdio.h>
#include<conio.h>
Syntax : for(initialization; condition; void main( )
increment/decrement) {
{
Statements;
int x;
} for(x=1; x<=10; x++)
{
printf("%d\t",x);
}
getch();
}
Output
1 2 3 4 5 6 7 8 9 10
Iterative/Repetitive loops
For Loop:
• This is an entry controlled looping statement.
• In this loop structure, more than one variable can be initialized.
• One of the most important features of this loop is that the three actions can be taken at a
time like variable initialization, condition checking and increment/decrement.
• The for loop can be more concise and flexible than that of while and do-while loops.
Iterative/Repetitive loops
While Loop #include<stdio.h>
Syntax : #include<conio.h>
variable initialization ; void main( )
while (condition) {int x=1;
{ while(x<=10)
statements ; {
variable increment or decrement ; printf("%d\t", x);
} x++;
}
getch();
}
Output
1 2 3 4 5 6 7 8 9 10
Iterative/Repetitive loops
For Loop While Loop
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void main( ) void main( )
{ {int x=1;
int x; while(x<=10)
for(x=1; x<=10; x++) {
{ printf("%d\t", x);
printf("%d\t",x); x++;
} }
getch(); getch();
} }
Output
1 2 3 4 5 6 7 8 9 10 Output
1 2 3 4 5 6 7 8 9 10
Iterative/Repetitive loops
While Loop
The while loop is an entry controlled loop
statement, i.e means the condition is evaluated
first and it is true, then the body of the loop is
executed.
Iterative/Repetitive loops
do-while loop #include<stdio.h>
#include<conio.h>
void main()
Syntax : variable initialization ; {
do{ int a,i;
statements ; a=5;
variable increment or decrement ; i=1;
}while (condition); do
{
printf("%d\t",a*i);
i++;
}while(i <= 10);
getch();
}
Output
5 10 15 20 25 30 35 40 45 50
Iterative/Repetitive loops
do-while loop
The do-while loop is an exit controlled loop
statement The body of the loop are executed first
and then the condition is evaluated. If it is true,
then the body of the loop is executed once again.
Nested for loop
#include<stdio.h>
#include<conio.h> Output
void main( ) 1
{ 21
int i,j; 321
for(i=1;i<5;i++) 4321
{ 54321
printf("\n") ;
for(j=i;j>0;j--)
{
printf("%d",j);
}
}
getch();
}
Nested for loop
#include<stdio.h>
#include<conio.h>
void main() Output
{ 1
int i,j,n; 12
clrscr(); 123
printf("Enter number of rows: "); 1234
scanf("%d",&n); 12345
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
printf("%d",j);
}
printf("\n");
}
getch();
}
Nested for loop
#include<stdio.h>
#include<conio.h>
void main() Output
{ 54321
int i,j,n; 4321
clrscr(); 321
printf("Enter number of rows: "); 21
scanf("%d",&n); 1
for(i=n;i>=1;i--)
{
for(j=i;j>=1;j--)
{
printf("%d ",j);
}
printf("\n");
}
getch();
}
Nested for loop
#include<stdio.h> for(i=n;i>=1;i--)
#include<conio.h> {
void main() for(j=1;j<=i;j++)
{ {
int i,j,n; printf("%d ",j);
clrscr(); }
printf("Enter number of rows: "); printf("\n");
scanf("%d",&n); }
for(i=1;i<=n;i++) getch();
{ }
for(j=1;j<=i;j++) Output
{ 1
12
printf("%d ",j); 123
} 1234
12345
printf("\n"); 1234
} 123
12
1
Jump Statements
Jumping statements are used to transfer the program‟s control from one location to another, these are
set of keywords which are responsible to transfer program‟s control within the same block or from one
function to another.
goto statement doesnot require any condition. This statement passes control
anywhere in the program i.e, control is transferred to another part of the program without testing
any condition.
Break Statement
Output
12345
Jump Statements
Continue Statement
Output
1234678910
Jump Statements
#include <stdio.h> printf("\nThe loop with continue produces output
as: \n");
int main() for (int i = 1; i <= 7; i++) {
{
for(j=0;j<4;j++)
Runtime Array initialization
{
An array can also be initialized at runtime using scanf() printf("%d\n",arr[j]);
function. }
Example getch();
#include<stdio.h> }
#include<conio.h>
void main()
{
int arr[4];
int i, j;
printf("Enter array element");
for(i=0;i<4;i++)
{
scanf("%d",&arr[i]); //Run time array initialization
}
ARRAYS
int a[5]={10,20,30,40,50};
1 : Initializing all specified memory locations During compilation, 5 contiguous memory locations are
2 : Partial array initialization. reserved by the compiler for the variable a and all these
3 : Intilization without size. locations are initialized.
4 : String initialization. a[0] a[1] a[2] a[3] a[4]
10 20 30 40 50
1000 1002 1004 1006 1008
1 : Initializing all specified memory locations Eventhough compiler allocates 5 memory locations,
2 : Partial array initialization. using this declaration statement, the compiler initializes
3 : Intilization without size. first two locations with 10 and 20, the next set of
4 : String initialization. memory locations are automatically initialized to zero.
}
Runtime Array initialization
for(j=0;j<4;j++)
An array can also be initialized at runtime using scanf() {
function. printf("%d\n",arr[j]);
Example }
#include<stdio.h> getch();
#include<conio.h> }
void main()
{
int arr[]; //error
int arr[1],b;
int i, j;
printf(“Enter the no of element”);
printf("Enter array element");
scanf(“%d”,&b);
for(i=0;i<b;i++)
{
scanf("%d",&arr[i]); //Run time array initialization
Two‐Dimensional Arrays
data_type array_name[size1][size2];
Example
int twodimen[4][3];
Example :
int a[3][4];
Two‐Dimensional Arrays
Output
Initialization of 2D Array
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
arr[0][0] = 1
arr[0][1] = 2
Accessing Two-Dimensional Array Elements arr[0][2] = 3
Example arr[1][0] = 2
1. #include <stdio.h> arr[1][1] = 3
2. #include <conio.h> arr[1][2] = 4
3. void main(){ arr[2][0] = 3
4. int i=0,j=0; arr[2][1] = 4
5. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
arr[2][2] = 5
6. clrscr();
7. for(i=0;i<4;i++){
arr[3][0] = 4
8. for(j=0;j<3;j++){ arr[3][1] = 5
9. printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]); arr[3][2] = 6
10. }//end of j
11. }//end of i
12. getch();
13. }
Two‐Dimensional Arrays
Example Write a C program Addition of Two Matrices printf("\nThe elements of A matrics");
#include<stdio.h>
for(i=0;i<m;i++)
#include<conio.h>void main()
{ {
int a[25][25],b[25][25],c[25][25],i,j,m,n; printf("\n");
clrscr(); for(j=0;j<n;j++)printf("\t%d",a[i][j]);
printf("enter the rows and colums of two matrics:\n"); }
scanf("%d%d",&m,&n); printf("\nThe elements of B matrics");
printf("\nenter the elements of A matrics"); for(i=0;i<m;i++)
for(i=0;i<m;i++) {
{ printf("\n");
for(j=0;j<n;j++)
for(j=0;j<n;j++)
scanf("\t%d",&a[i][j]);
} printf("\t%d",b[i][j]);
printf("\nenter the elements of B matrics"); }
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("\t%d",&b[i][j]);
Two‐Dimensional Arrays
printf("\nThe additon of two matrics");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
printf("\t%d",c[i][j]);
}
}
getch();
}
Multidimensional Arrays
Initialization of a three dimensional array. printf("\nDisplaying values:\n");
for(i = 0; i < 2; ++i) {
int test[2][3][4] = {
{ {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} }, for (j = 0; j < 3; ++j) {
{ {13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9} } for(k = 0; k < 2; ++k ) {
}; printf("test[%d][%d][%d] = %d\n", i, j, k, test[i][j]
#include <stdio.h> [k]);
int main() }
{ }
// this array can store 12 elements }
int i, j, k, test[2][3][2]; return 0;
printf("Enter 12 values: \n");
}
for(i = 0; i < 2; ++i) {
for (j = 0; j < 3; ++j) {
for(k = 0; k < 2; ++k ) {
scanf("%d", &test[i][j][k]);
}
}
}
Multidimensional Arrays
Output
Enter 12 values:
123456789101112
Displaying Values:
test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[0][1][1] = 4
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12
FUNCTIONS
Definition: A function is a block of code/group of
statements/self contained block of statements/
basic building blocks in a program that performs a
particular task. It is also known as procedure or
subroutine or module, in other programming languages.
Advantage of functions
1) Code Reusability
By creating functions in C, you can call it many times. So
we don't need to write the same code
again and again.
2) Code optimization
It makes the code optimized we don't need to write
much code.
3) Easily to debug the program.
FUNCTIONS
Types of Functions
There are two types of functions in C programming: 2. User-defined functions: are the functions which are
created by the C programmer, so
1. Library Functions: are the functions which are that he/she can use it many times. It reduces complexity
declared in the C header files such as of a big program and optimizes
scanf(), printf(), gets(), puts(), ceil(), floor() etc. You just the code. Depending upon the complexity and
need to include appropriate header files to use these requirement of the program, you can create
functions. These are already declared and defined in C as many user-defined functions as you want
libraries.
Points to be Remembered
System defined functions are declared in header files
System defined functions are implemented in .dll files.
(DLL stands for Dynamic Link Library).
To use system defined functions the respective header
file must be included.
FUNCTIONS
FUNCTIONS
ELEMENTS OF USER-DEFINED FUNCTIONS
#include<conio.h> {
• the life of the variable is until the control remains within the block.
Example:
void main()
int detail;
or
Storage Classes
void function1()
1: Automatic Storage class : {
int x=10;
void function1();
printf(“%d”,x);
void function2(); }
void function2()
void main() {
int x=0;
{ function1();
int x=100; printf(“%d”,x);
}
function2();
printf(“%d”,x);
}
Storage Classes
• the life of the variable is until the control remains within the block.
Register variable has faster access than normal variable. Frequently used variables are kept in
demo();
demo();
}
Storage Classes
demo();
demo();
}
Storage Classes
• the life of the variable is until the program execution comes to an end.
• To define a variable as external storage class, the keyword extern is used. An extern variable is also called as a global
variable
extern int i;
Storage Classes
When function is called within the same function, it is known as recursion in C. The function which calls the
same function, is known as recursive function.
A function that calls itself, and doesn't perform any task after function call, is know as tail recursion. In tail
recursion, we generally call the same function with return statement.
Features :
• There should be at least one if statement used to terminate recursion.
Advantages :
It is easy to use.
Disadvantages :
It is slower than that of looping statements because each time function is called.
Recursion
if (n == 0)
}
STRINGS
String is an array of characters that is terminated by \0 (null character). This null character indicates the end
of the string. Strings are always enclosed by double quotes ( " " ). Whereas, character is enclosed by single
quotes.
Using this declaration the compiler allocates 9 memory locations for the variable a ranging from 0 to 8.
Initializing Array string
char str[5]={'5','+','A'};
str[0]; ---> 5
str[1]; ---> +
str[2]; ---> A
Note: In initialization of the string we can not initialized more than size of string elements.
Ex:
Char b[9]={’C’,’O’,’M’,’P’,’U’,’T’,’E’,’R’};
The compiler allocates 9 memory locations ranging from 0 to 8 and these locations are initialized with the
characters in the order specified. The remaining locations are automatically initialized to null characters.
2 : Partial Array Initilization :
If the characters to be initialized is less than the size of the array, then the characters are stored sequentially
from left to right.The remaining locations will be initialized to NULL characters automatically.
int a[10]={‘R’,’A’,’M’,’A’ };
3 : Initilization without size :
:consider the declaration along with the initialization
char b[]={‘C’,’O’,’M’,’P’,’U’,’T’,’E’,’R’};
In this declaration, The compiler will set the array size to the total number of initial values i.e 8. The
character will be stored in these memory locations in the order specified.
4) Array Initilization with a String :
consider the declaration with string initialization.
char b[ ] = “COMPUTER”;
Here, the string length is 8 bytes. But , string size is 9 bytes. So the compiler reserves 8+1 memory
locations and these locations are initialized with the characters in the order specified. The string is
terminated by \0 by the compiler.
String Handling Functions
OUTPUT :
The string length of JBREC is : 5
The string length of JBRECECE is :8
2 : strcpy(string1,string2) – String Copy :
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str1[]="REDDY";
char str2[10];
strcpy(str2,str1);
printf("The string1 is :%s\n",str1);
printf("The string2 is :%s\n",str2);
strcpy(str2,str1+1);
printf("The string1 is :%s\n",str1);
printf("The string2 is :%s",str2);
}
OUTPUT :
The string1 is : REDDY
The string2 is : REDDY
The string1 is : REDDY
String Copy(w/o string function) :
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[10],str2[20];
int index;
printf("Enter the string\n");
scanf(“%s”,str1);
for(index=0;str1[index]!='\0';index++)
str2[index]=str1[index];
str2[index]='\0';
printf("String1 is :%s\n",str1);
printf("String2 is :%s\n",str2);
getch();
}
OUTPUT :
Enter the string : cprogramming
String1 is : cprogramming
String2 is : cprogramming
3: strcat(string1,string2) – String Concatenation :
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
void main()
{
{
char str1[10]="jbrec";
char str2[]="ece";
strcat(str1,str2);
printf("%s\n",str1);
printf("%s\n",str2);
getch();
}
OUTPUT : jbrecece
ece
String Concatenation (W/O using String function)
#include<stdio.h>
void main(void)
{
char str1[25],str2[25];
int i=0,j=0;
printf("\nEnter First String:");
gets(str1);
printf("\nEnter Second String:");
gets(str2);
while(str1[i]!='\0')
i++;
while(str2[j]!='\0')
{
str1[i]=str2[j];
j++;
i++;
}
str1[i]='\0';
printf("\nConcatenated String is %s",str1);
}
4 : strlwr(string) – String LowerCase
: #include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
void main()
{
char str[]="JBREC";
clrscr();
strlwr(str);
printf("The lowercase is :%s\n",str);
getch()
}
OUTPUT :
The lowercase is : jbrec
string LowerCase w/o using string
function
#include<stdio.h>
#include<conio.h>
void main()
{
char str[10];
int index;
printf("Enter the string:");
scanf("%s",str);
for(index=0;str[index]!='\0';index++)
{
if(str[index]>='A' && str[index]<='Z')
str[index]=str[index]+32;
}
printf("After conversionis :%s",str);
getch()
}
OUTPUT : 0 -1 32
String Comparision w/o using string
function
#include<stdio.h>
#include<conio.h> if(str1[index]!=str2[index])
#include<string.h>
{
void main()
flag=0;
{
break;
char str1[10],str2[20];
}
int index,l1,l2,flag=1;
}
printf("Enter first string:");
}
scanf("%s",str1);
else
printf("Enter second string:");
flag=0;
scanf("%s",str2);
if(flag==1)
l1=strlen(str1);
printf("Strings are equal");
l2=strlen(str2);
else
printf("Length of string1:%d\n",l1);
printf("Strings are not equal");
printf("Length of string2:%d\n",l2);
}
if(l1==l2)
{
for(index=0;str1[index]!='\0';index++)
{
7 : strrev(string) - String Reverse :
#include<stdio.h>
#include<conio.h> OUTPUT : Enter the string :subbareddy
#include<string.h> The string reversed is : ydderabbus
void main()
{
char str[20];
printf("Enter the string:");
scanf("%s",str);
printf("The string reversed is:%s",strrev(str));
getch();
}
String reverse w/o using string
function
include <stdio.h>
OUTPUT : Enter the string :subbareddy
#include <string.h>
The string reversed is : ydderabbus
void main(){
char string[20],temp;
int i,length;
printf("Enter String : ");
scanf("%s",string);
printf("%d", strlen(string)/2);
length=strlen(string)-1;
for(i=0;i<strlen(string)/2;i++){
temp=string[i];
string[i]=string[length];
string[length--]=temp;
}
printf("Reverse string :%s",string);