C Programming Lab Manual
C Programming Lab Manual
LAB MANUAL
C Programming
for
Dr. H. S. Shinde
Dean Engineering
LABORATORY MANUAL CONTENTS
This manual is intended for the Second year students of Computer Science and
Engineering in the subject of Programming in C. This manual typically contains
practical/Lab Sessions related Programming. In C programming covering various
aspects related to the subject to enhance understanding.
Students are advised to thoroughly go through this manual rather than only topics
mentioned in the syllabus as practical aspects are the key to understanding and
conceptual visualization of theoretical aspects covered in the books.
1. Make an entry in the Log Book as soon as you enter the Laboratory.
2. All the students should sit according to their roll numbers starting from
their left to right.
3. All the students are supposed to enter the terminal number in the logbook.
4. Do not change the terminal on which you are working.
5. All the students are expected to get at least the algorithm of the
program/concept to be implemented.
6. Strictly observe the instructions given by the teacher/Lab Instructor.
Mission of UDICT
1. PEO1. The graduates will utilize their expertise in the IT industry and
solve industry technological problems.
2. PEO2. Graduates should excel in engineering positions in industry
and other organizations that emphasize design & implementation of
IT applications.
3. PEO3. Graduates will be innovators & professionals in
technology development, deployment & system implementation.
4. PEO4. Graduates will be pioneers in engineering, engineering
management, research and higher education.
5. PEO5. Graduates will be good citizens & cultured human being
with full appreciation of of IT professional ethical & social
responsibilities
Program Specific Outcomes
CO1. Understand and develop C programming using variables and data types..
CO2. Apply the concepts of looping, branching, and decision-making statements for a
given problem.
Aim:- (a) Write a C program to find the sum and average of three numbers.
Theory:
Before we begin with our first C program do remember the following rules that are applicable to
all C programs:
(a) Each instruction in a C program is written as a separate statement. Therefore a complete C
program would comprise a series of statements.
(b) The statements in a program must appear in the same order in which we wish them to be
executed; unless of course the logic of the problem demands a deliberate ‘jump’ or transfer of
control to a statement, which is out of sequence.
(c) Blank spaces may be inserted between two words to improve the readability of the statement.
However, no blank spaces are allowed within a variable, constant or keyword.
(d) All statements are entered in small case letters.
(e) C has no specific rules for the position at which a statement is to be written. That’s why it is
often called a free-form language.
(f) Every C statement must end with a ;. Thus ; acts as a statement terminator. Let us now write
down our first C program.
Assuming that you are using a Turbo C or Turbo C++ compiler, here are the steps that you need
to follow to compile and execute your first C program…
(a) Start the compiler at C> prompt.
(b) The compiler (TC.EXE is usually present in C:\TC\BIN directory).
( c) Select New from the File menu.
(d) Type the program. Save the program using F2 under a proper name (say Program1.c).
(e) Use Ctrl + F9 to compile and execute the program. Use Alt + F5 to view the output.
Flowchart:
Program:
#include <stdio.h>
int main()
{
int a, b, c, sum;
float avg;
// Asking for input
printf("Enter 3 numbers: \n");
scanf("%d %d %d", &a, &b, &c);
// Calculating sum
sum = a + b + c;
// Calculating average of 3 numbers
avg = sum / 3;
// Displaying output
printf("Sum = %d \n", sum);
printf("Average = %.2f", avg);
return 0;
}
Output:
Enter 3 numbers:
3
5
7
Sum = 15
Average = 5.00
Aim:- (b) Write a C program to find the sum of individual digits of a given positive integer.
Flowchart
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,sum=0;
printf("enter a +ve integer"); // enter a integer value
scanf("%d",&n);
while(n>0) // checks the condition
{
sum=sum+n%10; // sum + remainder value
n=n/10;
}
printf("sum of individual digits of a positive integer is %d",sum); // prints the sum of individual
digits
}
Output:
enter a +ve integer456
sum of individual digits of a positive integer is 15
Experiment No. 2
Aim:- Write a C program to generate the first n terms of the Fibonacci sequence.
Theory:
C has three major decision making instructions—the if statement, the if-else statement, and the
switch statement. A fourth, somewhat less important structure is the one that uses conditional
operators. In this chapter we will explore all these ways (except switch, which has a separate
chapter devoted to it, later) in which a C program can react to changing circumstances.
A decision control instruction can be implemented in C using:
(a) The if statement
(b) The if-else statement
(c) The conditional operators
C uses the keyword to implement the decision control instruction. The general form of if
statement looks like this:
For Loop
Program:
#include <stdio.h>
int main()
{
int i, n;
// initialize first and second terms
int t1 = 0, t2 = 1;
// initialize the next term (3rd term)
int nextTerm = t1 + t2;
// get no. of terms from user
printf("Enter the number of terms: ");
scanf("%d", &n);
// print the first two terms t1 and t2
printf("Fibonacci Series: %d, %d, ", t1, t2);
// print 3rd to nth terms
for (i = 3; i <= n; ++i) {
printf("%d, ", nextTerm);
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
}
return 0;
}
Output:
Enter the number of terms: 10
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
Flowchart
Program:
#include<stdio.h>
void main()
{
int i, num, n, count;
printf("Enter the range: ");
scanf("%d", &n);
printf("The prime numbers in between the range 1 to %d:",n);
for(num = 1;num<=n;num++){
count = 0;
for(i=2;i<=num/2;i++){
if(num%i==0){
count++;
break;
}
}
if(count==0 && num!= 1)
printf("%d ",num);
}
}
Output:
Enter the range:50
The prime numbers in between the range 1 to 50:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Flowchart
Program
#include <stdio.h>
int main() {
int num, originalNum, remainder, result = 0;
printf("Enter a three-digit integer: ");
scanf("%d", &num);
originalNum = num;
while (originalNum != 0) {
// remainder contains the last digit
remainder = originalNum % 10;
result += remainder * remainder * remainder;
// removing last digit from the orignal number
originalNum /= 10;
}
if (result == num)
printf("%d is an Armstrong number.", num);
else
printf("%d is not an Armstrong number.", num);
return 0;
}
Output:
Enter an integer: 1634
1634 is an Armstrong number.
Experiment No. 3
Aim:- 3 a) Write a C program to check whether the given number is perfect or not
Flowchart:
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
// declare and initialize the variables
int num, rem, sum = 0, i;
// take input from the user.
printf("Enter a number\n");
scanf("%d", &num);
// find all divisors and add them
for(i = 1; i < num; i++)
{
rem = num % i;
if (rem == 0)
{
sum = sum + i;
}
}
if (sum == num)
printf(" %d is a Perfect Number");
else
printf("\n %d is not a Perfect Number");
getch();
}
Output:
Enter a number
28
Entered number is a Perfect Number
#include<stdio.h>
int main(){
int n,i;
int fact,rem;
printf("Enter a number : ");
scanf("%d",&n);
printf("");
int sum = 0;
int temp = n;
while(n){
i = 1,fact = 1;
rem = n % 10;
while(i <= rem){
fact = fact * i;
i++;
}
sum = sum + fact;
n = n / 10;
}
if(sum == temp)
printf("%d is a strong number",temp);
else
printf("%d is not a strong number",temp);
return 0;
}
Output:
Aim:-
4 a) Write a C program to find the roots of a quadratic equation.
So,
Flowchart:
Program:
# include<stdio.h>
# include<math.h>
int main () {
float a,b,c,r1,r2,d;
d= b*b - 4*a*c;
if (d>0) {
r1 = -b+sqrt (d) / (2*a);
r2 = -b-sqrt (d) / (2*a);
printf ("The real roots = %f %f", r1, r2);
}
else if (d==0) {
r1 = -b/(2*a);
r2 = -b/(2*a);
printf ("Roots are equal =%f %f", r1, r2);
}
else
printf("Roots are imaginary");
return 0;
}
Output:
Case 1:
Enter the values of a b c: 1 4 3
The real roots = -3.000000 -5.000000
Case 2:
Enter the values of a b c: 1 2 1
Roots are equal =-1.000000 -1.000000
Case 3:
Enter the values of a b c: 1 1 4
Roots are imaginary
Theory:
Decisions Using switch 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:
Program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a, b, i;
printf("Enter Number 1 :--> ");
scanf("%d", &a);
printf("\nEnter Number 2 :--> ");
scanf("%d", &b);
do
{
printf("\nEnter 1 for 'Addition' ");
printf("\nEnter 2 for 'Subtraction' ");
printf("\nEnter 3 for 'Multiplication' ");
printf("\nEnter 4 for 'Division' \n");
printf("Enter 0 for Exit ");
printf("\nEnter your choice :--> ");
scanf("%d", &i);
switch(i)
{
case 0: break;
case 1:
printf("\na + b = %d\n", a + b);
break;
case 2:
printf("\na - b = %d\n", a - b);
break;
case 3:
printf("\na * b = %d\n", a * b);
break;
case 4:
printf("\na / b = %f\n", a / b);
break;
default:
printf("\nEnter valid option\n");
}
} while(i != 0);
}
Output:
Enter Number 1 :--> 8
a + b = 11
Aim:-
5 a) Write a C program to find factorial of a given integer using non-recursive function
Theory:
A function is a self-contained block of statements that perform a coherent task of some kind.
Every C program can be thought of as a collection of these functions. As we noted earlier, using
a function is something like hiring a person to do a specific job for you. Sometimes the
interaction with this person is very simple; sometimes it’s complex
Flowchart:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i;
unsigned long long factorial = 1;
else
{
for(i=1; i<=n; ++i)
{
factorial *= i; // factorial = factorial*i;
}
printf("Factorial of Number %d = %llu", n, factorial);
}
getch();
}
Output:
Enter a number to find factorial:5
Factorial of Number 5 = 20
Flowchart
Figure: Recursion
Program:
#include<stdio.h>
long int multiplyNumbers(int n);
int main() {
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n));
return 0;
}
Output:
Enter a positive integer: 6
Factorial of 6 = 720
Experiment No. 6
Aim:-
6 a) Write C program to find GCD of two integers by using recursive function.
Theory:
Flowchart:
#include <stdio.h>
int hcf(int n1, int n2); //function declaration
int main() {
int n1, n2;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
Output:
Enter two positive integers: 366
60
G.C.D of 366 and 60 is 6.
#include<stdio.h>
#include<conio.h>
#include<math.h>
Output:
enter the two numbers:10 30
GCD of 10
Experiment No. 7
Aim:-
7a) Write a C program to find the largest and smallest number in a list of integers.
Theory:
Array
An array in C is a fixed-size collection of similar data items stored in contiguous memory
locations. It can be used to store the collection of primitive data types such as int, char, float, etc.,
and also derived and user-defined data types such as pointers, structures, etc.
Flowchart:
#include<stdio.h>
int main()
{
int i, large,n;
int a[n];
//int a[5]={4,3, 5,8,7};
printf("Enter count for array elements");
scanf("%d",&n);
printf("Enter array elements");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
large=a[0];
for(i=1;i<n;i++)
{
if(a[i]>large)
large=a[i];
}
printf("largest no. is: %d",large);
}
Output:
Enter count for array elements 5
Enter array elements 3 6 9 4 2
largest no. is: 9
Program:
#include<stdio.h>
int main()
{
int i,small,n;
int a[n];
//int a[5]={4,3, 5,8,7};
printf("Enter count for array elements");
scanf("%d",&n);
printf("Enter array elements");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
small=a[0];
for(i=1;i<n;i++)
{
if(a[i]<small)
small=a[i];
}
printf("Smallest no. is: %d",small);
}
Output:
Enter count for array elements 5
Enter array elements 6 2 8 4 9
Smallest no. is: 2
b) Write a C program to Sort the Array in an Ascending Order.
Flowchart:
#include <stdio.h>
void main (){
int num[20];
int i, j, a, n;
printf("enter number of elements in an array");
scanf("%d", &n);
printf("Enter the elements");
for (i = 0; i < n; ++i)
scanf("%d", &num[i]);
Output:
enter number of elements in an array
5
Enter the elements
12
23
89
11
22
The numbers in ascending order is:
11
12
22
23
89
#include <stdio.h>
int main() {
int A[3][3], B[3][3];
int row, col, isSym;
// Take a matrix A as input from user
printf("Enter the elements in matrix of size 3x3: \n");
for (row = 0; row < 3; row++) {
for (col = 0; col < 3; col++) {
scanf("%d", &A[row][col]);
}
}
// Finds the transpose of matrix A
for (row = 0; row < 3; row++) {
for (col = 0; col < 3; col++) {
// Stores each row of matrix A to each column of matrix B
B[row][col] = A[col][row];
}
}
printf("\n");
}
} else {
printf("\n Matrix is not Symmetric.");
}
return 0;
}
Output:
Enter elements in matrix of size 3×3:
123
345
456
Theory:
Two-Dimensional Array in C
The two-dimensional array is also called a matrix
The basic form of declaring a 2D array with x rows and y columns in C is shown below.
Syntax:
data_type array_name[x][y];
where,
● data_type: Type of data to be stored in each element.
● array_name: name of the array
● x: Number of rows.
● y: Number of columns.
We can declare a two-dimensional integer array say ‘x’ with 10 rows and 20 columns as:
● Example:
int x[10][20];
Program:
#include <stdio.h>
int main() {
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
printf("Enter the number of rows (between 1 and 100): ");
scanf("%d", &r);
printf("Enter the number of columns (between 1 and 100): ");
scanf("%d", &c);
printf("\nEnter elements of 1st matrix:\n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}
printf("Enter elements of 2nd matrix:\n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element b%d%d: ", i + 1, j + 1);
scanf("%d", &b[i][j]);
}
// adding two matrices
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
sum[i][j] = a[i][j] + b[i][j];
}
// printing the result
printf("\nSum of two matrices: \n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("%d ", sum[i][j]);
if (j == c - 1) {
printf("\n\n");
}
}
return 0;
}
Output:
Program:
#include <stdio.h>
#include <stdlib.h>
#define r1 2
#define c1 3
#define r2 3
#define c2 2
void Matrix_mul (int mat1[][c1], int mat2[][c2])
{
int mul[r1][c2];
printf ("Multiplication of given two matrices is:\n");
for (int i = 0; i < r1; i++)
{
for (int j = 0; j < c2; j++)
{
mul[i][j] = 0;
for (int k = 0; k < r2; k++)
{
mul[i][j] += mat1[i][k] * mat2[k][j];
}
printf ("%d\t", mul[i][j]);
}
printf ("\n");
}
}
int main ()
{
int mat1[r1][c1] = { {0, 1, 2}, {3, 4, 5} };
int mat2[r2][c2] = { {1, 2}, {3, 4}, {5, 6} };
int mul[r1][c2], i, j, k;
Output:
matrix 1 is :
0 1 2
3 4 5
matrix 2 is :
1 2
3 4
5 6
13 16
40 52
Experiment No. 9
Aim:- 9a) Write a C program to use function to insert a sub-string in to given main string
from a given Position.
Theory:
String:
The way a group of integers can be stored in an integer array, similarly a group of characters can
be stored in a character array. Character arrays are many a time also called strings. Many
languages internally treat strings as character arrays, but somehow conceal this fact from the
programmer. Character arrays or strings are used by programming languages to manipulate text,
such as words and sentences. A string constant is a one-dimensional array of characters
terminated by a null ( ’\0’ ). For example,
char name[ ] = { 'H', 'A', 'E', 'S', 'L', 'E', 'R', '\0' } ;
Each character in the array occupies 1 byte of memory and the last character is always ’\0’. What
character is this? It looks like two characters, but it is actually only one character, with the \
indicating that what follows it is something special. ’\0’ is called a null character. Note that ’\0’
and ’0’ are not same. ASCII value of ’\0’ is 0, whereas ASCII value of ’0’ is 48. Figure 15.1
shows the way a character array is stored in memory. Note that the elements of the character
array are stored in contiguous memory locations. The terminating null (’\0’) is important,
because it is the only way the functions that work with a string can know where the string ends.
In fact, a string not terminated by a ’\0’ is not really a string, but merely a collection of
characters.
Figure: String
C String Declaration Syntax
Declaring a string in C is as simple as declaring a one-dimensional array. Below is the basic
syntax for declaring a string.
char string_name[size];
In the above syntax string_name is any name given to the string variable and size is used to
define the length of the string, i.e the number of characters strings will store.
Algorithm:
Step 1:
Start
Step 2:
read main string and sub string
Step 3:
find the length of main string(r)
Step 4:
find length of sub string(n)
Step 5:
copy main string into sub string
Step 6:
read the position to insert the sub string(p)
Step 7:
copy sub string into main string from position p - 1
Step 8:
copy temporary string into main string from position p +
n - 1
Step 9: print the strings
Step 10: Stop
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str1[20], str2[20];
int l1, l2, n, i;
clrscr();
puts("Enter the string 1\n");
gets(str1);
l1 = strlen(str1);
puts("Enter the string 2\n");
gets(str2);
l2 =
(str2);
printf("Enter the position where the string is to be
inserted\n");
scanf("%d", &n);
for(i = n; i < l1; i++)
{
str1[i + l2] = str1[i];
}
for(i = 0; i < l2; i++)
{
str1[n + i] = str2[i];
}
str2[l2 + 1] = '\0';
printf("After inserting the string is %s", str1);
getch();
}
int main() {
char str1[100], str2[50];
int l1, l2, n, i;
printf("Enter the main string: ");
scanf("%s", str1);
printf("Enter the sub-string: ");
scanf("%s", str2);
printf("Enter the position where the item has to be inserted: ");
scanf("%d", &n);
l1 = strlen(str1);
l2 = strlen(str2);
for (i = l1; i >= n; i--) {
str1[i + l2] = str1[i];
}
for (i = 0; i < l2; i++) {
str1[n + i] = str2[i];
}
printf("After inserting, the string is: %s\n", str1);
return 0;
}
b) Write a C program to swap the values of two variables using (i) Call by value (ii) Call by
reference
The two types of function calls—call by value and call by reference. Arguments can generally be
passed to functions in one of the two ways:
(a) sending the values of the arguments
(b) sending the addresses of the arguments
In the first method, the ‘value’ of each of the actual arguments in the calling function is copied
into corresponding formal arguments of the calling function.
In the second method (call by reference), the addresses of actual arguments in the calling
function are copied into the formal arguments of the called function. This means that, using these
addresses, we would have access to the actual arguments and hence we would be able to
manipulate them.
#include <stdio.h>
void swap(int x, int y){
int temp = x;
x = y;
y = temp;
}
int main()
{
int x = 10;
int y = 11;
printf("Values before swap: x = %d, y = %d\n", x,y);
swap(x,y);
printf("Values after swap: x = %d, y = %d", x,y);
}
Output:
#include <stdio.h>
void swap(int *x, int *y){
int temp = *x;
*x = *y;
*y = temp;
}
int main(){
int x = 10;
int y = 11;
printf("Values before swap: x = %d, y = %d\n", x,y);
swap(&x,&y);
printf("Values after swap: x = %d, y = %d", x,y);
}
Output:
Aim:
10a) Write a C program using user-defined functions to determine whether the given string
is palindrome or not.
Flowchart
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = { "abbba" };
// Start from first and
// last character of str
int l = 0;
int h = strlen(str) - 1;
// Keep comparing characters
// while they are same
while (h > l) {
if (str[l++] != str[h--]) {
printf("%s is not a palindrome\n", str);
return 0;
// will return from here
}
}
Output:
abbba is a palindrome
b) Write a C program that displays the position or index in the main string S where the sub
string T begins, or - 1 if S doesnot contain T.
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char s[30], t[20];
char *found;
clrscr();
/* Entering the main string */
puts("Enter the first string: ");
gets(s);
/* Entering the string whose position or index to be displayed */
puts("Enter the string to be searched: ");
gets(t);
/*Searching string t in string s */
found=strstr(s,t);
if(found)
printf("Second String is found in the First String at %d position.\n",found-s);
else
printf("-1");
getch();
}
Output:
Enter the first string:
sridhar siricilla
Enter the string to be searched:
siri
Second String is found in the First String at 8 position.
11a) Write C program to count the number of lines, words and characters in a given text.
#include<stdio.h>
int main()
{
// declare variables
char str[200];
int line, word, ch;
// initialize count variables with zero
line = word = ch = 0;
// read multiline string
printf("Enter string terminated with ~ :\n");
scanf("%[^~]", str);
// check every character
for(int i=0; str[i]!='\0'; i++)
{
// if it is new line then
// one line and one word completed
if(str[i]=='\n')
{
line++;
word++;
}
// else it is a character
else
{
// if character is space or tab
// then one word is also completed
if(str[i]==' '||str[i]=='\t')
{
word++;
ch++;
}
return 0;
}
Output:
b) Write a C program to find the sum of integer array elements using pointers.
#include <stdio.h>
#include <malloc.h>
void main(){
int i, n, sum = 0;
int *ptr;
printf("Enter size of array :
");
scanf("%d", &n);
");
", sum);
return 0;
Output
12
13
14
15
16
#include <stdio.h>
#include <conio.h>
struct student
int rl;
char nm[20];
int m1;
int m2;
int m3;
int t;
float per;
};
void main()
struct student a;
clrscr();
printf("rollno=%d\n", a.rl);
printf("Name=%sk\n", a.nm);
printf("m1=%d\n", a.m1);
printf("m2=%d\n", a.m2);
printf("m3=%d\n", a.m3);
printf("total=%d\n", a.t);
printf("per=%f\n", a.per);
getch();
rollno=12
Name=rama
m1=30
m2=40
m3=50
total=120
per=40.000000