0% found this document useful (0 votes)
21 views30 pages

C Programming Lab Manual Exercises

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views30 pages

C Programming Lab Manual Exercises

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

CHRIST COLLEGE OF ENGINEERING AND

TECHNOLOGY
(Approved by AICTE and Affiliated to Pondicherry University)
(An ISO 9001:2008 Certified Institution)
Pitchaveeranpet, Moolakulam, Oulgaret, Puducherry – 605 010

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

ESCP102 - Programming for Problem Solving Laboratory

LAB MANUAL

PONDICHERRY UNIVERSITY
PROGRAMMING FOR PROBLEM SOLVING LABORATORY

LIST OF EXERCISES

1. Familiarization with programming environment


2. Simple computational problems using arithmetic expressions
3. Problems involving if-then-else structures
4. Iterative problems e.g., sum of series
5. 1D Array manipulation
6. Matrix problems, String operations
7. Simple functions
8. Programming for solving Numerical methods problems
9. Recursive functions
10. Pointers and structures
11. File operations

EX. No. : 1 STUDY OF TURBO C


AIM
To study the TURBO C IDE, compile and execute a simple C program.

DESCRIPTION

The TURBO C development environment offers the following main menu commands.
 File
 Edit
 Search
 Run
 Compile
 Debug
 Project
 Options
 Windows
 Help
At the main menu, either press an arrow key to move to the desired option and then press enter key
or press the highlighted capital letters of the option. You can also press alt key and the first letter of
the option, which you desire to open.
FILE (ALT-F)
This menu offers choices for loading existing files, creating new files and saving files. This
menu contains New, Open, Save, Save as, Save all, Change dir, Print, Dos Shell and Quit.
File ->New: This option is used to create a new program.
File ->Open (F3): This option is used to open an existing files.
File ->Save (F2): This option is used to save the program.
File ->Save as: This option is used to save the program in another name.
File ->Change dir: This option is used to change the directory of existing folder to another
directory.
File ->Print: This option is used to print the existing programs.
File ->Dos shell: This option is used to come out from the c editor to dos shell. To return to
Turbo C, type “exit” and press enter and the DOS prompt.
File ->Quit: This option is used to exit from C editor.
EDIT: (ALT –E): This command takes you to the edit window. In this menu, it is used to modify
the programs. In this menu we can copy, cut and paste the programs.
SEARCH (ALT – S): This menu lets you to find particular part of the program, replace the
particular part of program and move to particular line number.
RUN (ALT-R): This menu lets you to compile, link and run our program and start and debugging
sessions.
RUN->RUN (CTRL+F9): This option is used to compile, link and run our program. If we compile
and link with the option debug source debugging on, your program will run in debug mode. This
command will stop execution at the first break point or it will run the program all the way through.
After compilation, to view the result press Alt-F5.
COMPILE (ALT-F9): This menu allows to invoke compile to obj, Make Exe file, Link Exe file,
etc., Alt-F9 is used to compile and create an object file. F9 command is used to build a execution
file.
DEBUG: This menu’s options let you look at and change variable values, go to the declaration of
any function in the source code and look at the call stack. Break/Watch option is used to insert,
remove and go breakpoint in your program and set delete and edit watch expressions.
PROJECT (ALT-P): This menu is used to define and manage project.
OPTIONS (ALT-O): This menu allows configuring the Turbo C Editor.
WINDOWS (ALT-W): This menu is used to Cascade all files, move programs and close all
programs.

STEPS FOR PROGRAM WRITING


1. Invoke Turbo C editor using Start→Run→c:tc\bin\tc
2. Type the source program.
3. Save the program using F2 command. (filename.c)
4. Compile and run the program using Alt – F9 and CTRL-F9.
5. To view the result use Alt – F5.

