ECE - C Unit-II
ECE - C Unit-II
EC-405 PROGRAMMING IN C
UNIT - II
Conditional Statements and Arrays
Course Contents: If, If-else, Nested If else, Break, Continue, Switch statements Loops:- For, While, Do-
while,Nesting of Loops. 1 D Array declaration, Initialization, 2 D Array declaration, Initialization,
Accessing of Array elements.
⚫ The Conditional expression is also known as a ternary opeation, because it has three
operands.
⚫ These conditional operator are used to construct conditional expressions of the form.
▪ where Boolean epression is evaluated first. If it is non-zero (true), then the expression expr1
is evaluated, and that is the value of the conditional expression.
⚫ Otherwise expr2 is evaluated, and that is the value. Only one of expr1 and expr2 is
evaluated.
#include<stdio.h>
void main()
int a, b, x;
OUTPUT:
In the above program, When the user enter the value of a and b as 10 20, the condition
expression a>b is evaluated to false. Hence, Biggest Value is 20 is displayed on the screen.
When the user enter the value of a and b as 40 30, the condition expression a>b is evaluated
to true. Hence, Biggest Value is 40 is displayed on the screen.
Conditional Statements
▪ These conditions are specified by a set of conditional statements having Boolean expressions
which are evaluated to a Boolean value true or false.
1. If statement
2. If-Else statement
4. If-Else If ladder
5. Switch statement
If statement/Simple If statement:
▪ Syntax
▪ if(expression/condition)
▪ {
▪ //code to be executed
▪ }
▪ If the expression is evaluated to nonzero (true) then if block statement(s) are executed.
▪ If the expression is evaluated to zero (false) then Control passes to the next statement
following it.
if Statement Example
#include<stdio.h>
void main()
{
Write a program to check whether a given number is
int num=0;
even or odd by using bitwise logical operator.
#include<stdio.h>
printf("enter the number");
void main()
{
scanf("%d",&num);
int n;
printf("Enter an integer:");
if(num%2==0)
scanf("%d",&n);
if ( n & 1 == 1 )
{
printf("Odd\n");
printf("%d number in even",num); else
printf("Even\n");
} getch();
}
printf("%d number in odd",num); Output:
Enter an integer: 4
even
getch();
Output:
9 number is odd
NOTE: If the body of an if statement has only one statement, you do not need to use brackets {}.
If-else statement:
▪ The if-else statement in C language is used to execute the code if condition is true or false. It
is also called two-way selection statement.
Syntax : if(expression/condition)
//Statements
else
//Statements
▪ If the expression is evaluated to nonzero (true) then if block statement(s) are executed.
▪ If the expression is evaluated to zero (false) then else block statement(s) are executed.
getch();
Output:
▪ When a series of the decision are involved in a statement, we use if else statement in nested
form.
printf("Enter 3 number");
scanf("%d%d%d",&a,&b,&c);
if(a>b)
if(a>c)
printf("a is greatest");
else
printf("c is greatest");
else
if(b>c)
Output1:
{ Enter 3 number 30 20 10
a is greatest
printf("b is greatest"); Output2:
Enter 3 number 10 30 20
} b is greatest
Output3:
else Enter 3 number 10 20 30
c is greatest
{
printf("c is greatest");
getch();
If..else If ladder:
▪ The if-else-if statement is used to execute one code from multiple conditions. It is also called
multipath decision statement.
if(condition1)
//statements
else if(condition2)
//statements
else if(condition3)
//statements
else
//statements
#include<stdio.h>
void main()
int marks;
scanf("%d",&marks);
if(marks>75)
printf("grade A");
else if(marks>65)
printf("grade B");
Output1:
}
enter themarks:80
else if(marks>55)
grade A
{ Output2:
printf("grade C"); enter themarks:70
} grade B
Output3:
else if(marks>=45)
enter themarks: 60
{
grade C
printf("grade D"); Output4:
} enter themarks:50
else grade D
Output5:
{
enter themarks: 30
printf("fail");
fail
}
Switch Statement:
▪ A switch statement contains one or more case labels which are tested against the switch
expression.
▪ When the expression match to a case then the associated statements with that case would
be executed.
▪ Note:
Syntax:
Switch (expression)
Default: //Statements
#include <stdio.h>
main()
int num;
printf("Enter number:");
Write a program to check whether a given
scanf("%d",&num); character is vowel or consonant by using switch
case statement.
switch(num) #include <stdio.h>
int main()
{ {
char ch;
case 7: printf("Enter any alphabet: ");
scanf("%c", &ch);
printf("Value is 7"); switch(ch)
{
break; case 'a': case 'e': case 'i': case 'o':
case 'u': case 'A': case 'E': case 'I':
case 8: case 'O': case 'U':
printf("Vowel");
printf("Value is 8"); break;
default:
break; printf("Consonant");
}
case 9: return 0;
}
printf("Value is 9"); Output:
Enter any alphabet: b
break; Consonant
break;
return 0;
Output1:
Enter number:8
Value is 8
Output2:
Enter number:10
Out of range
Unconditional Statements
▪ In c, there are control statements that do not need any condition to control the program
execution flow. These control statements are called as unconditional control statements.
Break statement:
▪ A break statement terminates the execution of the loop and the control is transferred to the
statement immediately following the loop. i.e., the break statement is used to terminate
loops or to exit from a switch.
Syntax :
break;
Continue statement:
Continue is also a loop control statement just like the break statement.
Continue statement is opposite to that of break statement, instead of terminating the loop,
Statement 1;
continue;
Statement 2;
1. break statement is used in switch and continue statement is used in loops only.
loops.
3. Example: Example:
#include<stdio.h> #include<stdio.h>
int main(){ int main(){
int i; int i;
for(i=0;i<5;++i){ for(i=0;i<5;++i){
if(i==3) if(i==3)
break; continue;
printf(“%d “,i); printf(“%d “,i);
} }
return 0; return 0;
} }
OUTPUT: 0 1 2 OUTPUT: 0 1 2 4
Looping Statements:
▪ Looping statement is the statements execute one or more statement repeatedly several
number of times.
2. do-while
3. for
▪ When you need to execute a block of code several number of times then you need to use
looping concept in C language.
▪ Conditional statement executes only once in the program where as looping statements
executes repeatedly several number of time.
While loop
▪ The body of the loop will be executed repeatedly as long as the expression remains true.
When the while is reached, the computer evaluates
expression.
▪ If it is found to be false, body of loop will not be
executed, and the loop ends. Otherwise, the body of
loop will be executed, and then expression is checked
again and so on, till expressionbecomes false.
Syntax:
The while statement will be executed
repeatedly as long as the expression remains
true
Intialization;
while(condition) {
Statements; ......
Example:
int i=0;
while(i<3)
printf(“Hello\n”);
i++;
Output:
Hello
Hello
Hello
Do while Loop:
It is similar to that of while loop except that is always executes at least once. The test of
expression for repeating is done after each time body of loop is executed.
When we need to repeat the statement block at least 1 time then we use do-while loop.
Syntax:
do
<statement/block>;
}while(condition);
Example:
int i=0;
do
printf (“Hello\n”);
i++;
}while (i<3);
Output
Hello
Hello
Hello
For Loop:
Loop condition is tested before iteration to decide whether to continue or terminate the
loop.
Increment is executed at the end of each loop iteration.
Syntax:
<statement/block>;
Example:
printf(“Hello\n”);
Output:
Hello
Hello
Hello
temp=n;
while(n!=0)
{
reminder=n%10;
reverse=reverse*10+reminder;
n=n/10;
}
if(reverse==temp)
printf("Given number is palindrome");
else
printf("Given number is not palindrome");
}
Output:
enter a number:121
Given number is palindrome
4. Write a C program to check whether the given number is Armstrong or not.
If the sum of the cube of its digit is same as the number.
#include<stdio.h>
void main()
{ Number 153
int n,reminder,sum=0,temp;
printf("enter a number:"); Cube 13,33,53
scanf("%d",&n);
temp=n; Sum 13+33+53=153
do
{
reminder=n%10;
sum=sum+reminder*reminder*reminder;
n=n/10;
} while(n!=0);
if(sum==temp)
printf("Given number is Armstrong");
else
printf("Given number is not Armstrong");
}
Output:
enter a number:153
Given number is Armstrong
5. Write a C program to print factorial of given number.
#include<stdio.h>
void main()
{
int n,i,factorial=1;
printf("enter a number:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
factorial=factorial*i;
}
printf("factorial of %d! is %d",n,factorial);
}
Output:
enter a number:5
factorial of 5! is 120
scanf("%d",&n);
printf("fibonacci series are \t%d\t%d",first,second);
for(i=2;i<=n;i++)
{ \t Means One tab space
next=first+second;
first=second;
second=next;
printf("\t%d",next);
}
}
Output:
enter a number:5
fibonacci series are 0 1 1 2 3 5
7. Write a C program to check whether the given number is prime number or not.
#include<stdio.h> void main()
{
int n,i;
printf("enter a number:");
scanf("%d",&n);
for(i=2;i<=n-1;i++)
{
if(n%i==0)
break;
}
if(i==n)
{
printf(“%d is prime”,n);
Department of Computer Engineering
Aditya Polytechnic Colleges(255,249,404),Surampalem. Page 17
LECTURE NOTES
EC-405 PROGRAMMING IN C
}
else
printf(“%d is not prime”,n);
}
Output:
enter a number:5
5 is prime
{
int n,i=1,sum=0;
printf("Enter maximum values of series number: ");
scanf("%d",&n);
printf("Sum of the above given series : ");
for(i=1;i<=n;i++)
{
sum=sum+i*i;
printf("%d^2",i);
if(i<n)
{
printf("+");
}
}
printf("=%d",sum);
}
Output:
Enter maximum values of series number: 5
Sum of the above given series : 1^2 +2^2 +3^2 +4^2 +5^2 = 55
9. Write a C program to find the sum of the series : 12 + 32+ 52...................... + n2.
#include<stdio.h>
void main()
{
int n,i,sum=0;
printf("Enter maximum values of series number: ");
scanf("%d",&n);
printf("Sum of the above given series : ");
for(i=1;i<=n;i++)
{
if(i%2!=0)
{
sum=sum+i*i;
printf("%d^2",i);
if(i<n)
{
printf("+");
}
}
}
printf("=%d",sum);
}
Output:
Enter maximum values of series number: 5
Sum of the above given series : 1^2+3^2+5^2=35
Nesting loops
• When we need to repeated loop body itself n number of times use nested loops.
In the iterative loops, For loop is evaulated as first initialization after that it checks the
condition if the condition is true the for loop will be evaulated then it will print the inside for
loop statements and incrementing /decrementing the variable after the statements are
executed.
Syntax:
Nested for loop means another for loop inside the for loop.If the first for loop condition is
true it enters to the inner for loop if the inner for loop condition is also true then the inner
for loop statements will be executed and after the outer for loop statements will be
executed.
Incase if outer for loop is true then the inner for loop is false it will not print the inner for
loop statements.The outer for loop statements will be executed.Incase if outer for loop is
false then it will not evaulated the inner for loop and it will execute outer looping
statements.
Example:
▪ The nested while loop means any type of loop which is defined inside the 'while' loop.
Syntax:
while(condition)
while(condition)
Example:
▪ The nested do..While loop means any type of loop which is defined inside the 'do..while'
loop.
Syntax:
do
do
}while(condition);
}while(condition);
Example:
▪ Array is the collection of similar data types.An array is a variable that can store multiple
values.
▪ It is simply a group of data types. An array is a derived data type.An array is used to
represent a list of numbers, or a list of names.
Definition: Array is a sequence of memory locations for store in a list of homogeneous dataitems,
where each data item can be referred as using both common name (array name) andindex name
or index number.
▪ Here ‘list’ is array name variable, which can store 10 integer values. Therefore thespace
taken by the list is 20bytes.
▪ The arrays can be used to represent not only simple list of values but also task ofdata
items in two and three or more dimensions.
Types of Arrays
One-dimensional Arrays:
• A variable which represent the list of items using only one index (subscript) is
called one-dimensional array.
• For Example , if we want to represent a set of five numbers say(35,40,20,57,19), by
an array variable number, then number is declared asfollows int number [5];
• Here the type specifies the data type of elements contained in the array, such as int,float, or
char.
• And the size indicates the maximum numbers of elements that can be stored insidethe
array.
Here int is type, group is a variable name, 10 is a size of array and the subscripts (index) arestart
from 0 to 9.
Access Array Elements:
▪ Suppose you declared an array mark as below. The first element is mark[0], the second
element is mark[1] and so on. if int mark[5].
NOTE:
1. Arrays have 0 as the first index, not 1. In this example, mark[0] is the first element.
2. If the size of an array is n, to access the last element, the n-1 index is used. In this
example, mark[4].
3. Suppose the starting address of mark[0] is 1000d because the size of integer is 2 bytes when
it is 16bit of computer system. Then, the address of the mark[1] will be 1002d.
5. Suppose the starting address of mark[0] is 1000d because the size of integer is 2 bytes when
it is 32bit/64bit of computer system. Then, the address of the mark[1] will be 1004d.
▪ The general form of initialization of array is: datatype array-name[size] = { list of values };
▪ Here array number of size 3 and will assign 4 to first element(number[0]), 5 is assign with
second element(number[1]) and 9 is assign with third element(number[2]).
▪ If the number of values in the list is less than the number of elements, then only that many
elements will be intialized. The remaining elements will be set to zero automatically.
Example:
▪ The character array can also be initialized as follows : char name[ ] = “john”;
Example program:
1. The following program uses for loop to print elements of a 1-D array using Compile
time initialization.
#include<stdio.h>
void main()
{
int array[5]={1,2,3,4,5,6},i; //Initialization of array and declaraing of
array with multiple values
printf("Array of elements are:");
for(i=0;i<5;i++)
{
printf("%d",array[i]); // Acessing the elements of an array
}
}
Output:
Array of elements are:12345
Run time initialization:
• This approach is usually used for initializing large array, or to initialize array with user
specified values.
• Example:
for(i=0;i<5;i++)
scanf(“%d”, &a[i]);
• Here first 5 elements of the array are initialized during runtime initialization of elements of
an array.
Example program:
1. The following program uses for loop to take input and print elements of a 1-D array
using Run time initialization.
#include<stdio.h>
void main()
{
int a[10],i; //initialization of an array
printf("enter array elements:");
for(i=0;i<5;i++)
{
scanf("%d",&a[i]); //Acessing/Storing values of elements of an array
}
printf("Array of elements are:");
for(i=0;i<5;i++)
{
printf("%d",a[i]);//Acessing the elements of an array
}
}
Output:
enter array elements:1 2 3 4 5
Array of elements are:12345
for(i=2;i<10;i++)
{
fib[i]=fib[i-1]+fib[i-2];
printf("\t%d",fib[i]);
}
}
Output: Fibonacci series 0 1 1 2 3 5 8 13 21 34
Two-dimensional Arrays:
• A variable which represent the list of items using two index(subscript) is called two-
dimensional array.
• In Two dimensional arrays, the data is stored in rows and columns format.
datatype array-name[row_size][column_size];
• Here the type specifies the data type of elements contained in the array, such as int, float, or
char. The size should be either a numeric constant or a symbolic constant.
• Here the elements of first row initializes to zero and the elements of second row initializes
to one.
• If the values are missing in an initializer, they are automatically set to zero.
• Here first row initialize to 1, 1 and 2, and second row initialize to 0,0 and 0 automatically.
• In Two dimensional arrays, the data is stored in rows and columns format.
table[0][0] = 1;
table[0][1] = 2
table[0][2] = 3;
table[1][0] = 4;
table[1][1] = 5;
table[1][2] = 6;
#include<stdio.h>
void main()
{
int arrayname[2][2]={{0,1},{1,0}},i,j;
printf("2*2 Matrix A\n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d\t",arrayname[i][j]);
}
printf("\n");
}
}
Output:
2*2 Matrix A
0 1
1 0
Example of runtime Initialization of two dimensional array program.
#include<stdio.h>
void main()
{
int array[10][10],r,c;
printf("Enter elements of 2*2 matrix A");
for(r=0;r<2;r++)
{
for(c=0;c<2;c++)
{
scanf("%d",&array[r][c]);
}
}
printf("Elements are stored in array are:\n");
for(r=0;r<2;r++)
{
for(c=0;c<2;c++)
{
printf("%d\t",array[r][c]);
}
printf("\n");
}
}
Output:
Enter elements of 2*2 matrix A
1 2
3 4
Elements are stored in array are:
1 2
3 4
#include<stdio.h>
void main()
{
int a[2][2],b[2][2],d[2][2],r,c;
printf("Enter elements of 2*2 matrix of A:");
for(r=0;r<2;r++)
{
for(c=0;c<=1;c++)
{
scanf("%d",&a[r][c]);
}
}
//Matrix Of B
printf("Enter elements of 2*2 matrix of B:");
for(r=0;r<=1;r++)
{
for(c=0;c<=1;c++)
{
scanf("%d",&b[r][c]);
}
}
for(c=0;c<=1;c++)
{
scanf("%d",&b[r][c]);
}
}
printf("Result of matrix Multiplication:\n");
for(r=0;r<=1;r++)
{
for(c=0;c<=1;c++)
{
d[r][c]=0;//d[0][1]=0
for(k=0;k<=1;k++)
{
d[r][c]=d[r][c]+a[r][k]*b[k][c];
}
}
}
//Printing Matrix Elements
for(r=0;r<=1;r++)
{
for(c=0;c<=1;c++)
{
printf("%d\t",d[r][c]);
}
printf("\n");
}
}
Output:
enter element of 2*2 matrix A:
1 2
3 4
enter element of 2*2 matrix B:
3 2
1 0
Result of matrix Multiplication:
5 2
13 6
Write a C program to find largest / smallest number in an array
#include<stdio.h>
int main()
{
int a[50],i,n,large,small;
printf("\nEnter the number of elements : ");
scanf("%d",&n);
printf("\nInput the array elements : ");
for(i=0;i<n;++i)
{
scanf("%d",&a[i]); OUTPUT:
} Enter the number of elements : 5
large=small=a[0]; Input the array elements : 10 5 20 34 1
The smallest element is 1
for(i=1;i<n;++i)
{
The largest element is 34
if(a[i]>large)
large=a[i];
if(a[i]<small)
small=a[i];
}
printf("\nThe smallest element is %d\n",small);
printf("\nThe largest element is %d\n",large);
return 0;
}
Write a C program to sort the numbers in an array in ascending order
#include <stdio.h>
void main()
{
int num[20];
int i,j,a,n;
printf("enter number of elements in an array\n");
scanf("%d",&n);
printf("Enter the elements\n");
for (i=0;i<n;i++) OUTPUT:
enter number of elements in an array
{ 5
scanf("%d",&num[i]); Enter the elements
} 10 5 7 20 30
for (i=0;i<n;i++) The numbers in ascending order is:
{ 5
for (j=i+1;j<n;j++) 7
10
{ 20
if (num[i]>num[j]) 30
{
a=num[i];
num[i]=num[j];
num[j]=a;
}
}
}
printf("The numbers in ascending order is:\n");
for (i = 0; i < n; ++i)
{
printf("%d\n", num[i]);
}
}
Department of Computer Engineering
Aditya Polytechnic Colleges(255,249,404),Surampalem. Page 33
LECTURE NOTES
EC-405 PROGRAMMING IN C