0% found this document useful (0 votes)
21 views

C MODULE 1

Uploaded by

ishancp17
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

C MODULE 1

Uploaded by

ishancp17
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

CO1-Make use of basic programming concepts

Module 1
CO1 – Make use of basic programming concepts – sequential, conditional, looping structures and functions in c

Recall basic programming concepts – C program structure, selection structure, and repetition
structures.

Function – Declaration, prototype, definition, function call, storage class, lifetime and visibility
of variables.

Preprocessor – File inclusion – macro substitution

Recursion – Recursive definition of a problem, implementation of programs using recursion.

Control Statements
 Control statements control the flow of execution of the statements of a
program.
 C supports three types of control statements.
They are :
1. Sequential Control Statements
2. Conditional Control Statements
3. Iteration or Looping Statements

Sequential Control Statements


 It ensures that the instructions are executed in the same order in which they appear in the
program.
 The program statements are executed sequentially i.e., one after the another from
beginning to end.
Eg:
int main()
{
clrscr();
int x , y, sum;
printf(“enter the two numbers”);
scanf(“%d%d”,&x,&y);
sum=x+y;
printf(“the sum of the two numbers is =%d”,sum);
return 0;
}
Decision Control statements
 Also called Conditional Control or Selection Control Statements.
 These statements change the flow of execution depends on a condition-test.
 If the condition is true, then a set of statements is executed otherwise another set of statements
is executed.
 It helps in making decision about which set of statements is to be executed.
 Used to execute or skip some set of instructions based on given condition.
1. – Programming in C
3132
CO1-Make use of basic programming concepts

 C supports six types of control statements

1. if statement
2. if-else statement
3. Nested if else statement
4. else-if ladder
5. case control structure
6. conditional operators

if Statement
 This is the simplest form of decision control statement.
 If statement is used to test a condition, if condition is true then the code inside the if statement
is executed otherwise that code is not executed.
Syntax:
if(test_expression)
{
statement 1;
statement 2;
...
}

Example : Program to check whether


the given number is negative .
int main()
{ int num;
clrscr();
printf(“enter the number”);
scanf(“%d”,&num);
if(num<0)
{ printf(“the entered number is negative”); }
return 0;
}

if- else Statement


 This is a bi-directional control statement.
 This statement is used to test a condition, if the condition is true then one statement (block of
statements) is executed otherwise other statement (or block of statements) is executed.
Syntax:
if(test_expression)
{
Body of if Statement;
}
else

1. – Programming in C
3132
CO1-Make use of basic programming concepts
{
Body of else Statement;
}

Example: Program to find the biggest of two numbers


int main()
{
int num1, num2;
clrscr();
printf(“enter the two numbers”);
scanf(“%d %d”, &num1, &num2);
if (num1 > num2)
{
printf(“the number %d is big”, num1);
}
else
{
printf(“the number %d is big”,num2);
}
return 0;
}

Nested if Statement (Nested if – else Statement)


 It contains multiple if else condition.
 It is used to check the multiple conditions.
 This statement is like executing an if statement inside an else statement.
 In this, an if-else statement within either the body of an if statement or the body of
else statement or in the body of both if and else, then this is known as nesting of if else
statement.
Syntax:

