Lecture Five
Lecture Five
Sometimes the program needs to be executed depending upon a particular condition. C provides
the following statements for implementing the selection control structure.
if statement
if else statement
nested if statement
switch statement
if statement
syntax of the if statement
if (condition)
{
statement(s);
}
If the condition is true, the statement is executed; otherwise, it is skipped. The statement may
either be single or compound.
#include <stdio.h>
int main()
{
int number;
if (number < 0)
{
number = - number;
}
return 0;
}
Output:
Enter a number: -15
The absolute value of number is 15
if else statement
if (condition)
statement1;
else
statement2;
The given condition is evaluated first. If the condition is true, statement1 is executed. If the
condition is false, statement2 is executed. It should be kept in mind that statement and
statement2 can be single or compound.
#include <stdio.h>
int main()
{
int num1, num2;
return 0;
}
Output:
Enter two integers:25 19
The largest number is 25.
Nested if statement
The if block may be nested in another if or else block. This is called nesting of if or else block.
syntax of the nested if statement
if(condition 1)
{
if(condition 2)
{
statement(s);
}
}
Sometimes you want to check for a number of related conditions and choose one of several
actions. One way to do this is by chaining a series of ifs and elses. Look at the following code
segment :
if(condition 1)
statement 1;
else if (condition 2)
statement2;
else
statement3;
#include <stdio.h>
int main()
{
int num1, num2, num3;
switch statement
The syntax of the switch statement is:
switch (var / expression)
{
case constant1: statement 1;
break;
case constant2: statement2;
break;
.
.
default: statement3;
break;
}
The execution of the switch statement begins with the evaluation of the expression. If the value
of expression matches with the constant then the statements following this statement execute
sequentially till it executes break. The break statement transfers control to the end of the switch
statement. If the value of expression does not match with any constant, the statement with default
is executed.
Some important points about the switch statement
#include <stdio.h>
int main()
{
int day;
printf("Enter number 1-7 :");
scanf("%d", &day);
case 2:
printf("Monday");
break;
case 3:
printf("Tuesday");
break;
case 4:
printf("Wednesday");
break;
case 5:
printf("Thursday");
break;
case 6:
printf("Friday");
break;
case 7:
printf("Saturday");
break;
default:
printf("Invalid input");
}
return 0;
}
Output:
Enter number 1-7 :5
Thursday
Looping statement
while loop
do-while loop
for loop
while loop
Syntax of while loop
while(condition)
{
statement(s);
}
The flow diagram indicates that a condition is first evaluated. If the condition is true, the loop
body is executed and the condition is re-evaluated. Hence, the loop body is executed repeatedly
as long as the condition remains true. As soon as the condition becomes false, it comes out of the
loop and goes to the statement next to the ‘while’ loop.
#include <stdio.h>
int main()
{
int i = 1;
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10
do-while loop
Syntax of a do-while loop
do
{
statements;
} while (condition);
Note: That the loop body is always executed at least once. One important difference between the
while loop and the do-while loop the relative ordering of the conditional test and loop body
execution. In the while loop, the loop repetition test is performed before each execution of the
loop body; the loop body is not executed at all if the initial test fails. In the do-while loop, the
loop termination test is performed after each execution of the loop body. Hence, the loop body is
always executed at least once.
#include <stdio.h>
int main()
{
int number, sum = 0;
char choice;
do
{
printf("Enter a number :");
scanf("%d", &number);
sum += number;
return 0;
}
Output:
Enter a number:12
Do you want to continue(y/n)? y
Enter a number:6
Do you want to continue(y/n)? y
Enter a number:19
Do you want to continue(y/n)? n
Sum of numbers:37
for loop
It is a count controlled loop in the sense that the program knows in advance how many times the
loop is to be executed.
syntax of for loop
for (initialization; decision; increment/decrement)
{
statement(s);
}
The flow diagram indicates that in for loop three operations take place:
Operation (i) is used to initialize the value. On the other hand, operation (ii) is used to test
whether the condition is true or false. If the condition is true, the program executes the body of
the loop and then the value of the loop control variable is updated. Again it checks the condition
and so on. If the condition is false, it gets out of the loop.
#include <stdio.h>
int main()
{
int i;
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10
Jump Statements
The jump statements unconditionally transfer program control within a function.
goto statement
break statement
continue statement
#include >stdio.h>
int main()
{
int i;
for (i = 1; i >= 10; i++)
{
if (i == 5)
{
break; /* terminate loop if i is 5 */
}
printf("Loop is over.");
return 0;
}
Output:
1 2 3 4 Loop is over.
The continue statement
The continue statement is used in loops and causes a program to skip the rest of the body of the
loop.
while (condition)
{
Statement 1;
If (condition)
continue;
statement;
}
The continue statement skips the rest of the loop body and starts a new iteration.
#include <stdio.h>
int main()
{
int i;
for (i = 1; i <= 10; i++)
{
if (i % 2 == 0)
{
continue; /* skip next statement if i is even */
}
printf("%d ",i);
}
printf("Loop is over.");
return 0;
}
Output:
1 3 5 7 9 Loop is over.
The exit ( ) function
The execution of a program can be stopped at any point with exit ( ) and a status code can be
informed to the calling program. The general format is
exit (code) ;
where code is an integer value. The code has a value 0 for correct execution. The value of the
code varies depending upon the operating system.
Function
A function in C is a block of statements that has a name and can be executed by calling it from
some other place in your program. functions are used to divide complicated programs into
manageable pieces. Using functions has several advantages:
There are both library functions, functions that are already written and provided by C, and user-
defined functions, functions that you create. Because C does not provide every function that you
will ever need, you must learn to write your functions. User-defined functions in C are classified
into two categories:
void functions - functions that do not have a return data type. These functions do not use
a return statement to return a value.
Value-returning functions - functions that have a return data type. These functions return
the value of a specific data type using the return statement.
The declaration, called the function prototype, informs the compiler about the functions to be
used in a program, the argument they take, and the type of value they return.
The function definition tells the compiler what task the function will be performing. The function
prototype and the function definition must be the same on the return type, the name, and the
parameters. The only difference between the function prototype and the function header is a
semicolon. The function definition consists of the function header and its body. The header is
EXACTLY like the function prototype, EXCEPT that it contains NO terminating semicolon.
#include <stdio.h>
int main()
{
printf("Statement 1\n");
printline();
printf("Statement 2\n");
printline();
return 0;
}
/* function definition */
void printline()
{
int i;
for (i = 0; i < 30; i++)
{
printf("_");
}
printf("\n");
}
Output:
Statement 1
______________________________
Statement 2
______________________________
Argument To A Function
Sometimes the calling function supplies some values to the called function. These are known as
parameters. The variables which supply the values to a calling function called actual parameters.
The variable which receives the value from the called statement is termed formal parameters.
Consider the following example that evaluates the area of a circle.
Here radius is called the actual parameter and r is called a formal parameter.
#include <stdio.h>
int main()
{
float radius;
printf("Enter radius of circle: ");
scanf("%f", &radius);
print_area(radius);
return 0;
}
/* function definition */
void print_area(float r)
{
float area;
area = 3.14 * r * r;
printf("The area of circle is %f\n", area);
}
Output:
Enter radius of circle: 3.5
The area of circle is 38.465000
#include <stdio.h>
int main()
{
int l, b, area;
printf("Enter the length : ");
scanf("%d", &l);
return 0;
}
Global Variable: a variable that is declared outside any function is known as a global variable.
The scope of such a variable extends until the end of the program. these variables are available to
all functions which follow their declaration. So it should be defined at the beginning before any
function is defined.
It is possible to declare local and global variables of the same name. C++ provides the unary
scope resolution operator (::) to access a global variable when a local variable of the same name
is in scope. A global variable can be accessed directly without the unary scope resolution
operator if the name of the global variable is not the same as that of a local variable in scope.
Static Variables
Static variables are declared by writing the keyword static in front of the declaration. If a static
variable is not initialized then it is automatically initialized to 0. A static variable is initialized
only once and its value is retained between function calls.
#include <stdio.h>
void fun();
int main()
{
fun();
fun();
fun();
return 0;
}
void fun()
{
static int a = 10;
printf("a = %d\n", a);
a++;
}
Output:
a = 10
a = 11
a = 12
The storage class of a variable determines which parts of a program can access it and how long it
stays in existence. The storage class can be classified as automatic register static external.
Automatic variable
All variables by default are auto i.e. the declarations int a and auto int a are equivalent. Auto
variables retain their scope until the end of the function in which they are defined. An automatic
variable is not created until the function in which it is defined is called. When the function exits
and control is returned to the calling program, the variables are destroyed and their values are
lost. The name automatic is used because the variables are automatically created when a function
is called and automatically destroyed when it returns.
Register variable
A register declaration is an auto declaration. A register variable has all the characteristics of an
auto variable. The difference is that the register variable provides fast access as they are stored
inside CPU registers rather than in memory.
Static variable
A static variable has the visibility of a local variable but the lifetime of an external variable. Thus
it is visible only inside the function in which it is defined, but it remains in existence for the life
of the program.
External variable
A large program may be written by several persons in different files. A variable declared global
in one file will not be available to a function in another file. Such a variable, if required by
functions in both the files, should be declared global in one file and at the same time declared
external in the second file.
Related links
DJGPP a complete 32-bit C/C++ development system for Intel 80386 and higher PCs.
https://www.sanfoundry.com/c-programming-examples/