UNIT III - C Programing
UNIT III - C Programing
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 .
{ 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 ) ;
}
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 :
printf ( "I am in default \n" ) ;
}
}
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.
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
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;
………….
}
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
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
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;
}
}
}
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;
}
}
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.
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);
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.
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 :
#include <stdio.h>
#include <conio.h>
// function prototype
int getCube(int);
void main ( )
{
int a,cube;
// function calling
cube = getCube(a);
//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.
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:
#include <stdio.h>
int main ()
{
/* local variable declaration */
int a, b;
int c;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
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:
int main ()
{
/* local variable declaration */
int a, b;
/* actual initialization */
a = 10;
b = 20;
g = a + b;
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:
int main ()
{
/* local variable declaration in main function */
int a = 10;
int b = 20;
int c = 0;
return 0;
}
return a + b;
}
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:
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.
#include <stdio.h>
#include <conio.h>
/* function declaration */
void swap(int , int );
void main ( )
{
/* local variable definition */
int a = 100;
int b = 200;
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
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.
Thus recursion follows a bottom-up approach, where the last function call is
executed first, followed by its immediate previous call and so on.
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
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.