if(test_expression one)
{
if(test_expression two) {
//Statement block Executes when the boolean test expression two is true. }
}
else
{
//else statement
block
}

3132 – Programming in C
CO1-Make use of basic programming concepts

Example: Program to demonstrate Nested - if


void main()
{
int x = 20, y = 30;
if (x==20)
{
if (y==30)
{
printf("value of x is 20, and value of y is 30.");
}
}
}

else if Ladder
 After if statement else if is used to check the multiple conditions.
 This is a type of nesting in which there is an if-else statement in every else part except the last
else part.
 This type of nesting is called else if ladder.
Syntax:
if(test_expression)
{
//execute your code
}
else if(test_expression
n)
{
//execute your code
}
else
{
//execute your code
}

Example – Program to find the Grade of a student

int main()
{
int marks;
printf(“enter the percentage of the student”);
scanf(“%d”,&marks);
3132 – Programming in C
CO1-Make use of basic programming concepts
if(marks>=80)
printf(“your grade is a”);
else if(marks>=70)
printf(“your grade is b”);
else if(marks>=60)
printf(“your grade is c”);

else if(marks>=50)
printf(“your grade is d”);
else printf(“you are fail”);
return 0;
}

Switch case statement

 It is an alternative to the if-else-if ladder.


 Switch is another conditional control statement used to select one option from several options
based on given expression value.
 The selection is based upon the current value of an expression which is included with in the
switch statement.
 The switch statement evaluates expression and then looks for its value among the case
constants.
 If the value matches with case constant, then that particular case statement is executed. If
no one case constant not matched then default is executed.
 Every case statement terminates with colon “:”.
 In switch each case block should end with break statement, i.e.

Syntax:
switch(variable)
{
case 1:
//execute your
code
break;

case n:
//execute your
code
break;

default:
//execute your
code
break;
}

3132 – Programming in C
CO1-Make use of basic programming concepts

Example : Program to display the traffic control signal lights.

int main( )
{
char L;
printf(“ \n Enter your Choice( R,r,G,g,Y,y):”);
scanf(“%c”, &L);
switch(L)
{
case “R” :
case “r”: printf(“RED Light Please STOP”);
break;
case “Y” :
case “y”: printf(“YELLOW Light Please Check and Go”);
break;
case “G”:
case “g”: printf(“GREEN Light Please GO”);
break;
default: printf(“THERE IS NO SIGNAL POINT ”);
}
return 0;
}

Conditional Operator
 It is a ternary operator.
 It is used to perform simple conditional operations.
 Conditional operator is used to check a condition and Select a Value depending on the Value of the
condition.
 It is used to do operations similar to if-else statement.
Syntax:
Test expression? Value 1 : Value 2

Example : To find the largest of two numbers.


int main()
{
float num1, num2, max;

printf("Enter two numbers: ");


scanf("%f %f", &num1, &num2);
max = (num1 > num2) ? num1 : num2;
printf("Maximum of %.2f and %.2f = %.2f", num1, num2, max);
return 0;
}

3132 – Programming in C
CO1-Make use of basic programming concepts

1. C program to check whether the number is divisible by 5 and 11.


2. Program to find the roots of a quadratic equation.
3. Program to check if the number is Amstrong or not.
4. C program to calculate an electricity using the following criterion.

Iterations/Loop Control Statements

 A loop is used to repeat a block of code until the specified condition is met. Iterations
or loops are used when we want to execute a statement or block of statements several
times.
 The repetition of loops is controlled with the help of a test condition. The statements
in the loop keep on executing repetitively until the test condition becomes false.
 C programming has three types of loops:
a) for Loop
b) while Loop
c) do-while Loop

while Loop

 It is an entry control loop.


 Repeats a statement or group of statements while a given condition is true.
 It tests the condition before executing the loop body.
Syntax
while (testExpression) {
// the body of the loop
}

Example: To print first 10 natural numbers


int main( )
{ int x = 1;
while(x <= 10)
{
printf("%d\t", x);
x++;
}
}

do – while Loop

 It is an exit control loop.


 A do...while loop is similar to a while loop.
 It executes the body of loop at least once.
 If the condition is true, the body of the loop is executed again and the condition is evaluated
once more.
 This process goes on until the condition becomes
false.
 If the condition is false, the loop ends.

3132 – Programming in C
CO1-Make use of basic programming concepts

Syntax
do {
// the body of the loop
}
while (testExpression);

Example: Program to add numbers until the user enters zero.

int main()
{
int number, sum = 0;
// the body of the loop is executed at least once

do
{
printf("Enter a number: ");
scanf("%d", &number);
sum += number;
}
while(number != 0);
printf("Sum = %d",sum);
return 0;
}

for Loop

 It is an open ended loop..


 It is used to execute a set of statements repeatedly until a particular condition is satisfied.
 Executes a sequence of statements multiple times.

Syntax:
for (initializationStatement; testExpression; updateStatement)
{
// statements inside the body of loop
}

 The initialization statement is executed only once.


 Then, the test expression is evaluated. If the test expression is evaluated to false, the for loop
is terminated.
 If the test expression is evaluated to true, statements inside the body of the for loop are
executed, and the update expression is updated.
 Again the test expression is evaluated.
 This process goes on until the test expression is false. When the test expression is false, the
loop terminates.

3132 – Programming in C
CO1-Make use of basic programming concepts

