C MODULE 1
C MODULE 1
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.
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
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;
...
}
1. – Programming in C
3132
CO1-Make use of basic programming concepts
{
Body of else Statement;
}
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
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
}
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;
}
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
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
3132 – Programming in C
CO1-Make use of basic programming concepts
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
do – while Loop
3132 – Programming in C
CO1-Make use of basic programming concepts
Syntax
do {
// the body of the loop
}
while (testExpression);
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
Syntax:
for (initializationStatement; testExpression; updateStatement)
{
// statements inside the body of loop
}
3132 – Programming in C
CO1-Make use of basic programming concepts
int main()
{
int i;
for (i = 1; i < 11; ++i)
{
printf("%d ", i);
}
return 0;
}
Infinite Loop
Example
main ()
{
for(;;)
{
printf("welcome to ");
}
}
3132 – Programming in C
CO1-Make use of basic programming concepts
Nested 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
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
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.
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
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;
return 0;
}
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;
}
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.
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.
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:
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 :
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.
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().
When the compiler encounters functionName();, control of the program jumps to void
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.
∙ 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.
int main()
{
int n1,n2,sum;
scanf("%d %d",&n1,&n2);
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.
Parameter names are not important in function declaration only their type is required
Function Definition
3132 – Programming in C
CO1-Make use of basic programming concepts
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.
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
They can be used only by statements that are inside that function or block of code.
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.
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.
Depending upon the presence of arguments and the return values, user defined
functions can be classified into five categories.
∙ They are:
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.
#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.
In this, arguments are passed through the calling function to called function but does not
return value.
– Programming
3132 Such type of in
function
C practically dependent on each other.
<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
3132 – Programming in C
CO1-Make use of basic programming concepts
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
Recursive Working
#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);
return 0;
}
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.
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) {
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.
3132 – Programming in C
CO1-Make use of basic programming concepts
main() {
void func() {
int n2; // n2 is a local variable 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();
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.
#include <stdio.h>int
count ;
extern void write_extern();
main() {
count = 5;
write_extern();
}
Second File: support.c
int count;
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
count = 5;main() {
while(count--) {
func();
}
return 0;
}
void func( void ) {
static int i = 5;
i++;
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