KEMBAR78
ECE - C Unit-II | PDF | Control Flow | Boolean Data Type
0% found this document useful (0 votes)
9 views34 pages

ECE - C Unit-II

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views34 pages

ECE - C Unit-II

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

LECTURE NOTES

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.

Importance of conditional expression:

⚫ 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.

⚫ A ternary operator pair “? : ” is available in C to construct conditional expressions in the


form of

Boolean epression ? expr1 : expr2

▪ 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.

Conditional Operators Example

#include<stdio.h>

void main()

int a, b, x;

printf("Enter the values of a add b : ");

scanf("%d %d", &a, &b);

(a>b)?printf("Biggest value is %d",a):printf("Biggest value is %d",b);

OUTPUT:

Enter the value of a and b: 10 20 Enter the value of a and b: 40 30

Biggest Value is: 20 Biggest Value is: 40

Department of Computer Engineering


Aditya Polytechnic Colleges(255,249,404),Surampalem. Page 1
LECTURE NOTES
EC-405 PROGRAMMING IN C

 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

▪ Conditional statements help you to make a decision based on certain conditions.

▪ These conditions are specified by a set of conditional statements having Boolean expressions
which are evaluated to a Boolean value true or false.

▪ There are following types of conditional statements in C.

1. If statement

2. If-Else statement

3. Nested If-else statement

4. If-Else If ladder

5. Switch statement

If statement/Simple If statement:

▪ The single if statement in C language is used


to execute the code if a condition is true. It
is also called one-way selection statement.

▪ Syntax

▪ if(expression/condition)

▪ {

▪ //code to be executed

▪ }

How "if" statement works..

▪ 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()

Department of Computer Engineering


Aditya Polytechnic Colleges(255,249,404),Surampalem. Page 2
LECTURE NOTES
EC-405 PROGRAMMING IN C

