[go: up one dir, main page]

0% found this document useful (0 votes)
58 views20 pages

UNIT III - C Programing

Conditional statements in C include if statements and switch statements. 1. If statements have several forms - simple if, if-else, else-if ladder, and nested if-else. They allow executing code conditionally based on boolean expressions. 2. Switch statements allow executing different code based on the value of an expression and use case labels.

Uploaded by

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

UNIT III - C Programing

Conditional statements in C include if statements and switch statements. 1. If statements have several forms - simple if, if-else, else-if ladder, and nested if-else. They allow executing code conditionally based on boolean expressions. 2. Switch statements allow executing different code based on the value of an expression and use case labels.

Uploaded by

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

C Programming – UNIT III

Conditional Program Execution :


Many a times, we want a set of instructions to be executed in one situation, and an entirely
different set of instructions to be executed in another situation. This kind of situation is
dealt in C programs using a decision control instruction.

• C language has decision making capabilities and supports controlling of statements.


• C supports following control or decision making statements:
1. “ if ” Statements.
2. “ switch ” Statements.

1. If statement :
• The keyword if tells the compiler that what follows is a decision control instruction.
• The condition following the keyword if is always enclosed within a pair of parentheses.
• If the condition, whatever it is, is true, then the statement is executed. If the condition is
not true then the statement is not executed;
• if statement is a powerful decision making statement.
• if statement is used to control the flow of execution of statements.
Different forms of If statement
1.1 Simple If statement.
1.2 If…..else statement.
1.3 Nested if…..else statement.
1.4 Else if ladder or else if …else .

1.1 Simple if statement


Ex : WAP in C to Say Hello if no. is positive.
 If the condition, whatever it is, is true, then the void main( )
statement is executed. If the condition is not {
true then the statement is not executed; int x ;
 The general form of a simple if statement is : printf(“Enter Value For X : ”);
Syntax => scanf(“%d”, &x);
if (Condition)
if(x>=0)
{
True statement 1; {
True statement 2; printf(“Hello User!!!”);
}
... }
}

Content Designed By: Faiz Mohd Arif Khan |


1|
C Programming – UNIT III

1.2 If….Else statement


 IF the if expression evaluates to true, the block following the if statement or statements
are executed.
 The else statement is optional. It is used only if a statement or sequences of statements
are to be executed in case, the if expression evaluates to false.
 The group of statements after the if upto and not including the else is called an ‘if block’.
Similarly, the statements after the else form the ‘else block’.
 Notice that the else is written exactly below the if.
Ex : WAP in C to check no. is even or odd.
Syntax =>
void main( )
if(Condition) {
{ int x ;
True statement…1 printf(“Enter Value For X : ”);
True statement…2 scanf(“%d”, &x);
… if(x%2 == 0)
} {
else printf(“X is EVEN number.”);
{ }
False statement 1 else
False statement 1 {
… printf(“X is ODD number.”);
} }
}
1.3 Else if ladder
• The if – else – if statement is also known as the if-else-if ladder or the if-else-if staircase.
• The conditions are evaluated from the top downwards.
Syntax:-
if(condition) Ex : WAP in C to find max among three no.
{ void main( )
True statement…1 {
True statement…2 int x = 20, y = 27, z = 10 ;
… if( x>y && x>z )
} {
else if(condition) printf(“X is GREATER”);
{ }
True statement…1 else if( y>z )
True statement…2 {
… printf(“Y is GREATER”);
} }
else else
{ {
False statement 1 printf(“Z is GREATER”);
False statement 1 }
… }
}

Content Designed By: Faiz Mohd Arif Khan |


2|
C Programming – UNIT III

1.4 Nested if…else statement:


• It is perfectly all right if we write an entire if-else construct within either the body of the
if statement or the body of an else statement. This is called ‘nesting ‘of ifs.
• The general form of nested if…else statement is: Ex : WAP in C to find max among three no.
void main( )
Syntax: {
if (condition 1) int x = 20, y = 27, z = 10 ;
{ if( x>y )
if (condition 2) {

{ if( x>z )
statement 1; printf("X is GREATER");
} else
else printf("Z is GREATER");
{ }
else
statement 2;
{
}
if( y>z )
}
printf("Y is GREATER");
else
else
{
printf("Z is GREATER");
statement 3; }
} }