Example: Print numbers from 1 to 10

int main()
{
int i;
for (i = 1; i < 11; ++i)
{
printf("%d ", i);
}
return 0;
}

Infinite Loop

 A loop becomes an infinite loop if a condition never becomes


false.
 The for loop is traditionally used for this purpose.
 Three expressions are required to form the 'for' loop.
 But to provide two semicolons to validate the syntax of the for
loop. This will work as an infinite for loop.
 When the conditional expression is absent, it is assumed to be
true.

Example

main ()
{
for(;;)
{
printf("welcome to ");
}
}

3132 – Programming in C
CO1-Make use of basic programming concepts
Nested Loop

 Nested loop means a loop statement inside another loop


statement. That is why nested loops are also called as “loop
inside loop“.

Syntax for Nested For loop:

for ( initialization; condition; increment )


{
for ( initialization; condition; increment )
{
// statement of inside loop
}
// statement of outer loop
}

Example
int main()
{
int n;// variable declaration
printf("Enter the value of n :");
// Displaying the n tables.
for(int i=1;i<=n;i++) // outer loop
{
for(int j=1;j<=10;j++) // inner loop
{
printf("%d\t",(i*j)); // printing the value.
}
printf("\n");
}

Output
Enter the value of n : 3
1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27
30

Unconditional Control Statements

 Control statements that do not need any condition to control the program execution
flow.
 These control statements are called as unconditional control statements.
 C programming language provides three unconditional control statements.

1. break
2. continue
3. goto

break Statement

 It is used to terminate the loop (or) exit from the block.


 The control jumps to next statement after the loop (or) block.
 break is used with for, while, do-while and switch statement.
3132 – Programming in C
CO1-Make use of basic programming concepts
 When break is used in nested loops then, only the innermost loop is terminated.

Syntax for break statement as :

break;

Example

int main( ){
int i;
for (i=1; i<=5; i++){
printf ("%d", i);
if (i==3)
break;
}
}
continue Statement

 The continue statement is used to bring the program control to the beginning of the
loop.

 The continue statement skips some lines of code inside the loop and continues with the
next iteration.

 It is mainly used for a condition so that we can skip some


code for a particular condition.

Syntax

//loop statements
continue;
//some lines of the code which is to be skipped
Example

int main(){
int i=1; //initializing a local variable
//starting a loop from 1 to 10
for(i=1;i<=10;i++){
if(i==5){ //if value of i is equal to 5, it will continue the loop
continue;
}
printf("%d \n",i);
}//end of for loop
return 0;
}

goto Statement

 It is known as jump statement in C.


 goto is used to transfer the program control to a predefined label.
 The goto statment can be used to repeat some part of the code for a particular condition.
 Statement which is used to branch unconditionally within a program from one point to another.

3132 – Programming in C
CO1-Make use of basic programming concepts
Syntax:
goto label;
--------
label:
statement - X;
/* This the forward jump of goto statement */

The label is an identifier which is a valid variable name which is followed by a colon. When the
goto statement is encountered, the control of the program jumps to label and starts executing the
code.

Example - Program to calculate the sum and average of positive numbers. If the user enters a
negative number, the sum and average are displayed.

int main() {
const int maxInput = 100;
int i;
float number, average, sum = 0.0;

for (i = 1; i <= maxInput; ++i) {


printf("%d. Enter a number: ", i);
scanf("%f", &number);

// go to jump if the user enters a negative number


if (number < 0.0) {
goto jump;
}
sum += number;
}
jump:
average = sum / (i - 1);
printf("Sum = %.2f\n", sum);
printf("Average = %.2f", average);

return 0;
}

Counter Controlled Loop

 It is also known as definite repetition loop.


 In this loop, the number of iterations is known before the loop begins to execute.
 The counter-controlled loop has the following components:
o a control variable.
o the increment (or decrement)value by which the control variable is modified at
each iteration of the loop.
o loop terminating condition that checks if looping should continue.
 Since the counter controlled loop is controlled by a counter value.
 At each iteration counter value will increase or decrease with a definite value and condition
will be checked.
 So the number of loop execution becomes definite.

3132 – Programming in C
CO1-Make use of basic programming concepts

Example

int sum = 0;
int n = 1;
while (n <= 10){
sum = sum + n*n;
n = n+ 1;
}

Sentinel Controlled Loops

 It is also called indefinite loop.


 In this, the number of iterations is not known in advance.
 In this, a special value called sentinel value which is used to change the loop control
expression from true to false.
 The value of the control variable differs within a limitation and the execution can be
terminated at any moment.
 The value of this variable changes inside the loop.
 The loop breaks when the value of the control variable matches the condition.

Example

do{
printf("Input a number");
scanf("%d", &num);
}while(num > 0);

3132 – Programming in C
CO1-Make use of basic programming concepts

Modular Programming
 Modular programming is the process of subdividing a computer program into separate
sub programs called functions or procedures.

 A module is a separate software component.

 Module is basically a set of interrelated files that share their implementation details but
hide it from the outside world

 It can often be used in a variety of applications and functions with other components of
the system.

 It increases the maintainability, readability of the code and to make the program handy
to make any changes in future or to correct the errors.

Advantages of Using Modular Programming


1. Ease of Use : It allows simplicity, ease in debugging the code and prone to less error.

2. Reusability: It allows the user to reuse the functionality with a different interface without
typing the whole program again.
3. Ease of Maintenance: It helps in less collision at the time of working on modules, helping a
team–to
3132 work with proper
Programming in C collaboration while working on a large application.
CO1-Make use of basic programming concepts

Functions:

 A function is a group of statements that perform a specific task.


 A function can also be referred as a method or a sub-routine or a procedure, etc.
 Function is a reusable block of code that makes a program easier to understand, test and
can be easily modified without changing the calling program.
 Functions divide the code and modularize the program for better and effective results.
 In general, a larger program is divided into various subprograms which are called as
functions.
 Every C program has at least one function, which is main().

Needs of Functions in C
 To improve the readability of code.
 Improves the reusability of the code - same function can be used in any program rather
than writing the same code from scratch.
 Debugging of the code would be easier if we use functions, as errors are easy to be
traced.
 Reduce the size of the code- duplicate set of statements are replaced by function calls.

Types of Function :

 There are two types of function in C programming:

 Standard library functions


 User-defined functions
Standard Library Functions
3132 – Programming in C

 Also known as built-in functions.


 These functions are defined in header files.
CO1-Make use of basic programming concepts

Example:

 printf() is a standard library function to send formatted output to the screen. This
function is defined in the stdio.h header file. Hence, to use the printf() function, we
need to include the stdio.h header file using #include <stdio.h>.
 sqrt() function calculates the square root of a number. The function is defined in the
math.h header file.

User Defined Functions

 Functions that are defined by the user at the time of writing the program.
 The functions that we create in a program are known as user defined functions.
 In other words, a function created by user is known as user defined function, but later
it can be a part of 'C' library.
 Functions are made for code re-usability and for saving time and space.
 In C, main() is the user-defined function and first calling function in any program.
 main() is a special function that tells the compiler to start the execution of a C program
from the beginning of the function main().

How user-defined function works?


#include <stdio.h>
void functionName()
{ - - -- - - - - -
-----
}
int main()
{ ………..
functionName();
………………
}

 The execution of a C program begins from the main() function.

 When the compiler encounters functionName();, control of the program jumps to void
functionName().

 The compiler starts executing the codes inside the functionName().

3132 – Programming in C
CO1-Make use of basic programming concepts

 The control of the program jumps back to the main() function once code inside the
function definition is executed.

How to Define a Function in C

A function definition in C programming consists of a function header and afunction body.

The general form of a function definition is:

return_type function_name (parameter list/argument list)


{
body of the function – Block of code
}
∙ return_type − A function may return a value. The return_type can be of any data type of
the value the function return such as int, double, char, void etc.. 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.

∙ parameter list − A parameter is like a placeholder. Argument list contains variables names
along with their data types. These arguments are kind of inputs for the function. 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 C statements that define what
the function does.

Example : Sum of two numbers using function


#include <stdio.h>
int addNumbers(int a, int b); // function prototype

int main()
{

int n1,n2,sum;

printf("Enters two numbers: ");


3132 – Programming in C
CO1-Make use of basic programming concepts

scanf("%d %d",&n1,&n2);

sum = addNumbers(n1, n2); // function call


printf("sum = %d",sum);
return 0;
}

int addNumbers(int a, int b) // function definition


{
int result;
result = a+b;
return result; // return statement
}

Elements of user-defined function / Function Activities


∙ C programming has three elements or three activities.
∙ They are :
1. Function Declaration /Function Prototype
2. Function Definition
3. Function call

Function Declaration/Function Prototype

 A function declaration is a frame (prototype)of function that contains the function’s


name, list of parameter and return type and ends with the semicolon.

 It doesn't contain function body.

 A function prototype gives information to the compiler that the function may later be
used in the program.

 The function declarations (called prototype) are usually done above the main () function.

 General form is : return_type functionName(type1 argument1, type2 argument2, ...);


Example: int add(int x, int y); // Function Declaration

1. function name – name of the function is add()


2. return type – the return type of the function is int
3. arguments – two arguments (x and y) of type int are passed to the function ∙

Parameter names are not important in function declaration only their type is required

Example : int max(int, int);


3132 – Programming in C
CO1-Make use of basic programming concepts

Function Definition

 The function definition is an expansion of function declaration.


 It contains codes in the body part of the function for execution program by the compiler ∙
Function definition contains the block of code to perform a specific task.
 A function body consists of a single or a block of statements.
 It is also a mandatory part of a function.

The syntax of the function definition is :


return_type function_name(parameter_1, parameter_2, ........... ){
//statements
//body of the function
}
Example:
int add(int a, int b) // function body
{
int c;
c = a + b;
return c;
}

Calling a Function/Function Call

 A function call means calling a function whenever it is required in a


program.
 A function call is an optional part in a program.
 When a function is called, the control of the program is transferred to
the function definition and the compiler starts executing the codes
inside the body of a function.
Syntax : function_Name(Argument List);
Example: sum(5, 4);

Program to find the maximum of two numbers

int max(int num1,int num2); //Function Declarationint


main (){
int a =100, b = 200, result; //local variable definition
result = max(a, b); // Calling Function

3132 – Programming in C
CO1-Make use of basic programming concepts

printf("Max value is : %d\n", result );


return0;
}
int max(int num1,int num2){ // Function Definition

int result;
if(num1 > num2)
result= num1;
else
result= num2;
return result;
}

Function Arguments(Parameters)
 A function in C can be called either with arguments or without arguments.
 These function may or may not return values to the calling functions.
 All C functions can be called either with arguments or without arguments in a C
program.
 Also, they may or may not return any values.
 A function's arguments are used to receive the necessary values by the function call. ∙
They are matched by position; the first argument is passed to the first parameter, the
second to the second parameter and so on.
 A Parameter is the symbolic name for "data" that goes into a function .
 By default, the arguments are passed by value in which a copy of data is given to the
called function.
 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.
 Formal parameters behave like other local variables inside the function and are created
upon entry into the function and destroyed upon exit.

∙ Arguments are of two types :

1. Actual argument: Argument present in the function call statement.

2. Formal argument: Argument present in the function definition.

3132 – Programming in C
CO1-Make use of basic programming concepts

Scope of Variables
 The scope is the region in any program where the defined variable has its
existence.
 It cannot be accessed beyond this scope.

∙ In C programming language, there are three places where the variables can be declared:
1. Local variables which are inside a function or a block.
2. Global variables which are outside all the functions.
3. Formal parameters which are defined in the function parameters.
Local Variables

 Variables that are declared inside a function or block.

 They can be used only by statements that are inside that function or block of code.

 They are not known to functions outside.


Example
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);
return0;
}