SAMPLE 1: Write a program to perform arithmetic operation.


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("Enter the two number :\n");
scanf("%d%d",&a,&b);
printf("\nAddition:%d",a+b);
printf("\nSubtraction:%d",a-b);
printf("\nMultiplication:%d",a*b);
printf("\nDivison:%d",a/b);
printf("\nModulus:%d",a%b);
getch();
}
OUTPUT
Enter the two number:
3
2
Addition:5
Subtraction:1
Multiplication:6
Divison:1
Modulus:1

RESULT

Thus, the options in the TURBO C IDE have been studied and a simple C program is
compiled and executed.
EX. NO: 2(A) AREA OF THE TRIANGLE

AIM
To write a C program to find the area of the triangle

ALGORITHM
STEP 1: Start the program
STEP 2: Read the 3 sides of the triangle as a, b and c
STEP 3: Compute value of s=(a+b+c)/2
STEP 4: Compute area using the formulae sqrt(s*(s-a)*(s-b)*(s-c))
STEP 5: Print the value of area
STEP 6: Stop the program

PROGRAM
#include<stdio.h>
#include<math.h>
void main()
{
float a,b,c;
float s,area;
clrscr();
printf("Enter size of each sides of triangle:");
scanf("%f%f%f", &a,&b,&c);
s = (a+b+c)/2;
area = sqrt(s*(s-a)*(s-b)*(s-c));
printf("Area of triangle is: %.3f",area);
getch();
}
OUTPUT

Enter size of each sides of triangle: 3


3
3
Area of triangle is: 3.897

RESULT
Thus, the area of the triangle was successfully executed.
EX. NO: 2(B) CALCULATE STUDENT PERCENTAGE

AIM
To write a C program to find the total and average percentage of students for 6 subjects

ALGORITHM
STEP 1: Start the program
STEP 2: Read the six subjects of marks English, Tamil, Maths, Social,
Science and Hindi
STEP 3: Calculate the total marks of the subjects
STEP 4: Calculate the average of 6 subjects, by dividing total by 6.
STEP 5: Print total and average
STEP 6: Stop the program

PROGRAM
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,d,e,f,t;
float avg;
clrscr();
printf("\n Enter the English marks :");
scanf("%d",&a);
printf("\n Enter the Tamil marks :");
scanf("%d",&b);
printf("\n Enter the Maths marks :");
scanf("%d",&c);
printf("\n Enter the Social marks :");
scanf("%d",&d);
printf("\n Enter the Science marks :");
scanf("%d",&e);
printf("\n Enter the Hindi marks:");
scanf("%d",&f);
t=a+b+c+d+e+f;
avg=(t/6);
printf("\nTOTAL MARKS=%d",t);
printf("\nPERCENTAGE MARKS=%f ",avg);
getch();
}
OUTPUT
Enter the English marks: 100
Enter the Tamil marks: 92
Enter the Maths marks: 95
Enter the Social marks : 92
Enter the Science marks: 98
Enter the Hindi marks: 98
TOTAL MARKS=575
PERCENTAGE MARKS=95.833 %

RESULT
Thus, the program to calculate the total and average of student of the given marks
EX. NO.: 3 FIND GREATEST OF THREE NUMBERS USING IF ELSE STATEMENT

AIM
To write a C program to find greatest of three numbers using if else statement

ALGORITHM

STEP 1: Start the program


STEP 2: Read the value of A, B, C as a Input
STEP 3: Check if A is greater than or equal to both B and C, A is the largest
number.
STEP 4: Check if B is greater than or equal to both A and C, B is the largest
number.
STEP 5: Check if C is greater than or equal to both A and B, C is the largest
number.
STEP 6: Stop the program

PROGRAM

// C program to find the maximum number out of the three


// given numbers using if-else statement

#include <stdio.h>
int main()
{
int A, B, C;

printf("Enter the numbers A, B and C: ");


scanf("%d %d %d", &A, &B, &C);

// finding max using compound expressions


if (A >= B && A >= C)
printf("%d is the largest number.", A);

else if (B >= A && B >= C)


printf("%d is the largest number.", B);

else
printf("%d is the largest number.", C);

return 0;
}
OUTPUT