Example : In a company an employee is paid as under: If his basic salary is less than Rs. 1500,
then HRA = 10% of basic salary and DA = 90% of basic salary. If his salary is either equal to or
above Rs. 1500, then HRA = Rs. 500 and DA = 98% of basic salary. If the employee's salary is
input through the keyboard write a program to find his gross salary.
void main( )
{
float bs, gs, da, hra ;
printf ( "Enter basic salary : " ) ;
scanf ( "%f", &bs ) ;
if ( bs < 1500 )
{
hra = bs * 10 / 100 ;
da = bs * 90 / 100 ;
}
else
{
hra = 500 ;
da = bs * 98 / 100 ;
}
gs = bs + hra + da ;
printf ( "Gross salary = Rs. %f ", gs ) ;
}

Content Designed By: Faiz Mohd Arif Khan |


3|
C Programming – UNIT III

2. switch statement :
The control statement that allows us to make a decision from the number of choices is
called a switch, or more correctly a switch-case-default, since these three keywords go
together to make up the control statement. They most often appear as follows:
switch ( integer expression )
{
case constant 1 :
do this ;
case constant 2 :
do this ;
case constant 3 :
do this ;
default :
do this ;
}

The integer expression following the keyword switch is any C expression that will yield
an integer value. It could be an integer constant like 1, 2 or 3, or an expression that
evaluates to an integer. The keyword case is followed by an integer or a character
constant. Each constant in each case must be different from all the others.

 Execution Of switch :
First, the integer expression following the keyword switch is evaluated. The value it
gives is then matched, one by one, against the constant values that follow the case
statements. When a match is found, the program executes the statements following
that case, and all subsequent case

 default with switch :


If no match is found with any of the case statements, only the statements following
the default are executed.

Consider the following program:


void main( )
{
int i = 2 ;
switch ( i )
{
case 1 :
printf ( "I am in case 1 \n" ) ;
case 2 :
printf ( "I am in case 2 \n" ) ;
case 3 :
printf ( "I am in case 3 \n" ) ;

Content Designed By: Faiz Mohd Arif Khan |


4|
C Programming – UNIT III

default :
printf ( "I am in default \n" ) ;
}
}

The output of this program would be:


I am in case 2
I am in case 3
I am in default

The output is definitely not what we expected! We didn’t expect the second and third line
in the above output. The program prints case 2 and 3 and the default case.

 break with switch


Well, yes. We said the switch executes the case where a match is found and all the
subsequent cases and the default as well.
If you want that only case 2 should get executed, it is upto you to get out of the
switch then and there by using a break statement. The following example shows how
this is done. Note that there is no need for a break statement after the default, since
the control comes out of the switch anyway.
Consider the following program:
void main( )
{
int i = 2 ;
switch ( i )
{
case 1 :
printf ( "I am in case 1 \n" ) ;
break;
case 2 :
printf ( "I am in case 2 \n" ) ;
break;
case 3 :
printf ( "I am in case 3 \n" ) ;
break;
default :
printf ( "I am in default \n" ) ;
}
}

The output of this program would be:


I am in case 2

Content Designed By: Faiz Mohd Arif Khan |


5|
C Programming – UNIT III

Program Loops and Iteration :


The versatility of the computer lies in its ability to perform a set of instructions
repeatedly. This involves repeating some portion of the program either a specified
number of times or until a particular condition is being satisfied. This repetitive operation
is done through a loop control instruction.
There are three types of loop
1. while
2. for
3. do…while

1. while Loop :
The while statement creates a loop that repeats
until the test expression becomes  false, or
zero.  The while statement is an entry-condition
loop;  the decision to go through one or more
loop is made before the loop is traversed.  Thus, it
is possible  that the loop is never
traversed.  The statement part of the form can be a
simple  statement or a compound statement.

