You are on page 1of 52

Amity School of Engineering and Technology

Introduction to Computers
and Programming in C

ES202

Module III
Fundamental Features in C
Topics to be Covered

C Statements, conditional executing using


if, else, nesting of if, switch and break
Concepts of loops, example of loops in C
using for, while and do-while, continue and
break. Storage types (automatic, register
etc.), predefined processor, Command Line
Argument.

2
Conditional Statements
• Conditional statements are used to execute a set of statements on some
conditions.

• In C program, statements are executed sequentially, if no condition is


given around the statements.

• Flow of statement execution can be changed using conditional


statements.

• The process of using conditional statement us known as decision


making in ‘C.’

• Also called as control statements.

3
If Statement
• If the expression is true, then if block statement(s) are executed.
• If the expression is evaluated to false, then control passes to the next
statement following it.
• Syntax: if (LogicalExpr) Statement
• Program context: statement1
statement1;
if (LogicalExpr) statement2;
statement3;
Logical true
statement2
Expression

Flow of Execution false

statement3

4
If statement
Example:

void main()
{
int a;
printf(“\n enter any number”);
scanf(“%d”, & a);
if(a%2==0)
{
printf(“even”);
}
getch();
}

5
If-else
• Used to execute the code if condition is true or false. It is also called
two-way selection statement.

• Syntax:
if (LogicalExpr)
StatementA
else
StatementB

false Logical true


statementB statementA
Expression
Flow of Execution

6
If-else
Example:
void main()
{
int a;
printf(“\n enter any number”);
scanf(“%d”, & a);
if(a%2==0)
{
printf(“even number”);
}
else
{
printf(“Odd number”);
}
getch();
} 7
Nested if-else

• The nested if-else statement allows you to check for


multiple test expressions and execute different codes for
more than 2 conditions.

• Also known as multi-way selection statement.

8
Nested if-else
Example:
void main() else
{ {
int a,b,c; if(b>c)
printf(“\n enter any three number”);
printf(“ b is greatest”);
scanf(“%d %d %d”, & a, &b, &c);
else
if(a>b)
{ printf(“ c is greatest”);
if(a>c)
}
printf(“a is greatest”); getch();
else
printf(“c is greatest”); }

} 9
If-else-if
• Used to execute one code from multiple conditions.

• It is also called multipath decision statement.

• The if-else-if statement has the following form (3 levels example).

if(condition_1)
statement_1;
else if (condition_2)
statement_2;
else if(condition_3)
statement_3;
else
statement_4;
next_statement; 10
If-else-if
Example:

int main() else if(marks>55)


{ {
int marks=80; printf("Third class");
if(marks>75) }
{ }
printf("First class"); else
} {
else if(marks>65) printf(“fourth class”);
{
printf("Second class"); }
} return 0;

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

• Acts as a substitute for a long if-else-if ladder.

• Float variables can not be used as switch expression or case


values.

12
Switch Case Syntax

13
Switch Statement
Example:

void main () printf(“\n Subtraction =%d’, a-b);