Enter the numbers A, B and C: 56 78 30

78 is the largest number.

RESULT
Thus, the program to find greatest of three numbers using if else was successfully executed.
EX. NO.: 4 (A) SUM OF ‘n’ NUMBERS USING DO-WHILE
AIM
To write a C program to find sum of ‘n’ numbers using a do-while statement

ALGORITHM
STEP 1: Start the program
STEP 2: Get the value of ‘n’
STEP 3: Calculate the sum using sum=sum + n until the condition fails.
STEP 4: Print the value of sum
STEP 5: Stop the program
PROGRAM
#include<stdio.h>
#include<conio.h>
void main()
{
int n,sum=0;
clrscr();
printf("Enter n value:");
scanf("%d",&n);
do
{
sum=sum+n;
n=n-1;
}
while(n>0);
printf("sum of the given numbers are: %d",sum);
getch();
}

OUTPUT

Enter n value: 5
Sum of the given numbers are: 15

RESULT
Thus, the program to find sum of ‘n’ numbers using a do-while statement was successfully
executed.
EX. NO.: 4 (B) SUM OF ‘n’ NUMBERS USING FOR STATEMENTS
AIM
To write a C program to find sum of ‘n’ numbers using a for statement.

ALGORITHM
STEP 1: Start the program
STEP 2: Get the value of ‘n’
STEP 3: Calculate the sum using sum=sum + n until the condition fails.
STEP 4: Print the value of sum
STEP 5: Stop the program
PROGRAM
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,sum=0 ;
printf("Enter n value:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
sum =sum+i;
}
printf ("The sum of number upto %d is %d", n,sum);
getch();
}

OUTPUT

Enter n value: 10
Sum of the given numbers are: 55

RESULT
Thus, the program to find sum of ‘n’ numbers using a for statements was successfully
executed.
EX. NO.: 5 LARGEST AND SMALLEST ELEMENTS IN AN ARRAY
AIM
To write a C program to find the largest and smallest element in an array

ALGORITHM

STEP 1: Start the program


STEP 2: Read the size of array
STEP 3: Read the elements of the array
STEP 4: Take big= a[0] and compare it with a[1], and exchange the bigger element to big
STEP 5: Do this for all the array element using for loop and in the end, the bigger element
will be in big
STEP 6: Print big
STEP 7: Take small= a[0] and compare it with a[1], and exchange the smaller element to
small
STEP 8: Do this for all the array element using for loop and in the end, the smaller element
will be in small
STEP 9: Print small
STEP 10: Stop the program

PROGRAM

#include<stdio.h>
void main()
{
int a[50],size,i,big,small;
clrscr();
printf("\nEnter the size of the array: ");
scanf("%d",&size);
printf("\n\n Enter %d elements in to the array: ", size);
for(i=0;i<size;i++)
scanf("%d",&a[i]);
big=a[0];
for(i=1;i<size;i++)
{
if(big<a[i])
big=a[i];
}
printf("\n Largest elementis: %d",big);
small=a[0];
for(i=1;i<size;i++)
{
if(small>a[i])
small=a[i];
}
printf("\n Smallest elementis: %d",small);
getch();
}

OUTPUT
Enter the size of the array: 4
Enter 4 elements in to the array: 78
45
12
90
Largest element is: 90
Smallest element is: 12

RESULT
Thus, the c program to find the largest and smallest element in an array was successfully
executed.
EX. No.: 6 (A) MATRIX OPERATIONS-MULTIPLICATION

AIM

To write a C program to perform the matrix operation - Multiplication.

ALGORITHM

STEP 1: Start the program