Syntax :
while(condition)
{
Statement 1;
………….
}

Example : Output :
#include<stdio.h> value of a: 10
void main () value of a: 11
{ value of a: 12
int a = 10; value of a: 13
value of a: 14
while( a < 20 ) value of a: 15
{ value of a: 16
printf("value of a: %d\n", a); value of a: 17
a++; value of a: 18
} value of a: 19

Content Designed By: Faiz Mohd Arif Khan |


6|
C Programming – UNIT III

2. for Loop :
 A for loop is a repetition control structure that allows you to efficiently write
a loop that needs to execute a specific number of times.
 Execute a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
Syntax:
for( init, condition, increment)
{
Statement 1;
………….
}

Here is the flow of control in a for loop:

1. The init step is executed first, and only once. This step


allows you to declare and initialize any loop control
variables. You are not required to put a statement here,
as long as a semicolon appears.
2. Next, the condition is evaluated. If it is true, the body
of the loop is executed. If it is false, the body of the
loop does not execute and flow of control jumps to the
next statement just after the for loop.

3. After the body of the for loop executes, the flow of


control jumps back up to the increment statement.
This statement allows you to update any loop control
variables. This statement can be left blank, as long as a
semicolon appears after the condition.
4. The condition is now evaluated again. If it is true, the loop executes
and the process repeats itself (body of loop, then increment step, and
then again condition). After the condition becomes false, the for loop
terminates.

Example : Output :
value of a: 10
#include <stdio.h> value of a: 11
void main () value of a: 12
{ value of a: 13
int a; value of a: 14
for( a = 10; a < 20; a = a + 1 ) value of a: 15
{ value of a: 16
printf("value of a: %d\n", a); value of a: 17
} value of a: 18
} value of a: 19

Content Designed By: Faiz Mohd Arif Khan |


7|
C Programming – UNIT III

3. do…while Loop :
 Like a while statement, except that it tests the condition at the end of the loop
body.
 Unlike for and while loops, which test the loop condition at the top of the
loop, the do...while loop in C programming language checks its condition at
the bottom of the loop.
 A do...while loop is similar to a while loop, except that a do...while loop is
guaranteed to execute at least one time.
Syntax:
do
{
Statement1;
……………
}while( condition);

Notice that the conditional expression appears at the end of the loop, so
the statement(s) in the loop execute once before the condition is tested.

If the condition is true, the flow of control jumps back up to do, and the
statement(s) in the loop execute again. This process repeats until the
given condition becomes false.

Example : Output :
#include <stdio.h>
void main () value of a: 10
{ value of a: 11
int a = 10; value of a: 12
value of a: 13
do value of a: 14
{ value of a: 15
printf("value of a: %d\n", a); value of a: 16
a = a + 1; value of a: 17
} while( a < 20 ); value of a: 18
} value of a: 19

Content Designed By: Faiz Mohd Arif Khan |


8|
C Programming – UNIT III

Difference between while and do-while loop


while do…while
1. while loop is entry control loop 1. do while is exit control loop
2. In while loop the condition is tested first, if 2. In do while the statements are executed first and
the condition is true then statements are then the condition are tested to execute again.
executed.
3. while loop do not run in case the condition 3. A do while loop runs at least once.
given is false.
4. In a while loop the condition is first tested 4. A do while is used for a block of code that must
and if it returns true then it goes in the loop. be executed at least once.
5. Syntax: 5. Syntax:
while( condition ) do
{ {
statement(s); satatement(s);
} }while( condition );
 Difference Between while and do-while loop :

 break statement :
The break statement in C programming language has following two usage:
 When the break statement is encountered inside a loop, the
loop is immediately terminated and program control resumes
at the next statement following the loop.
 It can be used to terminate a case in the switch statement.
If you are using nested loops ( i.e. one loop inside another loop), the
break statement will stop the execution of the innermost loop and
start executing the next line of code after the block.

Example : Output :

#include <stdio.h>
void main ()
{
int a = 10; value of a: 10
value of a: 11
while( a < 20 )
value of a: 12
{
printf("value of a: %d\n", a); value of a: 13
a++; value of a: 14
if( a > 15) value of a: 15
{
break;
}
}
}

Content Designed By: Faiz Mohd Arif Khan |


9|
C Programming – UNIT III

 continue statement :
 The continue statement in C programming language works somewhat like
the break statement. Instead of forcing termination, however, continue forces the
next iteration of the loop to take place, skipping any code in between.
 For the for loop, continue statement causes the conditional test and increment
portions of the loop to execute. For he while and do...while loops, continue statement
causes the program control passes to the conditional tests

Example : Output :
#include <stdio.h>
void main ()
{
int a = 10; value of a: 10
do value of a: 11
{ value of a: 12
if( a == 15) value of a: 13
{ value of a: 14
a = a + 1; value of a: 16
continue; value of a: 17
} value of a: 18
printf("value of a: %d\n", a); value of a: 19
a++;
}while( a < 20 );
}

 goto statement :
 A goto statement in C programming language provides an unconditional jump from
the goto to a labeled statement in the same function.
 NOTE: Use of goto statement is highly discouraged in any programming language
because it makes difficult to trace the control flow of a program, making the program
Content Designed By: Faiz Mohd Arif Khan |
10 |
C Programming – UNIT III

hard to understand and hard to modify. Any program that uses a goto can be rewritten
so that it doesn't need the goto.
Example : Output :
#include <stdio.h>
void main ()
{
int a = 10; value of a: 10
display: value of a: 11
printf("value of a: %d\n", a); value of a: 12
a++; value of a: 13
if(a <= 15) value of a: 14
{ value of a: 15
goto display;
}
}

Content Designed By: Faiz Mohd Arif Khan |


11 |
C Programming – UNIT III

Modular Programming :
Modular programming is a software design technique that break downs a program into
individual components(modules) that can programmed and tested independently. It is a
requirement for effective development and maintenance of large programs and projects.
Advantages of modular programming:
i)Manageable : Reduce problem to smaller, simpler, humanly comprehensible problems.
ii)Divisible : Modules can be assigned to different teams/programmers. It enables parallel
work thereby reducing program development time. Also it facilitates
programming, debugging, testing and maintenance.
iii)Re-usable : Modules can be re used within a program and across programs.