Global Variables

 Global variables are defined outside a function or block, usually on top of the
program.

 Global variables hold their values throughout the lifetime of your program.

 They can be accessed anywhere in the program and in any function.


Example
#include<stdio.h>
int g; /* global variable declaration */int
main (){
int a, b; /* local variable declaration */
/* actual initialization */
a =10; b =20;
3132 –g Programming
= a + b; in C
printf("value of a = %d, b = %d and g = %d\n", a, b, g);
return0;
}
CO1-Make use of basic programming concepts

A program can have same name for local and global variables but the value of local
variableinside a function will take preference.

#include<stdio.h>
int g =20; /* global variable declaration */int
main (){
int g =10; /* local variable declaration */
printf("value of g = %d\n", g);
return0;
}

Formal parameters

 They are the local variables within the function and take a precedence over the
global variables.

 These variables behave like local variables in the function.


 They can be accessed inside the function but not outside the function.

Types of user defined functions in C

 Depending upon the presence of arguments and the return values, user defined
functions can be classified into five categories.
∙ They are:

1. Function with no arguments and no return values


2. Function with no arguments and return value
3. Function with arguments and no return values
4. Function with arguments and return value

1. Function with no arguments and no return value

 Such functions neither receives any data from the calling function nor returns a
value.
 In other words, the calling function does not get any value from the called