STEP 2: Read the order of matrix m,n
STEP 3: Read the value of two matrices A,B
STEP 4: Set the loop i=0 to m and j=0 to N
STEP 5: Initialize the value c[i][j]=0
STEP 6: Set loop i=0 to M j=0 to N and k=0 to N
STEP 7: Calculate c[i][j]=c[i][j]+a[i][k]*b[k][j]
STEP 8: End loop
STEP 9: Print the value of c[i][j]
STEP 10: Stop the program
PROGRAM

/*** MATRIX OPERATIONS - MULTIPLICATION ***/

#include<stdio.h>

#include<conio.h>

void main()

int n,i,j,a[3][3],b[3][3],c[3][3],m,k;

clrscr();

printf("Enter the order of two Matrices");

scanf("%d %d",&m,&n);

printf("\n Enter the Matrix A");

for(i=0;i<m;i++)

for(j=0;j<n;j++)

scanf("%d",&a[i][j]);

printf("\n");

printf("\n Enter the Matrix B");


for(i=0;i<m;i++)

for(j=0;j<n;j++)

scanf("%d",&b[i][j]);

printf("\n");

printf("Matrix Multiplication\n");

for(i=0;i<m;i++)

for(j=0;j<n;j++)

c[i][j]=0;

for(k=0;k<n;k++)

c[i][j]=c[i][j]+a[i][k]*b[k][j];

printf("\t%d",c[i][j]);

printf("\n");

getch();

OUTPUT

Enter the order of two Matrices 3 3

Enter the Matrix A

111

111

111
Enter the Matrix B

222

222

222

Matrix Multiplication

6 6 6

6 6 6

6 6 6

RESULT

Thus the C program to perform the matrix operations was compiled and successfully executed.
EX. NO.: 6(B) STRING FUNCTIONS
AIM
To write a C program to perform various string handling functions are strlen, strcmp, strcat.
ALGORITHM
STEP 1: Start the program
STEP 2: Read the value of two string1 and string2
STEP 3: Compute and print string1and string2 length using the function strlen
STEP 4: Compare string1 with string2 whether they are similar or not using the
function
strcmp and print the result
STEP 5: Concatenate string1 and string2 using the function strcat
STEP 6: Stop the program
PROGRAM
#include <stdio.h>
#include <conio.h>
#include <string.h>
void main( )
{
char s1[20],s2[20];
int len1,len2 ;
clrscr( ) ;
printf("Enter String1 and string2:");
scanf("%s %s",s1,s2);
printf ( "\nString s1: %s", s1 ) ;
printf ( "\nString s2: %s", s2 ) ;
len1 = strlen ( s1 ) ;
printf ( "\n\n length of the string s1: %d", len1 ) ;
len2 = strlen ( s2 ) ;
printf ( "\n\n length of the string s2: %d", len2 ) ;
if ( strcmp ( s1, s2 ) == 0 )
printf ( "\n \n The strings s1 and s2 are similar" ) ;
else
printf ( "\n\n The strings s1 and s2 are not similar" ) ;
strcat ( s1, s2 ) ;
printf ( "\n\n String s1 after concatenation: %s", s1 ) ;
getch( ) ;
}
OUTPUT
Enter String1 and string2: Engineering College
String s1: Engineering
String s2: College
length of the string s1: 11
length of the string s2: 7
The strings s1 and s2 are not similar
String s3 after concatenation: Engineering College

RESULT
Thus, the c program to perform string function was executed successfully
EX. NO.: 7 FACTORIAL USING FUNCTIONS
AIM
To write a C program to find the factorial of a given number using functions

ALGORITHM

STEP 1: Start the program


STEP 2: Declare the function findFactorial with argument int
STEP 3: Get the range of n up to which factorial has to be calculated
STEP 4: Initialize f=1 and compute f=f*i, up to n , in the function findFactorial
STEP 5: Print the value of factorial
STEP 6: Stop the program

PROGRAM
#include<stdio.h>
int findFactorial(int);
void main()
{
int i,factorial,num;
clrscr();
printf("Enter a number: ");
scanf("%d",&num);
factorial = findFactorial(num);
printf("Factorial of %d is: %d",num,factorial);
getch();
}