{
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:

enter the number 9

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

How "if..else" statement works..

Department of Computer Engineering


Aditya Polytechnic Colleges(255,249,404),Surampalem. Page 3
LECTURE NOTES
EC-405 PROGRAMMING IN C

▪ 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.

if..else Statement Example

#include<stdio.h> Leap year or not a leap year:


#include<stdio.h>
void main() void main()
{
{ int year;
printf("Enter a year: ");
int num=0; scanf("%d", &year);
if(((year%4==0) && ((year%400==0) ||
printf("enter the number"); (year%100!==0))
{
scanf("%d",&num); printf("%d is a leap year", year);
}
if(num%2==0) else
{
{ printf("%d is not a leap year", year);
}
printf("%d number is even", num); getch();
}
} Output:
Enter a year: 2004
else 2004 is a leap year

printf("%d number is odd",num);

getch();

Output:

enter the number 5 enter the number 8

5 number is odd 8 number is even

Nested If-else statement:


▪ The nested if...else statement is used when a program requires more than one test
expression. It is also called a multi-way selection statement.

▪ When a series of the decision are involved in a statement, we use if else statement in nested
form.

Department of Computer Engineering


Aditya Polytechnic Colleges(255,249,404),Surampalem. Page 4
LECTURE NOTES
EC-405 PROGRAMMING IN C

Syntax: Write a program to perform arithmetic operations using


switch case statement.
if( expression ) #include<stdio.h>
void main()
{ {
int a,b;
if( expression1 ) int op;
printf(" 1.Addition\n 2.Subtraction\n 3.Multiplication\n
{ 4.Division\n");
printf("Enter the values of a & b: ");
statement-block1; scanf("%d %d",&a,&b);
printf("Enter your Choice : ");
} scanf("%d",&op);
switch(op)
else {
case 1 :
{ printf("Sum of %d and %d is : %d",a,b,a+b);
break;
statement-block 2; case 2 :
printf("Difference of %d and %d is : %d",a,b,a-b);
} break;
case 3 :
} printf("Multiplication of %d and %d is : %d",a,b,a*b);
break;
else case 4 :
printf("Division of Two Numbers is %d : ",a/b);
{ break;
default :
statement-block 3; printf(" Enter Your Correct Choice.");
break;
} }
getch();
Nested If-else statement Example }
OUTPUT:
#include<stdio.h> 1.Addition
2.Subtraction
void main( ) 3.Multiplication
4.Division
{ Enter the values of a & b: 10 20
Enter your Choice : 1
int a,b,c; Sum of 10 and 20 is : 30

printf("Enter 3 number");

scanf("%d%d%d",&a,&b,&c);

if(a>b)

if(a>c)

Department of Computer Engineering


Aditya Polytechnic Colleges(255,249,404),Surampalem. Page 5
LECTURE NOTES
EC-405 PROGRAMMING IN 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.

▪ It is a chain of if..else statements in which each if statement is associated with else if


statement and last would be an else statement.
Syntax

if(condition1)

Department of Computer Engineering


Aditya Polytechnic Colleges(255,249,404),Surampalem. Page 6
LECTURE NOTES
EC-405 PROGRAMMING IN C

//statements

else if(condition2)

//statements

else if(condition3)

//statements

else

//statements

If..else If ladder Example:

#include<stdio.h>

void main()

int marks;

printf("enter the marks:");

scanf("%d",&marks);

if(marks>75)

printf("grade A");

else if(marks>65)

Department of Computer Engineering


Aditya Polytechnic Colleges(255,249,404),Surampalem. Page 7
LECTURE NOTES
EC-405 PROGRAMMING IN C

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:

1. The switch statement must be an integral type.

2. Case labels must be constants.

3. Case labels must be unique.

4. Case labels must end with a colon.

5. The break statement transfers the control out of switch statement.

Syntax:

Department of Computer Engineering


Aditya Polytechnic Colleges(255,249,404),Surampalem. Page 8
LECTURE NOTES
EC-405 PROGRAMMING IN C

Switch (expression)

case value1: //Statements break;

case value 2: //Statements break;

case value 3: //Statements

case value n: //Statements break;

Default: //Statements

Switch statement Example

#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

default: printf("Out of range");

Department of Computer Engineering


Aditya Polytechnic Colleges(255,249,404),Surampalem. Page 9
LECTURE NOTES
EC-405 PROGRAMMING IN C

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.

▪ C programming language provides the following unconditional control statements...


1. break
2. continue
3. goto
▪ The above three statements do not need any condition to control the program executionflow.

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.

▪ It can be used within for, while, do-while, or switch statement.

▪ The break statement is written simply as break;

▪ In case of inner loops, it terminates the control of inner loop only.

Syntax :

 Break is a keyword used to terminate loop or to exit


from switch statement.
 It is written as
statements;

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,

Department of Computer Engineering


Aditya Polytechnic Colleges(255,249,404),Surampalem. Page 10
LECTURE NOTES
EC-405 PROGRAMMING IN C

it forces to execute the next iteration of the loop.


 As the name suggest the continue statement forces the loop to continue or execute the next
iteration.
 When the continue statement is executed in the loop, the code inside the loop following the
continue statement will be skipped and next iteration of the loop will begin.
Syntax:

 This is used to skip some of the statements in a loop.


 It will be in the form:

Statement 1;

continue;

Statement 2;

 Here statement 2 is skipped when


continue statement is executed.

Difference between break and continue

S.No. break continue

1. break statement is used in switch and continue statement is used in loops only.
loops.

2. When break is encountered the switch When continue is encountered, the


or loop execution is immediately statements after it are skipped and the
stopped. loop control jump to next iteration.

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.

Department of Computer Engineering


Aditya Polytechnic Colleges(255,249,404),Surampalem. Page 11
LECTURE NOTES
EC-405 PROGRAMMING IN C

▪ In C programming language there are three types of loops


1. while

2. do-while

3. for

Why use loop?

▪ When you need to execute a block of code several number of times then you need to use
looping concept in C language.

Advantage with looping statement:

▪ Reduce length of Code

▪ Take less memory space.

▪ Burden on the developer is reducing.

▪ Time consuming process to execute the program is reduced.

Difference between conditional and looping statement

▪ 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.

▪ It is also called as Entry - controlled loop.

Syntax:
 The while statement will be executed
repeatedly as long as the expression remains
true

Intialization;

while(condition) {

Statements; ......

Increment/decrements (++ or --);


}
Department of Computer Engineering
Aditya Polytechnic Colleges(255,249,404),Surampalem. Page 12
LECTURE NOTES
EC-405 PROGRAMMING IN C

Note: If while loop condition never false then loop


becomes infinite loop.

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.

 It is also called as exit controlled loop.

When use do..while Loop:

 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

Department of Computer Engineering


Aditya Polytechnic Colleges(255,249,404),Surampalem. Page 13
LECTURE NOTES
EC-405 PROGRAMMING IN C

printf (“Hello\n”);

i++;

}while (i<3);

Output

Hello

Hello

Hello

For Loop:

For loop has three parts:

 Initializer is executed at start of 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.

 It is another entry controlled statement.

Syntax:

for( [initialize]; [condition]; [increment/decrement] )

<statement/block>;

Example:

for(i=0; i<3; i++)

printf(“Hello\n”);

Output:

Hello
Hello
Hello

Department of Computer Engineering


Aditya Polytechnic Colleges(255,249,404),Surampalem. Page 14
LECTURE NOTES
EC-405 PROGRAMMING IN C

1. Write a C program to print sum of n natural numbers using while loop.


The positive numbers 1,2,3,… are known as natural numbers. The sum of
naturalnumbers upto 10 is: sum=1+2+3+….+10
#include<stdio.h>
void main()
{
int i=1,n,sum=0;
printf("enter n natural number:");
scanf("%d",&n);
while(i<=n)
{
sum+=i;
i++;
}
printf("sum of %d natural number is %d",n,sum);
}
Output:
enter n natural number:10
sum of 10 natural number is 55
2. Write a C program to print sum of digits of given number.
#include<stdio.h>
void main() Number 135
{
int n,rem,sum=0; Digit 1,3,5
printf("enter number:");
scanf("%d",&n); Sum 1+3+5=9
while(n!=0)
{
rem=n%10;
sum=sum+rem;
n=n/10;
}
printf("sum of digits is %d",sum);
}
Output:
enter number:135
sum of digits is 9

3. Write a C program to check given number is a palindrome or not.


An integer is a palindrome if the reverse of that number is equal to the original number.
#include<stdio.h>
void main()
{
int n,reminder,reverse=0,temp;
printf("enter a number:");
scanf("%d",&n);
Department of Computer Engineering
Aditya Polytechnic Colleges(255,249,404),Surampalem. Page 15
LECTURE NOTES
EC-405 PROGRAMMING IN C

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:");

Department of Computer Engineering


Aditya Polytechnic Colleges(255,249,404),Surampalem. Page 16
LECTURE NOTES
EC-405 PROGRAMMING IN C

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

6. Write a C program to print fibonacci numbers.


#include<stdio.h>
void main()
{
int n,i,first=0,second=1,next;
printf("enter a number:");

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

8. Write a C program to find the sum of the series : 12 + 22 + 32 ............. + n2.


#include<stdio.h>
void main()

{
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);

Department of Computer Engineering


Aditya Polytechnic Colleges(255,249,404),Surampalem. Page 18
LECTURE NOTES
EC-405 PROGRAMMING IN C

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

10. Write a program to print even and odd number upto 1 to n.


#include <stdio.h>
void main()
{
int i,num;
printf("Print all even number until\n");
scanf("%d",&num);
printf("Even number from 1 to %d are\n",num);
for(i=1; i<=num; i++)
{
if(i%2==0)
{
printf("even numbers is %d\n",i);
}
else
printf("odd numbers is %d\n",i);
}
getch();
}
OUTPUT:
Print all even number until 1 to
5
Even number from 1 to 5 are
odd numbers is 1
even numbers is 2
odd numbers is 3
even numbers is 4
odd numbers is 5

Department of Computer Engineering


Aditya Polytechnic Colleges(255,249,404),Surampalem. Page 19
LECTURE NOTES
EC-405 PROGRAMMING IN C

Nesting loops

• In Nested loop one loop is place within another loop body.

• It is called as nested loops.

• When we need to repeated loop body itself n number of times use nested loops.

• Nested loops can be design upto 255 blocks.


Write a program to print prime numbers between
two given numbers
Syntax of Nested loop #include<stdio.h>
void main()
1. Outer_loop {
int i,j,n,c;
2. { printf("Enter max range\n");
scanf("%d",&n);
3. Inner_loop printf("Prime numbers are:-\n");
for(i=2;i<=n;i++)
4. { {
c=0;
5. // inner loop statements. for(j=1;j<=i;j++)
{
6. } if(i%j==0)
{
7. // outer loop statements. c++;
}
8. } }

TYPES OF NESTED LOOP if(c==2)


{
There are three types of nested loops.They are: printf("%d ",i);
}
1. NESTED FOR LOOP }
}
2. NESTED WHILE LOOP OUTPUT:
Enter max range
3. NESTED DO-WHILE LOOP 6
Prime numbers are:-
NESTED FOR LOOP: 235

 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:

for (initialization; condition; update)

for(initialization; condition; update)

Department of Computer Engineering


Aditya Polytechnic Colleges(255,249,404),Surampalem. Page 20
LECTURE NOTES
EC-405 PROGRAMMING IN C

// inner loop statements.

// outer loop statements.

 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:

 To print the following series:


*
**
***
****
*****
#include<stdio.h>
void main()
{
int rows,column;
rows=1;
while(rows<=5)
{
column=1;
while(column<=rows)
{
printf("*");
column++;
}
rows++;
printf("\n");
}
}

Nested while loop:

▪ The nested while loop means any type of loop which is defined inside the 'while' loop.

Department of Computer Engineering


Aditya Polytechnic Colleges(255,249,404),Surampalem. Page 21
LECTURE NOTES
EC-405 PROGRAMMING IN C

Syntax:

while(condition)

while(condition)

// inner loop statements.

// outer loop statements.

Example:

 To print the following series:


*
**
***
****
*****
#include<stdio.h>
void main()
{
int rows,column;
rows=1;
while(rows<=5)
{
column=1;
while(column<=rows)
{
printf("*");
column++;
}
rows++;
printf("\n");
}
}

Nested do..while loop:

▪ The nested do..While loop means any type of loop which is defined inside the 'do..while'
loop.

Department of Computer Engineering


Aditya Polytechnic Colleges(255,249,404),Surampalem. Page 22
LECTURE NOTES
EC-405 PROGRAMMING IN C

Syntax:
do

do

// inner loop statements.

}while(condition);

// outer loop statements.

}while(condition);

Example:

 To print the following series:


***
***
***
***
***
#include<stdio.h>
void main()
{
int rows,columns;
rows=1;
do
{
columns=1;
do
{
printf("*");
columns++;
}while(columns<=3);
printf("\n");
rows++;
}while(rows<=5);
}
What is Array?

▪ 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.

Department of Computer Engineering


Aditya Polytechnic Colleges(255,249,404),Surampalem. Page 23
LECTURE NOTES
EC-405 PROGRAMMING IN C

▪ Array of character is a string. Each data item of an array is called an element.

▪ And each element is unique and located in separated memory location.

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.

▪ Syntax: Data type arrayname [size];

▪ Example: int list [10];

▪ Here ‘list’ is array name variable, which can store 10 integer values. Therefore thespace
taken by the list is 20bytes.

▪ Here list is a array name and [10] is called index or subscript.

▪ 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

 In C language, there are three types of array.They are:


1. One-dimensional arrays
2. Two-dimensional arrays
3. Multidimensional 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];

• And the computer store these numbers as shown below:


number [0]
number [1]
number [2]
number [3]
number [4]

• The values can be assigned to the array as follows :


number [0] = 35;
number [1] = 40;
number [2] = 20;
number [3] = 57;
number [4] = 19;

Department of Computer Engineering


Aditya Polytechnic Colleges(255,249,404),Surampalem. Page 24
LECTURE NOTES
EC-405 PROGRAMMING IN C

DECLARATION OF ONE-DIMENSIONAL ARRAYS

• The general form of array declaration is : datatype array-name[size];

• 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.

• The size should be either a numeric constant or a symbolic constant.

Example: int group [10] ;

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:

▪ You can access elements of an array by indices.

▪ 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.

4. Similarly, the address of mark[2] will be 1004dd and so on.

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.

6. Similarly, the address of mark[2] will be 1008dd and so on.

INITIALIZATION OF ONE-DIMENSIONAL ARRAYS:

▪ After an array is declared, its elements must be initialized.otherwise,they will


contain”garbage” values.An array can be initialized for stored the values or elements in
following stages :
1. At compile time
2. At run time
Department of Computer Engineering
Aditya Polytechnic Colleges(255,249,404),Surampalem. Page 25
LECTURE NOTES
EC-405 PROGRAMMING IN C

Compile time initialization:


▪ In compile time initialization, the array is initialized when they are declared.

▪ The general form of initialization of array is: datatype array-name[size] = { list of values };

▪ The list of values is separated by commas.

Example: int number[3] = {4,5,9};

▪ 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 integer array can be initialized as follows:

▪ int number[ ] = {1,2,3,4};

▪ The character array can be initialized as follows :

▪ char name[ ] = {‘j’,’o’,’h’,’n’,’\0’};

▪ 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:

• In run time initialization, the array is explicitly initialize at run time.

• An array can also be initialized at runtime using scanf() function.

Department of Computer Engineering


Aditya Polytechnic Colleges(255,249,404),Surampalem. Page 26
LECTURE NOTES
EC-405 PROGRAMMING IN C

• 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

2. Write a C program to print fibonacci series using an arrays.


#include<stdio.h>
void main()
{
int fib[10],i;
fib[0]=0;
fib[1]=1;
//0 1 1 2 3 5
printf("Fibonacci series %d\t%d",fib[0],fib[1]);

Department of Computer Engineering


Aditya Polytechnic Colleges(255,249,404),Surampalem. Page 27
LECTURE NOTES
EC-405 PROGRAMMING IN C

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.

Example: int table[2][3];

DECLARATION OF TWO-DIMENSIONAL ARRAYS:

• The general form of two dimensional array declaration is :

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.

INITIALIZATION OF TWO-DIMENSIONAL ARRAYS:

• The general form of initializing two-dimensional array is :

datatype array_name[row_size][column_size] = {list of values};

Example: int table[2][3] = {0,0,0,1,1,1};

• Here the elements of first row initializes to zero and the elements of second row initializes
to one.

• This above statement can be written as : int table[2][3] = {{0,0,0}, {1,1,1}};

• In two-dimensional array the row_size can be omitted.

Example: int table[ ][3] = {{0,0,0}, {1,1,1}};

• If the values are missing in an initializer, they are automatically set to zero.

Example: int table[2][3] = {1,1,2};

• Here first row initialize to 1, 1 and 2, and second row initialize to 0,0 and 0 automatically.

Memory Layout of Two-dimensional array:

• In Two dimensional arrays, the data is stored in rows and columns format.

Department of Computer Engineering


Aditya Polytechnic Colleges(255,249,404),Surampalem. Page 28
LECTURE NOTES
EC-405 PROGRAMMING IN C

• For example: int table[2][3] = {1,2,3,4,5,6};


• The memory layout of above example :

table[0][0] = 1;

table[0][1] = 2

table[0][2] = 3;

table[1][0] = 4;

table[1][1] = 5;

table[1][2] = 6;

Example of Compile time Initialization of two dimensional array program.

#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]);
}

Department of Computer Engineering


Aditya Polytechnic Colleges(255,249,404),Surampalem. Page 29
LECTURE NOTES
EC-405 PROGRAMMING IN 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

Addition Matrix Program:

#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]);
}
}

Department of Computer Engineering


Aditya Polytechnic Colleges(255,249,404),Surampalem. Page 30
LECTURE NOTES
EC-405 PROGRAMMING IN C

printf("Resultant Matric of C:\n");


for(r=0;r<=1;r++)
{
for(c=0;c<=1;c++)
{
d[r][c]=a[r][c]+b[r][c];
}
}
//Printing the Resultant element matrix of C
for(r=0;r<=1;r++)
{
for(c=0;c<=1;c++)
{
printf("%d\t",d[r][c]);
}
printf("\n");
}
}
Output:
Enter elements of 2*2 matrix of A:
1 2
3 4
Enter elements of 2*2 matrix of B:
3 2
1 0
Resultant Matric of C:
4 4
4 4
Matrix Multiplication Program:
#include<stdio.h>
void main()
{
int a[2][2] ,b[2][2],d[2][2],r,c,k;
printf("enter element of 2*2 matrix A:");
for(r=0;r<=1;r++)
{
for(c=0;c<=1;c++)
{
scanf("%d",&a[r][c]);
}
}
printf("enter element of 2*2 matrix B:");
for(r=0;r<=1;r++)
{
Department of Computer Engineering
Aditya Polytechnic Colleges(255,249,404),Surampalem. Page 31
LECTURE NOTES
EC-405 PROGRAMMING IN 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 : ");

Department of Computer Engineering


Aditya Polytechnic Colleges(255,249,404),Surampalem. Page 32
LECTURE NOTES
EC-405 PROGRAMMING IN C

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

Write a C program to find sum of elements of an array


#include <stdio.h>
#define MAX_SIZE 100
int main()
{
int arr[MAX_SIZE];
int i, n, sum=0;

printf("Enter size of the array: ");


scanf("%d", &n);

printf("Enter %d elements in the array: ", n);


for(i=0; i<n; i++)
{
scanf("%d", &arr[i]);
}
for(i=0; i<n; i++)
{
sum = sum + arr[i];
}
printf("Sum of all elements of array = %d", sum);
return 0;
}
OUTPUT:
Enter size of the array: 5
Enter 5 elements in the array: 10 20 1 2 2
Sum of all elements of array = 35

Department of Computer Engineering


Aditya Polytechnic Colleges(255,249,404),Surampalem. Page 34

You might also like