Unit Iii
Unit Iii
UNIT III
Decision making statements - Switch statement - Looping statements – Pre-processor
directives - Compilation process – One dimensional array – Two dimensional array –
Multidimensional array.
Flow of control: The order in which the program statements are executed is known as flow
of control. By default, statements in a c program are executed in a sequential order.
The default flow of control can be altered by using flow control statements. These
statements are of two types.
Selection-Conditional Branching
1.Branching
Jump-unconditional Branching
2.Iteration statements
Branching statements
Branching statements are used to transfer program control from one point to another.
2 types
a) Conditional Branching:- Program control is transferred from one point to another
based on the result of some condition
Eg) if, if-else, switch
b) Unconditional Branching:- Program control is transferred from one point to another
without checking any condition
Eg) goto, break, continue, return
T
Statement
1
24CSE401 - UNIT III
else
printf(“The number is odd”);
getch();
}
Output:
Enter a number:15
The number is odd
v) Switch statement
It is a multi way branch statement.
It provides an easy & organized way to select among multiple operations depending
upon some condition.
Execution
1. Switch expression is evaluated.
2. The result is compared with all the cases.
3. If one of the cases is matched, then all the statements after that matched case gets
executed.
4. If no match occurs, then all the statements after the default statement get executed.
Switch ,case, break and default are keywords
Break statement is used to exit from the current case structure
Flowchart
switch(expression)
case: break
constant 0 statement
case :
statement break
constant 1
default
statement break
Syntax
switch(expression) End of switch
{
case value 1:
program statement;
program statement;
……
break;
case value 2:
program statement;
Program statement;
……
break;
…
case value n:
program statement;
program statement;
……
break; 5
default:
program statement;
program statement;
}
24CSE401 - UNIT III
Example1
void main()
{
char ch;
printf(“Enter a character \n”);
scanf(“%c”,&ch);
switch(ch)
{
case ‘A’:
printf(“you entered an A\n”);
break;
case ‘B’:
printf(“you entered a B\n”);
break;
default:
printf(“Illegal entry”);
break;
}
getch();
}
Output
Enter a character
A
You entered an A
Example2
void main()
{
int n;
printf(“Enter a number \n”);
scanf(“%d”,&n);
switch(n%2)
{
case 0:printf(“EVEN \n”);
break;
case 1:printf(“ODD \n”);
break;
}
getch();
}
Output:
Enter a number
5
ODD
6
24CSE401 - UNIT III
b)break statement
A break statement can appear only inside a body of , a switch or a loop
A break statement terminates the execution of the nearest enclosing loop or
switch.
Syntax
break;
break;
Example:1
#include<stdio.h>
void main()
{
int c=1;
while(c<=5)
{
if (c==3)
break;
printf(“\t %d”,c);
c++;
7
24CSE401 - UNIT III
}
}
Output : 1 2
Example :2
#include<stdio.h>
void main()
{
int i;
for(i=0;i<=10;i++)
{
if (i==5)
break;
printf(“ %d”,i);
}
}
Output :1 2 3 4
Example :1
#include<stdio.h>
void main()
{
int c=1;
while(c<=5)
{
if (c==3)
continue;
printf(“\t %d”,c);
c++;
}
}
Output : 1 2 4 5
Example :2
#include<stdio.h>
main()
{
int i;
8
24CSE401 - UNIT III
for(i=0;i<=10;i++)
{
if (i==5)
continue;
printf(“ %d”,i);
}
}
Output :1 2 3 4 6 7 8 9 10
return;
(or)
return expression;
1. for loop
It is the most popular looping statement.
Syntax:
for(initialization;condition2;incrementing/updating)
{
Statements; 9
}
24CSE401 - UNIT III
2. while statement
They are also known as Entry controlled loops because here the condition is checked before the
execution of loop body.
Syntax:
10
24CSE401 - UNIT III
while (expression)
{
statements;
}
3. do while statement
11
24CSE401 - UNIT III
They are also known as Exit controlled loops because here the condition is checked after the
execution of loop body.
Syntax:
do
{
statements;
}
while(expression);
The body of do-while is executed once, even when the condition is initially false.
4
Sum=10
Nested loops
If the body of a loop contains another iteration statement, then we say that the loops are nested.
Loops within a loop are known as nested loop.
Syntax
while(condition)
{
while(condition)
{
Statements;
}
Statements;
}
PRE-PROCESSOR DIRECTIVES
The C preprocessor is a microprocessor that is used by compiler to transform your code before
compilation. It is called micro preprocessor because it allows us to add macros. Preprocessor
directives are executed before compilation.
1. #include Used to paste code of given file into current #include <filename>
file. It is used include system-defined and #include “filename”
user-defined header files. If included file is
not found, compiler renders error.
2. #define Used to define constant or micro #define PI 3.14
substitution. It can use any basic data type
3. #undef Used to undefine the constant or macro #define PI 3.14
defined by #define #undef PI
4. #ifdef Checks if macro is defined by #define. If #ifdef MACRO
yes, it executes the code otherwise #else //code
code is executed, if present. #endif
5. #ifndef Checks if macro is not defined by #define. #ifndef MACRO
If yes, it executes the code otherwise #else //code
code is executed, if present. #endif
COMPILATION PROCESS
What is compilation?
Compilation is the process the computer takes to transform a program written in a high-level language
from source code into machine code that the computer can understand.
14
24CSE401 - UNIT III
Compiling a C Program
A sequence of binary instructions consisting of 1 and 0 bits is called as machine code. High-level
programming languages such as C, C++, Java, etc. consist of keywords that are closer to human
languages such as English. Hence, a program written in C (or any other high-level language) needs to
be converted to its equivalent machine code. This process is called compilation.
Note that the machine code is specific to the hardware architecture and the operating system. In other
words, the machine code of a certain C program compiled on a computer with Windows OS will not
be compatible with another computer using Linux OS. Hence, we must use the compiler suitable for
the target OS.
In this tutorial, we will be using the gcc (which stands for GNU Compiler Collection). The GNU
project is a free-software project by Richard Stallman that allows developers to have access to
powerful tools for free.
The gcc compiler supports various programming languages, including C. In order to use it, we should
install its version compatible with the target computer.
15
24CSE401 - UNIT III
Preprocessing
Compiling
Assembling
Linking
16
24CSE401 - UNIT III
Example
To understand this process, let us consider the following source code in C languge (main.c) -
Output
The ".c" is a file extension that usually means the file is written in C. The first line is the preprocessor
directive #include that tells the compiler to include the stdio.h header file. The text
inside /* and */ are comments and these are useful for documentation purpose.
The entry point of the program is the main() function. It means the program will start by executing
the statements that are inside this function’s block. Here, in the given program code, there are only
two statements: one that will print the sentence "Hello World" on the terminal, and another statement
that tells the program to "return 0" if it exited or ended correctly. So, once we compiled it, if we run
this program we will only see the phrase "Hello World" appearing.
17
24CSE401 - UNIT III
In order for our "main.c" code to be executable, we need to enter the command "gcc main.c", and the
compiling process will go through all of the four steps it contains.
Step 1: Preprocessing
It includes the code of the header file(s), which is a file with extension .h which contains C
function declarations and macro definitions.
It replaces all of the macros (fragments of code which have been given a name) by their values.
The output of this step will be stored in a file with a ".i" extension, so here it will be in "main.i".
In order to stop the compilation right after this step, we can use the option "-E" with the gcc
command on the source file, and press Enter.
Step 2: Compiling
The compiler generates the IR code (Intermediate Representation) from the preprocessed file, so this
will produce a ".s" file. That being said, other compilers might produce assembly code at this step of
compilation.
We can stop after this step with the "-S" option on the gcc command, and press Enter.
18
24CSE401 - UNIT III
Step 3: Assembling
The assembler takes the IR code and transforms it into object code, that is code in machine language
(i.e. binary). This will produce a file ending in ".o".
We can stop the compilation process after this step by using the option "-c" with the gcc command,
and pressing Enter.
19
24CSE401 - UNIT III
Note that the "main.o" file is not a text file, hence its contents won't be readable when you open this
file with a text editor.
Step 4: Linking
The linker creates the final executable, in binary. It links object codes of all the source files together.
The linker knows where to look for the function definitions in the static libraries or the dynamic
libraries.
Static libraries are the result of the linker making a copy of all the used library functions to the
executable file. The code in dynamic libraries is not copied entirely, only the name of the library is
placed in the binary file.
By default, after this fourth and last step, that is when you type the whole "gcc main.c" command
without any options, the compiler will create an executable program called main.out (or main.exe in
case of Windows) that we can run from the command line.
We can also choose to create an executable program with the name we want, by adding the "-o"
option to the gcc command, placed after the name of the file or files we are compiling.
So now we could either type "./hello.out" if you didn’t use the "-o" option or "./hello" to execute the
compiled code. The output will be "Hello World" and following it, the shell prompt will appear
again.
20
24CSE401 - UNIT III
Arrays
Definition:
An array is a data structure that is used to store data of the same type. The position of an
element is specified with an integer value known as index or subscript.
E.g.
1 3 5 2 a(integer array)
char b[5]={‘A’.’r’,’r’};
22
24CSE401 - UNIT III
EXAMPLE PROGRAMS:
1.Computing Mean
2.Computing Median
3.Computing Mode
1.Computing Mean:
\* C Program to to find the mean of n numbers using array *\
#include <stdio.h>
void main()
{
int m[5],i,sum=0,n;
float mean;
printf(“enter number of students \n”);
scanf(“%d”,&n);
printf(“enter marks of students \n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&m[i]);
}
for(i=0;i<n;i++)
sum=sum+m[i];
mean=(float)sum/n;
printf(“Mean=%f”,mean);
}
Output:
Enter number of students
5
Enter marks of students
55
60
78
85
90
Mean=73.6
2.Computing Median:
#include<stdio.h>
#include<conio.h>
main()
{
int i,j,temp,n,a[20],sum=0;
float median;
printf("enter n:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
23
24CSE401 - UNIT III
3.Computing Mode:
#include<stdio.h>
#include<conio.h>
void main()
{
int maxvalue = 0, maxCount = 0, i, j,a[20],n,count=0;
clrscr();
printf("enter the N value:");
scanf("%d",&n);
for(i = 0; i < n;i++)
{
24
24CSE401 - UNIT III
Declaration
25
24CSE401 - UNIT III
Initialization
1. By using an initialization list, 2D array can be initialized.
e.g. int a[2][3] = {1,4,6,2}
1 4 6
a
2 0 0
Output:
Enter the rows and columns of two matrices…. 3 3
Enter the elements of A matrix… 1 2 3 4 5 6 7 8 9
Enter the elements of B matrix… 1 2 3 4 5 6 7 8 9
The addition of two matrixes
246
8 10 12
14 16 18
}
printf("Product matrix C\n");
for(i=0; i<r1; i++)
{
for(j=0; j<c2; j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
getch();
}
Output
Enter order of matrix A : 2 3
Enter order of matrix B : 3 2
Enter matrix A elements
111
111
Enter matrix B elements
22
22
22
Product matrix C
66
66
y1=(y1*y);
x2=(x2*x);
y2=(y2*y);
printf("Line after scaling");
line(x1,y1,x2,y2);
getch();
closegraph();
}
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[2][2],i,j;
long determinant;
clrscr();
printf("Enter the 4 elements of matrix: ");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
scanf("%d",&a[i][j]);
}
printf("\nThe matrix is\n");
{
for(i=0;i<2;i++)
{
printf("\n");
for(j=0;j<2;j++)
printf("%d\t",a[i][j]);
}
}
29
24CSE401 - UNIT III
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],i,j;
long determinant;
clrscr();
printf("Enter the 9 elements of matrix: ");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
}
printf("\nThe matrix is\n");
for(i=0;i<3;i++)
{
printf("\n");
for(j=0;j<3;j++)
printf("%d\t",a[i][j]);
}
30
24CSE401 - UNIT III
31
24CSE401 - UNIT III
Output:
How many rows 2
How many columns 2
3.Multidimensional array
A multidimensional array in simple terms is an array of arrays. Like we have one index in a
one-dimensional array, two indices in a two-dimensional array, in the same way we have n
indices in an n-dimensional array or multidimensional array. Conversely, an n-dimensional
array is specified using n indices. An n-dimensional m1 × m2 × m3 ×….. mn array is a
collection m1 * m2 * m3 *…… *mn ements. In a multidimensional array, a particular element is
specified by using n subscripts as A[I1] [I2] [I3]..... [In], where,
A multidimensional array can contain as many indices as needed and the requirement of the
memory increases with the number of indices used. However, practically speaking we will
hardly use more than three indices in any program. Figure 5.32 shows a three-dimensional
array. The array has three pages, four rows, and two columns.
32
24CSE401 - UNIT III
Example
Consider a three-dimensional array defined as int A[2][2][3]. Calculate the number of
elements in the array. Also show the memory representation of the array in row major order
and column major order.
Note
A three-dimensional array consists of pages. Each page in turn contains m rows and n
columns.
#include <stdio.h>
#include <conio.h>
int main()
{
int array [2] [2] [2], i, j, k;
clrscr();
printf("\n Enter the elements of the matrix");
for (i = 0; i < 2;i++)
{
for(j=0;j< 2;j++)
{
for (k=0; k < 2;k++)
scanf("%d", &array [i] [j] [k]);
}
}
}
33
24CSE401 - UNIT III
Output
Enter the elements of the matrix
12345678
The matrix is:
arr [0] [0] [0] = 1 arr [0] [0] [1] = 2
arr [0] [1] [0] = 3 arr [0] [1] [1] = 4
arr [1] [0] [0] = 5 arr [1] [0] [1] = 6
arr [1] [1] [0] = 7 arr [1] [1] [1] = 8
34