function.
 Such functions can either be used to display information because they are
completely dependent on user inputs.
 In this type, each function is independent.
 – So
3132 there is noindata
Programming C transfer between calling and called function.

Example – To find the sum of two numbers using function


CO1-Make use of basic programming concepts

#include<stdio.h>
void add(); // function declarationint
main() {
add(); // function call and argument is not passedreturn
0; }
void add() //function definition. Return type is void, doesn’t return any value {int a
=10,b = 100, sum;
sum = a + b;
printf(”Sum = %d”,sum);
}
2. Function with no arguments and return value

 This type of functions, arguments are passed through the calling function to called
function but the called function returns value.

 Function with return value means result will be sent back to the caller from the function.

 Such type of function are independent.

Example - Program to calculate the area of square using the function#include


<stdio.h>
int area(); //function prototype with return type int.int
main()
{
int square_area;
square_area = area(); // function call
printf("Area of square = %d", square_area);
return 0;
}
int area() // return type is int means it returns some value
{
int side, area;
printf(“\n Enter the side of the square :”);
scanf(“%d”, &sid);
area = side * side;
return area;
}

3. Function with arguments and no return value

 In this, arguments are passed through the calling function to called function but does not
return value.

 So it’s a one-way type communication.

– Programming
3132 Such type of in
function
C practically dependent on each other.