int findFactorial(int num)


{
int i,f=1;
for(i=1;i<=num;i++)
f=f*i;
return f;
}

OUTPUT
Enter a number: 5
Factorial of 5 is: 120

RESULT

Thus the program to find the factorial of a given number using functions was executed
successfully.
EX. NO.: 8 SECANT METHOD IN NUMERICAL PROBLEM SOLVING
AIM
To write a C program to Secant Method using Numerical Problem Solving

ALGORITHM

STEP 1: Start the program


STEP 2: Get values of x0, x1 and e
*Here x0 and x1 are the two initial guesses
e is the stopping criteria, absolute error or the desired degree of
accuracy*
STEP 3: Compute f(x0) and f(x1)
STEP 4: Compute x2 = [x0*f(x1) – x1*f(x0)] / [f(x1) – f(x0)]
STEP 5: Test for accuracy of x2
If [ (x2 – x1)/x2 ] > e, *Here [ ] is used as modulus sign*
then assign x0 = x1 and x1 = x2
goto step 4
else,
goto step 6
STEP 6: Display the required root as x2.
STEP 7: Stop the program

PROGRAM
#include<stdio.h>
float f(float x)
{
return(x*x*x-4); // f(x)= x^3-4
}
float main()
{
float a,b,c,d,e;
int count=1,n;
printf("\n\nEnter the values of a and b:\n"); //(a,b) must contain the solution.
scanf("%f%f",&a,&b);
printf("Enter the values of allowed error and maximun number of iterations:\n");
scanf("%f %d",&e,&n);
do
{
if(f(a)==f(b))
{
printf("\nSolution cannot be found as the values of a and b are same.\n");
return;
}
c=(a*f(b)-b*f(a))/(f(b)-f(a));
a=b;
b=c;
printf("Iteration No-%d x=%f\n",count,c);
count++;
if(count==n)
{
break;
}
} while(fabs(f(c))>e);
printf("\n The required solution is %f\n",c);
}

OUTPUT

Enter the values of a and b:


5
6
Enter the values of allowed error and maximun number of iterations:
4
3
Iteration No-1 x=3.670330
Iteration No-2 x=3.034687

The required solution is 3.034687

RESULT

Thus, the program to calculate Secant Method using Numerical Problem Solving was executed
successfully.
EX. NO.: 9 FIBONACCI USING RECURSIVE FUNCTIONS
AIM
To write a C program to find the Fibonacci of a given number using Recursive functions

ALGORITHM

STEP 1: Start the program


STEP 2: Declare the function printFibonacci with argument int
STEP 3: Get the range of n up to which Fibonacci has to be calculated
STEP 4: Initialize n1=0,n2=1,n3 and check the condition using if state when n>0,
if its true print the value of Fibonacci number
STEP 5: Stop the program

PROGRAM
#include<stdio.h>
void printFibonacci(int n){
static int n1=0,n2=1,n3;
if(n>0){
n3 = n1 + n2;
n1 = n2;
n2 = n3;
printf("%d ",n3);
printFibonacci(n-1);
}
}
int main(){
int n;
printf("Enter the number of elements: ");
scanf("%d",&n);
printf("Fibonacci Series: ");
printf("%d %d ",0,1);
printFibonacci(n-2); //n-2 because 2 numbers are already printed
return 0;
}
OUTPUT

Enter the number of elements: 10


Fibonacci Series: 0 1 1 2 3 5 8 13 21 34

RESULT

Thus, the program to find the Fibonacci of a given number using Recursive functions was
executed successfully.

EX. NO.: 10(A) SWAPPING OF TWO NUMBERS USING POINTERS

