Complete Manual
Complete Manual
LABORATORY MANUAL
C Programming
111CCE-1
C Programming Lab
Student Information
Name: ___________________________________________________________________________________
Marks
Grades:
Lab Activity 25% marks
Lab Report/Exam/Quiz 10% marks
Homework/Project 15% marks
Final Exam 50% marks
Lab Policy:
Attendance is Mandatory.
Copies in labs will get a grade of ZERO.
Elearning 10% i.e 3 Lectures of 50minutes each.
-------------------------------------------------------------------------------------------------------------------------------------
I have read and understand these rules and procedures, I agree to abide by these rules
and procedures at all times while using these facilities, I understand that failure to
follow these rules will result in disciplinary action may be taken.
1. Introduction to Lab 08
Facts about C
C was invented to write an operating system called UNIX.
C is a successor of B language which was introduced around 1970
The language was formalized in 1988 by the American National Standard Institue (ANSI).
By 1973 UNIX OS almost totally written in C.
Today C is the most widely used System Programming Language.
Most of the state of the art software have been implemented using C
Why to use C?
C was initially used for system development work, in particular the programs that make-up the
operating system. C was adoped as a system development language because it produces code that runs
nearly as fast as code written in assembly language. Some examples of the use of C might be:
Operating Systems Language Compilers Assemblers
Text Editors Print Spoolers Network Drivers
Modern Programs Data Bases Language Interpreters
Utilities
1. Documentation section: The documentation section consists of a set of comment lines giving the
name of the program, the author and other details, which the programmer would like to use later.
2. Link section: The link section provides instructions to the compiler to link functions from the
system library such as using the #include directive.
3. Definition section: The definition section defines all symbolic constants such using the #define
directive.
4. Global declaration section: There are some variables that are used in more than one function. Such
variables are called global variables and are declared in the global declaration section that is outside
of all the functions. This section also declares all the user-defined functions.
5. main () function section: Every C program must have one main function section. This section
contains two parts; declaration part and executable part
1. Declaration part: The declaration part declares all the variables used in the executable part.
2. Executable part: There is at least one statement in the executable part.
These two parts must appear between the opening and closing braces. The program execution begins
at the opening brace and ends at the closing brace. The closing brace of the main function is the
logical end of the program. All statements in the declaration and executable part end with a
semicolon.
6. Subprogram section: If the program is a multi-function program then the subprogram section
contains all the user-defined functions that are called in the main () function. User-defined functions
are generally placed immediately after the main () function, although they may appear in any order.
Welcome to C Programming
Output/Conclusion:
Output/Conclusion: Welcome to C
Programming
Objectives:
1. Familiarize the usage of Input Output Statements.
2. Understand the use of data types.
Points to Remember:
INPUT AND OUTPUT
C provides standard functions scanf() and printf(), for performing formatted input and output.
These functions accept, as parameters, a format specification string and a list of variables.
FormattedOutput: The function printf() is used for formatted output to standard output based on a
format specification. The format specification string, along with the data to be output, are the
parameters to the printf() function.
Syntax: printf (format, data1, data2,……..);
In this syntax format is the format specification string. This string contains, for each variable to be output, a
specification beginning with the symbol % followed by a character called the conversion character.
Example: printf (“%c”, data1);
The conversion character % allows one data type to be converted to another type and printed. It is followed by
the format specifier letter i.e: d The data is converted to decimal (integer)
c The data is taken as a character.
s The data is a string and character from the string , are printed until a NULL, character is reached.
f The data is output as float or double with a default Precision 6.
Formatted Input: The function scanf() is used for formatted input from standard input and provides
many of the conversion facilities of the function printf().
Syntax: scanf (format, num1, num2,……);
The function scanf() reads and converts characters from the standards input depending on the string format
specification and stores the input in memory locations represented by the other arguments (num1, num2,….).
Example: scanf(“%c %d”,&Name, &Roll No);
Note: the data names are listed as &Name and &Roll No instead of Name and Roll No respectively. This is
how data names are specified in a scnaf() function. In case of string type data names, the data name is not
preceded by the character &.
VARIABLES
A variable is nothing but a name given to a storage area that our programs can manipulate. Each
variable in C has a specific type, which determines the size and layout of the variable's memory;
the range of values that can be stored within that memory; and the set of operations that can be
applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character.
It must begin with either a letter or an underscore.
Upper and lowercase letters are distinct because C is case-sensitive.
It should not be a keyword and white spaces are not allowed.
Ex: Mohammed x1 T_raise
Activity-Program-3: Assume that any month is of 30 days. Now you are given
total days. Find out the exact number of Years, Months & Days. Make a program
in which the total numbers of days are given and you have to convert that in
perfect no of days, year and month.
Activity-Program-4: You are given time in total seconds. Convert it into Hour:
Min: Seconds format. Same as the above program but here instead of days the
seconds are given and you need to convert it into hour, min and seconds format.
Objectives:
3. Familiarize the usage of Operators.
4. Familiarize the usage of different Expressions.
Points to Remember:
OPERATORS : C language offers many types of operators. They are,
1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators
High priority: * / %
Low priority: + -
The evaluation procedure of an arithmetic expression includes two left to right passes through the
entire expression. In the first pass, the high priority operators are applied as they are encountered and
in the second pass, low priority operations are applied as they are encountered. Suppose, we have an
arithmetic expression as: x = 9 - 12 / 3 + 3 *2 - 1
First Pass
Step 1: x = 9-4 + 3 * 2 - 1
Step 2: x = 9 - 4 + 6 – 1
Second Pass
Step 1: x = 5 + 6 - 1
Step 2: x = 11 - 1
Step 3: x = 10
But when parenthesis is used in the same expression, the order of evaluation gets changed. i.e its high
priority compare to other operators in the above expression.
Activity Program 6:. Write a C program to find the sum of individual digits of a 3
digit number. (Hint: 547 = 5+ 4+ 7 i.e sum=16)
Activity Program 7:. Write a C program to read the values of x and y and print
the results of the following expressions in one line:
i. (x + y) / (x - y)
ii. (x + y)(x - y)
Objectives:
1. Familiarize the usage different if else.
Points to Remember:
The if Statement: A simple condition is expressed in the form
if (condition)
statement;
It starts with the keyword if, followed by a condition (a logical expression) enclosed within
parenthesis, followed by the result statement. The resulting statement is executed if the
condition is evaluated as TRUE. Note that there is no semicolon (;) after the condition
expression. Consider the following example:
if (marks >50)
printf("You have passed the exam!");
If the value of the variable “marks” is greater than 50, the message “You have passed the
exam!” is displayed on the screen; otherwise the statement is skipped and no message is
displayed.
Program 1: Write a program which accepts a number (an amount of money to be
paid by a customer in riyals) entered from the keyboard. If the amount is greater
than or equal to 1000 riyals, a 5% discount is given to the customer. Then display
the final amount that the customer has to pay.
#include <stdio.h>
void main()
{ float amount,final_amount, discount;
printf("Enter amount: ");
scanf("%f", &amount); //get amount
if (amount >= 1000) // if amount >= 1000 give discount
{ discount = amount* 0.05;
final_amount = amount - discount; Enter amount: 1234
Program 2: Write a program which accepts a number (an amount of money to be paid
by a customer in riyals) entered from the keyboard. If the amount is greater than or
equal to 1000 riyals, a 5% discount is given. If the amount is less than 1000 riyals, a 3%
discount is given to the customer. Display the final amount that the customer has to pay.
#include <stdio.h>
void main()
{ float amount,final_amount, discount;
printf("Enter amount: ");
scanf("%f", &amount); //get amount
if (amount >= 1000) // if amount >= 1000 give discount
{ discount = amount*0.05;
final_amount = amount - discount;
printf ("Discount 5 percent: %.2f", discount);
}
else Enter amount: 900
{ discount = amount*0.03;
Discount 3 percent: 27.00
final_amount = amount - discount;
printf ("Discount 3 percent: %.2f", discount); Total: 873.00
}
printf ("\nTotal: %.2f", final_amount);
}
The if-else-if Ladder: In certain cases multiple conditions are to be detected. In such cases the
conditions and their associated statements can be arranged in a construct that takes the form.
if (condition-1)
statement-1; else if (condition-2)
statement-2; else if (condition-3)
statement-3;
… else
statement-n;
Activity Program 5: Write a C Program to accept a character and check whether the
Activity Program 6: Write a C Program to swap two numbers without third variable.
Activity Program 7: Write a C Program to insert any number and check whether the
If any or both the values are <=0, print the output as “Wrong Input Values”.
If both the values are equal, find Area(s*s) and Perimeter(4*s) of Square.
If both the values are different, find Area(l*b) and Perimeter(2*[l+b])of Rectangle.
Objectives:
5. Familiarize the usage of Nested if.
6. Familiarize the usage of switch.
Points to Remember:
Nesting Conditions : Sometimes we need to check for multiple decisions. This can be accomplished
by two approaches; using compound relational tests or using nested conditions. When conditions are
nested the if-else/if- else-if construct may contain other if-else/if-else-if constructs within themselves.
Program 1: Write a C program to find maximum of three numbers using nested if-else.
#include <stdio.h>
void main()
{ int a=10, b=20, c=15;
if(a>b)
{ if(a>c)
printf("A is Big %d",a);
else
printf("C is Big %d",c);
}
else
{ if(b>c)
printf("B is Big %d",b);
else
printf("C is Big %d",c);
}
}
Program 2: Write a C program to calculate electricity bill as per the give below.
(User can enter the Consumption Kwh and Mention Consumption Category 1 as Residential, 2 as
Commercial and 3 as Agricultural & Charities.)
next-statement;
Objectives:
1. Familiarize the usage of for loop.
2. Familiarize the usage of while loop.
3. Familiarize the usage of do-while loop
Points to Remember:
A Program is usually not limited to a linear sequence of instructions or conditional structures and it is
sometimes required to execute a statement or a block of statements repeatedly. These repetitive
constructs are called loops or control structures. The C language supports three constructs; namely
for, while and do-while loops.
The for loop: The for loop construct is used to repeat a statement or block of statements a
specified number of times. The general form of a for loop is:
for (counter-initialization; condition; increment-decrement)
statement(s);
Program 1: Write a C program to calculate the sum of all the even numbers up to 100.
#include <stdio.h>
void main()
{
int counter, sum = 0;
for(counter=0; counter <= 100; (counter += 2)) //increment by 2
{
sum += counter;
}
printf("Total : %d", sum);
}
The while loop:The while loop construct contains only the condition. The programmer has to take
care about the other elements (initialization and incrementing). The general form of the while loop is:
while (condition)
{ statement(s);
}
Break and Continue: The break keyword is used to terminate a loop, immediately bypassing any
conditions. The control will be transferred to the first statement following the loop block. If you have nested
loops, then the break statement inside one loop transfers the control to the immediate outer loop. The break
statement can be used to terminate an infinite loop or to force a loop to end before its normal termination.
Consider the following example’s:
Activity Program 6: Write a program to compute the sum of all integers between
any given two numbers. (Read the input from keyboard)
Activity Program 8: Write the only logic(i.e code) for the following programs:
0 *
1 0
* *
2 1 0
3 2 1 0 * * *
4 3 2 1 0 * * * *
* * * * *
Objectives:
1. Familiarize the usage of one dimensional arrays in C Programming.
Points to Remember:
Arrays are a series of elements of the same data type placed consecutively in memory that can be individually
referenced by adding an index to a unique name. Using an array we can store five values of type int with a
single identifier without having to declare five different variables with a different identifier. Arrays are useful
when you store related data items, such as grades received by the students, sine values of a series of angles, etc.
Like any other variable in C an array must be declared before it is used. The typical declaration of an array is:
data-type array-name[no-of-elements];
Intialization of an Array:
An array will not be initialized when it is declared; therefore its contents are undetermined
until we store some values in it. The following array can hold marks for five subjects.
int marks[5];
The elements of an array can be initialised in two ways. In the first approach, the value of
each element of the array is listed within two curly brackets ({}) and a comma (,) is used to
separate one value from another. For example:
marks[5] = {55, 33, 86, 81, 67};
In the second approach elements of the array can be initialised one at a time. This approach
makes use of the format:
array-name[index];
For example:
marks[0] = 55;
marks[1] = 33;
marks[2] = 86;
marks[3] = 81;
marks[4] = 67;
Output:
Array[5]: 10 20 50 60 90
Average : 72.00
Activity Program 5: Write a C program that asks the user to type any five
numbers and save them in an array. The program finds and prints the average
Minimum = 1, Average = 3
Objectives:
1. Familiarize the usage of multi dimensional arrays in C Programming.
Points to Remember:
One-dimensional (or single dimensional) array, as it takes one index and store only one type of data.
Multi dimensional array can takes more than one index and strore the data. Two- dimensional array
can be declared in the following form:
data-type array-name[size-1][size-2];
You can declare an array to hold marks of 100 students with store marks of 5 subjects as in the
following example:
int students[100][5];
The first index defines the number of students and the second index defines the number of subjects.
Altogether it declares 500 (1005) memory locations. Initialising marks of the first student can be
performed in the following manner.
marks[0][0] = 55;
marks[0][1] = 33;
marks[0][2] = 86;
marks[0][3] = 81;
marks[0][4] = 67;
Similarly we can define arrays with n dimensions and such arrays are called n-dimensional or
multidimensional arrays. A two-dimensional array is initialised in the same way. The following
statement declares and initialises a two-dimensional array of type int which holds the scores of three
students in five different tests.
#include <stdio.h>
void main()
{ int i,j;
int marks[3][4]; //array of 5 elements
int sum[3];
float avg=0, average[3];
for(i=0;i<3;i++)
{ printf("==========Marks of STUDENT_%d========== \n", i+1);
sum[i]=0;
for(j=0;j<4;j++)
{ printf("Enter marks for subject %d: ", j+1);
scanf("%d", &marks[i][j]); //get the marks
sum[i]=sum[i]+marks[i][j]; // sum of marks for each student
}
}
for(i=0;i<3;i++)
{ average[i] = sum[i]/4.0;
printf("\n Average marks of STUDENT_%d : %.2f ", i+1, average[i]);
avg=avg+average[i]; // sum of all average marks for each student
}
printf("\n Average marks taken by all the 3 students== %.2f ", avg/3.0);
}
Output:
==========Marks of STUDENT_1==========
Enter marks for subject 1: 55
Enter marks for subject 2: 33
Enter marks for subject 3: 86
Enter marks for subject 4: 81
==========Marks of STUDENT_3==========
Enter marks for subject 1: 39
Enter marks for subject 2: 82
Enter marks for subject 3: 59
Enter marks for subject 4: 57
1 0 2 2 3 2
+ =
0 1 2 2 2 3
Activity Program_3: Write a C program to store nine elements for 3x3 matrixes
1 2 3 1
4 5 6 = 5
7 8 9 9
Objectives:
1. Familiarize the usage of functions.
2. Understand Recursive functions with return value.
Points to Remember:
The C functions that you have used so far (such as printf and scanf) are built into the C libraries, but
you can also write your own functions. Therefore functions can be classified as built-in and user
defined. A modular program is usually made up of different functions, each one accomplishing a
specific task such as calculating the square root or the factorial. In general a modular program consists
of the main( ) function followed by set of user defined functions as given below
#include
……
#define …..
Prototypes of functions
int main( )
{ ……….
}
function_1( )
{ ………..
}
function_2( )
{ ………..
}
…………
function_n()
{ ………..
}
The source code contains other elements in addition to the function blocks. It starts with
the #include directive, followed by the #define directive (if any) then followed by the
prototypes of functions. The prototype is a declaration of a function used in the program.
Then comes the program building block which includes the main() function and
implementation of the user defined functions.
USES OF C FUNCTIONS:
C functions are used to avoid rewriting same logic/code again and again in a program.
There is no limit in calling C functions to make use of same functionality wherever required.
We can call functions any number of times in a program and from any place in a program.
A large C program can easily be tracked when it is divided into functions.
The core concept of C functions are, re-usability, dividing a big task into small pieces to achieve
the functionality and to improve understandability of very large C programs.
CALL BY VALUE:
In call by value method, the value of the variable is passed to the function as parameter.
The value of the actual parameter can not be modified by formal parameter.
Different Memory is allocated for both actual and formal parameters. Because, value of actual
parameter is copied to formal parameter.
Output:
Enter radius: 10
Area : 314.10
Circumference : 62.82
Activity Program 4: Write a C Program to swap two numbers using functions and
without using temporary variable.
Activity Program 5: Write a C Program to print Fibonacci series with limit upto
10 numbers using Recursive function. (Fibonacci series: 0,1,1,2,3,5,8,13….etc.)
Objectives:
1. Familiarize the usage of String functions.
2. Understand character array’s.
Points to Remember:
Strings are defined as an array of characters. The difference between a character array and a string is
the string is terminated with a special character ‘\0’. We can perform String operations using the pre-
defined Standard Library functions of “string.h” header file.
What is NULL Char ‘\0’: ‘\0’ represents the end of the string. It is also referred as String
terminator & Null Character.
Program 1: Write a C program using two string functions gets() and puts() to
take string input from the user and display it respectively
#include<stdio.h>
void main()
{ char name[30];
printf("Enter name: ");
gets(name); //Function to read string from user like scanf("%s",&name);
printf("Name: ");
puts(name); //Function to display string like printf("%s",name); but limited to word
}
strcat: The strcat() function will append a copy of the source string to the end of destination string.
The strcat() function takes two arguments: 1) dest 2) src
It will append copy of the source string in the destination string. The terminating character at the end
of dest is replaced by the first character of src. Return value: The strcat() function returns dest.
Program 3: Write a C program that will concatenate one string to the end of
another string and display it as output.
#include<string.h>
#include<stdio.h>
void main()
{ char dest[50] = "This is an";
char src[50] = " example";
strcat(dest, src);
puts(dest);
}
Activity Program 4: Write a C Program that will read two strings. If given two
strings are same then print “Given strings are same”. If given two strings are not
same then print “Given strings are not same”.
Objectives:
3. Familiarize with pointers.
Points to Remember:
Pointer in C language is a variable that stores/points the address of another variable. A Pointer in C is
used to allocate memory dynamically i.e. at run time. The pointer variable might be belonging to any of
the data type such as int, float, char, double, short etc.
Pointer Syntax : data_type *var_name; Example : int *p; char *p;
Where, * is used to denote that “p” is pointer variable and not a normal variable.
Declaring Pointers
A pointer is declared using the indirection (*) operator. The typical declaration of a pointer is:
data-type *pointer-name;
If a pointer “a” is pointing to an integer, it is declared as:
int *a;
Since a pointer is a variable, its value is also stored in another memory location. Therefore in
computation even the address of the pointer can be used. The location of a variable in memory is
system dependent and therefore the address of a variable is not known directly. The address
operator (&) allow us to retrieve the address from a variable associated with it.
#include <stdio.h>
void main()
{ int number = 20; int *pnt;
pnt = &number;
printf("\nThe number is: %d", number);
printf("\nThe address of the number is: %d", &number);
printf("\nThe pointer is: %d", pnt);
printf("\nThe address of the pointer is: %d", &pnt);
printf("\nThe value of the pointer is: %d", *pnt);
}
The number is: 20
Text Strings and Pointers: A character pointer is used to point to the first character of a string
as given in the following example:
char *a;
a = "Hello World!";
First character: H
First character: 72
1 Pointer arithmetic
There are four arithmetic operators that can be used in pointers: ++, --, +, -
2 Array of pointers
You can define arrays to hold a number of pointers.
3 Pointer to pointer
C allows you to have pointer on a pointer and so on.
CALL BY REFERENCE:
In call by reference method, the address of the variable is passed to the function as parameter.
The value of the actual parameter can be modified by formal parameter.
Same memory is used for both actual and formal parameters since only address is used by both
parameters.
and n = 44
and b = 22
5 4 6 8 9
Activity Program 6: Write a C program to find the length of string using pointers.
Objectives:
1. Familiarize with Structures.
2. Familiarize with Unions.
Points to Remember:
Structure: As we know that Array is collection of the elements of same type , but many time we have
to store the elements of the different data types. Suppose Student record is to be stored, then for
storing the record we have to group together all the information such as Roll, name, Percent which
may be of different data types. Ideally Structure is collection of different variables under single name.
Basically Structure is for storing the complicated data. A structure is a convenient way of grouping
several pieces of related information together.
Definition of Structure in C: Structure is composition of the different variables of different data types,
grouped under same name.
typedef struct
{ char name[64];
char course[128];
int age;
int year;
} student;
Each member declared in Structure is called member. Name given to structure is called as tag.
Structure member may be of different data type including user defined data-type also. Declaration of
Structure reserves no space. Struct keyword is used to declare structure.
Program 1: Write a C Program to demonstrate struct student with id, name and percentage
of marks.
#include <stdio.h>
Output/Conclusion:
Id is: 1
Name is: Ali
Percentage is: 86.50
REFERENCES
1. E. Balagurusamy, “Computing fundamentals and C Programming”, 2nd edition, McGraw-
Hill, India, 2017. ISBN-13: 978-9352604166