Example – Program to find the largest of two numbers using function#include


CO1-Make use of basic programming concepts

<stdio.h>
void greatNum(int x, int y); // Function prototype
int main()
{
int num1, num2; printf("Enter
two integers :");
scanf("%d %d",&num1, &num2);
greatNum(num1, num2); //Function called and argument is passed
return 0;
}
// return type is void meaning it return no value

void greatNum(int x, int y)


{
if(x > y){
printf("The greater number is %d", x);
}
else
{
printf("The greater number is %d", y);
}
}

3132 – Programming in C
CO1-Make use of basic programming concepts

4. Function with arguments and a return value


 Both the calling function and called function will receive data from each other.
 This is the best type, as this makes the function completely independent of inputs
andoutputs, and only the logic is defined inside the function body.
 It’s like a dual communication.
 Both functions are dependent on each other.

Example – Program to find the area of circle


#include <stdio.h>
int area(int radius); //function prototype with return type intint
main()
{
int area, radius;
printf("Enter the radius of circle :");
scanf("%d",&radius);
area = area(radius); //function call
printf("Area of circle = %d", area);
return 0;
}

int area(int r)
{
int area;
area = 3.14 * r *
r;return area;

Recursive Function
3132 – Programming in C
CO1-Make use of basic programming concepts

 Recursion is the process of repeating items in a self-similar way.


 In programming languages, if a program allows to call a function inside the same
function,then it is called a recursive call of the function.
 The C programming language supports recursion, i.e., a function to call itself.
 But while using recursion, programmers need to be careful to define an exit condition
fromthe function, otherwise it will go into an infinite loop.
 A function that calls itself is known as a recursive function. And, this
technique isknown as recursion.

Recursive Working

Example - Program to find the factorial using recursion

#include
<stdio.h>int
factorial(int i)
{
if(i <= 1)
{return
1;
}
return i * factorial(i - 1);
}
int main()
{
int n;
printf(“\n Enter a number : “);
scanf (“%d”, &n);

printf("Factorial of %d is %d\n", n, factorial(n));


3132 – Programming in C
CO1-Make use of basic programming concepts

return 0;
}

Storage class, lifetime and visibility of variables

Every variable in C programming has two properties: type and storage class.

Type refers to the data type of a variable. And, storage class determines the scope, visibility andlifetime of a
variable and/or functions within a C Program. They precede the type that they modify.

There are 4 types of storage class:

1. automatic
2. external
3. static
4. register

1. Auto

Local Variable

The variables declared inside a block are automatic or local variables. The local variables exist only inside
the block in which it is declared.
eg:

#include <stdio.h>int

main(void) {

for (int i = 0; i < 5; ++i) {


printf("C programming");
}

// Error: i is not declared at this pointprintf("%d", i);


return 0;
}

When you run the above program, you will get an error undeclared identifier i. It's because i is declared
inside the for loop block. Outside of the block, it's undeclared.

Let's take another example.int

3132 – Programming in C
CO1-Make use of basic programming concepts

main() {

int n1; // n1 is a local variable to main()


}

void func() {
int n2; // n2 is a local variable to func()
}

In the above example, n1 is local to main() and n2 is local to func().

This means you cannot access the n1 variable inside func() as it only exists inside main(). Similarly,
you cannot access the n2 variable inside main() as it only exists inside func().

2. extern

Global Variable

Variables that are declared outside of all functions are known as external or global variables. They are
accessible from any function inside the program.

eg:-

#include <stdio.h>
void display();

int n = 5; // global variableint

main()
{
++n;
display();
return 0; se
}

void display()
{
++n;
printf("n = %d", n);
}

Suppose, a global variable is declared in file1. If you try to use that variable in a different file file2, the
compiler will complain. To solve this problem, keyword extern is used in file2 to indicate that the external
variable. The extern storage class is used to give a reference of a global

3132 – Programming in C
CO1-Make use of basic programming concepts

variable that is visible to ALL the program files. When you use 'extern', the variable cannot be initialized
however, it points the variable name at a storage location that has been previously defined.

When you have multiple files and you define a global variable or function, which will also be used in
other files, then extern will be used in another file to provide the reference of defined variable or function.
Just for understanding, extern is used to declare a global variable or function in another file.

The extern modifier is most commonly used when there are two or more files sharing the same global
variables or functions as explained below.

First File: main.c

#include <stdio.h>int

count ;
extern void write_extern();

main() {
count = 5;
write_extern();
}
Second File: support.c

#include <stdio.h> extern

int count;

void write_extern(void) { printf("count


is %d\n", count);
}
Here, extern is being used to declare count in the second file, whereas it has its definition in the first file,
main.c. Now, compile these two files as follows −

$gcc main.c support.c


It will produce the executable program a.out. When this program is executed, it produces the following
result -count is 5

Register Variable

The register keyword is used to declare register variables. Register variables were supposed to be faster
than local variables.

3132 – Programming in C
CO1-Make use of basic programming concepts

Register storage class is used to define local variables that should be stored in a register instead of RAM.
This means that the variable has a maximum size equal to the register size (usually one word) and can't
have the unary '&' operator applied to it (as it does not have a memory location).

{
register int miles;
}

The register should only be used for variables that require quick access such as counters. It should also be
noted that defining 'register' does not mean that the variable will be stored in a register. It means that it
MIGHT be stored in a register depending on hardware and implementation restrictions.

Static Variable

A static variable is declared by using the static keyword. For example;static int i;

The value of a static variable persists until the end of the program.eg:

#include <stdio.h>
void display();

int main()
{
display();
display();
}
void display()
{
static int c = 1;c
+= 5;
printf("%d ",c);
}

3132 – Programming in C
CO1- Make use of basic programming concepts in c
During the first function call, the value of c is initialized to 1. Its value is increased by 5. Now, the value of c
is 6, which is printed on the screen.

During the second function call, c is not initialized to 1 again. It's because c is a static variable. The value c is
increased by 5. Now, its value will be 11, which is printed on the screen.

The static storage class instructs the compiler to keep a local variable in existence during the life-time of the
program instead of creating and destroying it each time it comes into and goes out of scope. Therefore,
making local variables static allows them to maintain their values between function calls.

The static modifier may also be applied to global variables. When this is done, it causes that variable's scope
to be restricted to the file in which it is declared.

In C programming, when static is used on a global variable, it causes only one copy of that member to be
shared by all the objects of its class.

eg:

#include <stdio.h>void

func(void); static int

count = 5;main() {

while(count--) {
func();
}

return 0;
}
void func( void ) {

static int i = 5;
i++;

printf("i is %d and count is %d\n", i, count);


}

When the above code is compiled and executed, it produces the following result –
i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0

3132 – Programming in C

You might also like