In C language, modules are implemented as functions.

Functions
 A function is a group of statements that together perform a task. Every C program has
at least one function which is main(), and all the most trivial programs can define
additional functions.
 You can divide up your code into separate functions. How you divide up your code
among different functions is up to you, but logically the division usually is so each
function performs a specific task.

 Types Of Functions :
1. Library Function: The C standard library provides numerous built-in functions
that your program can call. For example, function printf() to display the
formatted output on screen.
2. User Define Function: If a set of statements are needed to execute more than one
times then user can define their own function and call when needed. For example,
function add(int a , int b) to add two integers a and b.

 Function Prototype :
Every function in C programming should be declared before they are used. These type of
declaration are also called function prototype. Function prototype gives compiler
information about function name, type of arguments to be passed and return type.
Syntax:
Return-type function-name ( parameter list );
Example :
int add(int a, int b);

Parameter names are not important in function declaration(prototype) only their


type is required, so following is also valid declaration
int add(int, int);

Content Designed By: Faiz Mohd Arif Khan |


12 |
C Programming – UNIT III

 Function Definition :
The general form of a function definition in C programming language is as follows:
Return-type function-name(parameter-list)
{
Body of function;
}
A function definition in C programming language consists of a function header and
a function body. Here are all the parts of a function:
 Return Type: A function may return a value. The return_type is the data type of
the value the function returns. Some functions perform the desired operations
without returning a value. In this case, the return_type is the keyword void.

 Function Name: This is the actual name of the function. The function name and
the parameter list together constitute the function signature.

 Parameters: A parameter is like a placeholder. When a function is invoked, you


pass a value to the parameter. This value is referred to as actual parameter or
argument. The parameter list refers to the type, order, and number of the
parameters of a function. Parameters are optional; that is, a function may contain
no parameters.

 Function Body: The function body contains a collection of statements that define