AIM
To write a C program to swap two numbers by using call by reference method
ALGORITHM
STEP 1: Start the program
STEP 2: Get two numbers in i and j
STEP 3: Using pointer,
swap t=*a;
*a=*b;
*b=t;
STEP 4: Print the swapped values i and j
STEP 5: Stop the program
PROGRAM
#include<stdio.h>
#include<conio.h>
void swap(int *a,int*b);
void main()
{
int i, j;
clrscr();
printf(" Enter the First Number in A : ");
scanf("%d",&i);
printf("\nEnter the Second Number in B : ");
scanf("%d",&j);
swap(&i,&j); /* call by reference*/
printf("\n A = %d",i);
printf("\n B = %d",j);
getch();
}

/* call by reference*/
void swap(int *a, int *b)
{
int t;
t=*a;
*a=*b;
*b=t;
}

OUTPUT
Enter the First Number in A: 100
Enter the Second Number in B: 99
A = 99
B = 100

RESULT
Thus, the program to swap two numbers by using call by value reference was executed
successfully.
EX. NO.: 10(B) STUDENT DETAILS USING STRUCTURES
AIM
To write a C program to create student details using structures
ALGORITHM
STEP 1: Start the program
STEP 2: Declare the structure ‘student’ with roll no, name and total mark, up to 100
students using array
STEP 3: Read the number of student details to be obtained in ‘n’
STEP 4: Read the student roll no, name and total mark till ‘n’
STEP 5: Print the student roll no, name and total mark till ‘n’
STEP 6: Stop the program
PROGRAM
#include <stdio.h>
#include <conio.h>
void main()
{
struct student
{
int rollno;
char name[25];
int totalmark;
}stud[100];
int n,i;
clrscr();
printf("Enter total number of students\n\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter details of No.%d student\n",i+1);
printf("Name:\n");
scanf("%s",&stud[i].name);
printf("Roll number:\n");
scanf("%d",&stud[i].rollno);
printf("Total mark:\n");
scanf("%d",&stud[i].totalmark);
}
printf("STUDENTS DETAILS:\n");
printf(“********************\n\n”);
for(i=0;i<n;i++)
{
printf("\nRoll number:%d",stud[i].rollno);
printf("\nName:%s",stud[i].name);
printf("\nTotel mark:%d",stud[i].totalmark);
printf(“\n*********************”);
}
getch();
}
OUTPUT
Enter total number of students: 2
Enter details of No.1 student
Name:Dev
Roll number:1
Total mark:489
Enter details of No.2 student
Name:Raj
Roll number:2
Total mark:390
STUDENTS DETAILS:
********************
Roll number:1
Name:Dev
Totel mark:489
********************
Roll number:2
Name:Raj
Total mark:390
********************
RESULT
Thus the c program to create student details using structures was successfully executed.

EX. NO.:11 CREATING AND DISPLAY THE CONTENT OF THE FILE


AIM
To create a file by getting the input from the keyboard and retrieve the contents of the file
using file operation commands.
ALGORITHM
STEP 1: Start the program
STEP 2: Declare the FILE *f1
STEP 3: Open the file in the write mode
STEP 4: Read the character one by one from the keyboard using getchar() function
STEP 5: Store the content in the file Input
STEP 6: Close the file using fclose() function
STEP 7: Reopen the file in the read mode
STEP 8: Display the content from the file
STEP 9: Close the file using fclose() function
STEP 10: Stop the program
PROGRAM
#include<stdio.h >
#include<conio.h>
void main()
{
FILE *f1;
char c;
clrscr();
printf(“Data Input”);
f1=fopen(“INPUT”,”w”); /*Open the file Input*/
while((c=getchar())!=EOF) /*get a character from key board*/
putc(c,f1); /*write a character to input*/
fclose(f1); /*close the file input*/
printf(“\nData Output\n”);
f1=fopen(“INPUT”,”r”); /*Reopen the file input*/
while((c=getc(f1))!=EOF)
printf(“%c”,c);
fclose(f1);
}

OUTPUT
Data Input
Hello world
^Z
Data Output
Hello world

RESULT
Thus the program is getting the input from the keyboard and retrieve the contents of the file
using file operation.

You might also like