{ break;
int a,b, ch; case 3 :
printf(“\n enter two numbers”) printf(“\n Multiplication=%d”,
scanf(“%d%d”, &a, &b); a*b);
printf(“\n enter choice between break;
1,2,3”); default :
scanf(“%d”, & ch); printf(“\n Invalid choice" );
}
switch(ch) printf(“\n end of switch statement”);
{
case 1: getch();
printf(“\n sum=%d”, a+b); }
break;
case 2 :
15
Loops
• A loop is a sequence of instructions that is continually repeated until a
certain condition is reached.
• Loops allow for the same statement to be executed a number of times in
succession.
• entry-controlled and exit-controlled.
• while, do-while and for loop.
• for and while loop is entry-controlled loops.
• do-while is an exit-controlled loop.

16
Loops
• entry-controlled and exit-controlled.

Source: Programming in ANSI C, E. Balagurusamy. McGrawHill


17
The while loop

• A WHILE loop is a loop that repeats while some condition is satisfied.


• It tests its condition at the beginning of every loop.
• A while loop has the following syntax:
while (condition)
statement;

• If the condition is true, the statement is executed; then the condition is


evaluated again
• If the condition of a while statement is false initially, the statement is
never executed
• Therefore, we say that a while statement executes zero or more times

18
while loop - flow diagram

19
do-while loop

• Unlike a while loop, a do-while loop tests its condition at the end of the
loop.

• This means that its sequence of activities always runs at least once.

• Syntax is:

do
statement
while (expression);

20
do-while loop - flow diagram

21
while/do-while loop
While loop Do-while loop
Entry controlled loop Exit controlled loop
checks the condition at the the condition is checked after the
starting of the loop and if the execution of all statements in the
condition is satisfied body of the body of the loop.
loop is executed.

If the condition in a while loop is if the condition in ‘do-while’ loop


false, not a single statement inside is false, then also the body of the
the loop is executed. loop is executed at least once then
the condition is tested.

there is no use of the semi-colon in The syntax of a do-while loop


the while loop syntax. includes a semi-colon to terminate
the loop.
22
while and do-while loop
Example:
while(condition) do
{ {
statements; statements;
} } while (expression);

Example: Example:
int a=5; int a=5;
while(a<5) do
{ {
printf("%d\n",a); printf(“\n%d”, a);
} }while(a<5);
printf(“\n end of loop”); printf(“\n end of loop”);

O/P: end of loop O/P: 5


end of loop
23
for Loop

• A for loop is a loop that repeats a specified number of times.

• The loop uses a counter to tell it how many times to run the
same sequence of activities.

Syntax:
for ( init; condition; increment )
{
statement(s);
}

24
for loop - Flow diagram

initialization

false
condition

true

statement

increment

25
for loop

Example:

for(i=1;i<=3;i++)
printf(“\n %d”, i);
O/P: 1
2
3

26
Nested Loops
• We can use nested loops in C.
• Nested loops means loops that can be
placed inside the other loop.
• We can use concept of nested loop in all
three types of loop such as for, while and do
while however, we use for loop normally as it
is easiest to control.
• A for loop can be used to control the number
of times that a particular set of statements
will be executed.

27
Nested Loops
• In the case of nested loop, we have
minimum two loops, outer loop and inner
loop
• Inner loop will control the execution of
statements given in the body of inner loop.
• Outer loop is used to control the number of
times that a complete loop is repeated.

28
Nested Loops
Example:

for( i=1;i<=3;i++)
{
printf(“Outer Loop”);
for( j=1;j<=2;j++)
{
printf(“Inner Loop”);
}
}

29
break statement
• break statement is used to exit from the current loop.

• It is used to indicate a set of statements is finished (and no


more should be executed)

• Syntax: break;

• When break statement will be encountered inside any loop,


the loop will be immediately terminated, and the control
resumes at the next statement following the loop.

• Also used in switch statement to terminate a case.


30
break Statement

Source: Programming in ANSI C, E. Balagurusamy. McGrawHill


31
break Statement
Example:

int main () {
int a = 10;
while( a < 15 ) {
printf(“%d\n”, a);
a++;
if( a > 13) O/P:
{ 10
break; 11
} 12
} 13
return 0;
}

32
continue Statement

• continue keyword forces the next iteration to take place


immediately, skipping any instructions that may follow it.

• The continue statement can only be used inside a loop (for,


do-while and while) and not inside a switch-case selection.

• Unlike the break statement, continue does not force the


termination of a loop, it merely transfers control to the
next iteration.

33
continue Statement

Source: Programming in ANSI C, E. Balagurusamy. McGrawHill

34
continue Statement
Example:
int main ()
{
int i;
for(i=0;i<=10;i++)
{
if(i==5)
continue;
printf(“\t %d”,i);

}
return(0);
}

Output:
0 1 2 3 4 6 7 8 9 10 35
goto statement
• goto statement is used for unconditional jumping.

• It is a jumping statement which can be used to jump from one


statement to another inside any function.
label: goto label;
//statements…. //statements…
goto label; label:

– goto label: used to tell compiler to jump to the statement marked


as a label.
– label: user-defined identifier which indicates the target statement.

36
goto statement

Source: Programming in ANSI C, E. Balagurusamy. McGrawHill

37
exit()

• The exit( ) function is a standard library function.

• It terminates the execution of the program.

• It is necessary to use this function with goto statement, if you do not want
to execute the statements written after else statement.

38
goto and exit ()
Example:
#include <stdio.h>
label:
void display() printf("number is less
{ than or equal to 5");
int n;
printf("\n enter number"); }
scanf("%d", &n);
int main()
if(n<=5)
{
goto label; display();
else return 0;
{ }
printf("\n number is greater than 5");
exit(0); }

39
Predefined Processor
• C preprocessor is not a part of the compiler but is a separate step in the
compilation process.

• All preprocessor directives begin with a hash symbol (#).

• Preprocessing is the first step of the language processing system.


• The preprocessor is a program that processes the source code before it
passes through the compiler.
• It operates under the control of directives known as preprocessor
directives.

40
Predefined Processor

41
Preprocessor Tasks
1. File inclusion
•  Including all the files from library into the program.

For example, #include<stdio.h> 


• the file will be searched in the standard directory.

• Preprocessor will include all the contents of library file stdio.h in


the program.

#include “stdio.h”
• File will be searched in the current source directory.

42
Preprocessor Tasks
2. Macro Substitution
• A macro is a fragment of code which has been given a name.

• defined by using # define preprocessor directive.

• Before the source code passes to the compiler, C preprocessor


examines for macro definitions.

• If it finds #define directive, then it search for the macro templates in


the program and replaces the macro template with the appropriate
macro expansion.

• After this process, program handed over to the compiler.

43
Preprocessor Tasks
• object like macro
#define max 100

• function like macro


– The macros can take function like arguments, the arguments are
not checked for data type.
– #define show(x) (printf(“\n value of x=%d”, x)
– #undef-used to delete the macro definition

44
Preprocessor Tasks

Macro Definition Macro with Arguments

#define Area(x) ( 3.14 * x * x )


#define PI 3.14
main( )
main( ) {
{ float r = 1.50; a ;
float r = 1.50; a = Area ( r ) ;
float area ; printf ( "\nArea of circle = %f", a ) ;
area = PI * r * r ; }
printf ( "\nArea of circle = %f",
area ) ;
}

45
Preprocessor Tasks
3. Removing comments

•  It removes all the comments.

• A comment is written only for the humans to understand the code and
they are of no use to a machine.

• preprocessor removes all of them as they are not required in the


execution and won’t be executed as well.

46
Preprocessor Tasks
4. Conditional Compilation
• Compiler can skip some part of a source code if we want.

• preprocessing commands #ifdef and #endif are used for this purpose.
#ifdef macroname
statement 1 ;
statement 2 ;
statement 3 ;
#endif

• If macro name has been #defined, the block of code will be processed
otherwise compiler will skip this block of code.

47
Preprocessor Tasks
#if and #elif directive

• The #if directive can be used to test whether an expression evaluates


to a nonzero value or not.

• If the result of the expression is nonzero, then subsequent lines upto


a #else, #elif or #endif are compiled.

• If the result of the expression is zero, then #if statements will be


skipped.

48
Preprocessor Tasks
Example:

main( )
{
#if age >=30
statement 1 ;
statement 2 ;
#else
statement 3 ;
statement 4 ;
#endif
}

49
Command Line Argument
• In C programs, values can be passed from the command line when they
are executed.

• These values are called command line arguments.

• handled using main() function arguments.

• int main( int argc, char *argv[] )

•  argc refers to the number of arguments passed, and argv[] is a pointer


array which points to each argument passed to the program.

50
Command Line Argument
int main(int arg, char *argv[])
{
int i,x,f=1;
x=atoi(argv[1]); //atoi() is used to convert string argument
value into integer value
for(i=1;i<=x;i++)
{
f=f *i ;
}
printf("\n factorial=%d", f);
return 0;
}

51
References
 Programming in ANSI C, E. Balagurusamy. McGrawHill
 Let Us C, Yashvant Kanetkar, BPB Publications
 Programming in C, Reema Thareja, Oxford University Press
 https://www.dotnettricks.com

52
Thank You

You might also like