what the function does.
Example :
int add(int a , int b)
{
int sum;
sum = a + b;
return sum;
}

 Function Calling :
While creating a C function, you give a definition of what the function has to do. To use a
function, you will have to call that function to perform the defined task.

When a program calls a function, program control is transferred to the called function. A
called function performs defined task and when its return statement is executed or when
its function-ending closing brace is reached, it returns program control back to the main
program.

To call a function you simply need to pass the required parameters along with function
name and if function returns a value then you can store returned value.

Example : int result = add(20, 30);

Content Designed By: Faiz Mohd Arif Khan |


13 |
C Programming – UNIT III

EXAMPLE :
#include <stdio.h>
#include <conio.h>

// function prototype
int getCube(int);

void main ( )
{
int a,cube;

printf("Enter Value For a : ");


scanf("%d", &a);

// function calling
cube = getCube(a);

printf("Cube of a is %d.", cube);


}

//function definition
int getCube(int x)
{
int c;
c = x*x*x;
return c;
}

OUTPUT :
Enter Value For a : 3
Cube of a is 27.

Content Designed By: Faiz Mohd Arif Khan |


14 |
C Programming – UNIT III

Scope Rules :
A scope in any programming is a region of the program where a defined variable can
have its existence and beyond that variable can not be accessed. There are three places
where variables can be declared in C programming language:

1. Inside a function or a block which is called local variables,


2. Outside of all functions which is called global variables.
3. In the definition of function parameters which is called formal parameters.
 Local Variables
Variables that are declared inside a function or block are called local variables. They can
be used only by statements that are inside that function or block of code. Local variables
are not known to functions outside their own. Following is the example using local
variables. Here all the variables a, b and c are local to main( ) function.

#include <stdio.h>

int main ()
{
/* local variable declaration */
int a, b;
int c;

/* actual initialization */
a = 10;
b = 20;
c = a + b;

printf ("value of a = %d, b = %d and c = %d\n", a, b, c);

return 0;
}

 Global Variables
Global variables are defined outside of a function, usually on top of the program. The
global variables will hold their value throughout the lifetime of your program and they
can be accessed inside any of the functions defined for the program.

A global variable can be accessed by any function. That is, a global variable is available
for use throughout your entire program after its declaration. Following is the example
using global and local variables:

Content Designed By: Faiz Mohd Arif Khan |


15 |
C Programming – UNIT III

/* global variable declaration */


int g;

int main ()
{
/* local variable declaration */
int a, b;

/* actual initialization */
a = 10;
b = 20;
g = a + b;

printf ("value of a = %d, b = %d and g = %d\n", a, b, g);

return 0;
}

 Formal Parameters
A function parameters, formal parameters, are treated as local variables with-in that
function and they will take preference over the global variables. Following is an example:

/* global variable declaration */


int a = 20;

int main ()
{
/* local variable declaration in main function */
int a = 10;
int b = 20;
int c = 0;

printf ("value of a in main() = %d\n", a);


c = sum( a, b);
printf ("value of c in main() = %d\n", c);

return 0;
}

/* function to add two integers */


int sum(int a, int b)
{
printf ("value of a in sum() = %d\n", a);
printf ("value of b in sum() = %d\n", b);

return a + b;
}

Content Designed By: Faiz Mohd Arif Khan |


16 |
C Programming – UNIT III

Function Arguments:
If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are
created upon entry into the function and destroyed upon exit.

While calling a function, there are two ways that arguments can be passed to a function:

Call Type Description


This method copies the actual value of an argument into the formal
Call by value parameter of the function. In this case, changes made to the
parameter inside the function have no effect on the argument.
This method copies the address of an argument into the formal
parameter. Inside the function, the address is used to access the
Call by reference
actual argument used in the call. This means that changes made to
the parameter affect the argument.

By default, C uses call by value to pass arguments. In general, this means that code
within a function cannot alter the arguments used to call the function and above
mentioned example while calling max( ) function used the same method.

 Call By Value :
The call by value method of passing arguments to a function copies the actual value
of an argument into the formal parameter of the function. In this case, changes made
to the parameter inside the function have no effect on the argument.

By default, C programming language uses call by value method to pass arguments. In


general, this means that code within a function cannot alter the arguments used to call
the function.

Content Designed By: Faiz Mohd Arif Khan |


17 |
C Programming – UNIT III

Example : Consider the function swap( ) definition as follows.

#include <stdio.h>
#include <conio.h>

/* function declaration */
void swap(int , int );

void main ( )
{
/* local variable definition */
int a = 100;
int b = 200;

printf("Before swap, value of a : %d\n", a );


printf("Before swap, value of b : %d\n", b );

/* calling a function to swap the values */


swap(a, b);

printf("After swap, value of a : %d\n", a );


printf("After swap, value of b : %d\n", b );

/* function definition to swap the values */


void swap(int x, int y)
{
int temp;

temp = x; /* save the value of x */


x = y; /* put y into x */
y = temp; /* put temp into y */
}

OUTPUT :
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 100
After swap, value of b : 200

Content Designed By: Faiz Mohd Arif Khan |


18 |
C Programming – UNIT III

 Recursion :
 Recursion is the process by which a function calls itself from itself. In other
words, the function call is embedded in the function definition.

 The function body has a terminating condition which if satisfied terminates


further call to itself and the remaining statements if any in the previous call are
executed.

 Thus recursion follows a bottom-up approach, where the last function call is
executed first, followed by its immediate previous call and so on.

 The advantage of recursion is that it reduces program code, thus making it


simpler.

Example :
/*FACTORIAL OF n BY RECURSION USING USER DEFINE FUNCTION*/

#include<stdio.h>
#include<conio.h>

int fact(int);
void main ( )
{
int num,factorial;
int fact(int n);
clrscr( );
printf("Enter the value :");
scanf("%d",&num);
factorial=fact(num);
printf("The factorial of %d is : %d",num, factorial);
getch( );
}
int fact(int n)
{
if(n==1)
return 1;
else
return(n*fact(n-1));
}

OUTPUT :
Enter the value : 4
The factorial of 4 is : 24

Content Designed By: Faiz Mohd Arif Khan |


19 |
C Programming – UNIT III

Compiling and Linking


When programmers talk about creating programs, they often say, "it compiles fine" or,
when asked if the program works, "let's compile it and see". This colloquial usage might
later be a source of confusion for new programmers. Compiling isn't quite the same as
creating an executable file! Instead, creating an executable is a multistage process divided
into two components: compilation and linking. In reality, even if a program "compiles
fine" it might not actually work because of errors during the linking phase. The total
process of going from source code files to an executable might better be referred to as
a build. 

 Compilation
Compilation refers to the processing of source code files (.c) and the creation of an
'object' file. This step doesn't create anything the user can actually run. Instead, the
compiler merely produces the machine language instructions that correspond to the
source code file that was compiled. For instance, if you compile (but don't link) three
separate files, you will have three object files created as output, each with the name
<filename>.o or <filename>.obj (the extension will depend on your compiler). Each of
these files contains a translation of your source code file into a machine language file --
but you can't run them yet! You need to turn them into executables your operating system
can use. That's where the linker comes in. 

               
preprocessor compiler
SOURCE CODE r EXPANDED CODE   OBJECT CODE
xyz.c     xyz.obj

 Linking
Linking refers to the creation of a single executable file from multiple object files. In this
step, it is common that the linker will complain about undefined functions (commonly,
main itself). During compilation, if the compiler could not find the definition for a
particular function, it would just assume that the function was defined in another file. If
this isn't the case, there's no way the compiler would know -- it doesn't look at the
contents of more than one file at a time. The linker, on the other hand, may look at
multiple files and try to find references for the functions that weren't mentioned. 

         

OBJECT CODE LINKER EXECUTABLE CODE


xyz.obj   xyz.exe

Content Designed By: Faiz Mohd Arif Khan |


20 |

You might also like