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

C Student-manual With output (1)

The document is a master manual for the course 'Problem Solving and C Programming' for the Department of Computer Science and Engineering at NPR College of Engineering and Technology. It outlines the course objectives, list of experiments, program outcomes, and includes various C programming exercises with algorithms and sample outputs. The manual emphasizes developing programming skills using C constructs, arrays, strings, and file processing, aiming to produce competent technical professionals.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

C Student-manual With output (1)

The document is a master manual for the course 'Problem Solving and C Programming' for the Department of Computer Science and Engineering at NPR College of Engineering and Technology. It outlines the course objectives, list of experiments, program outcomes, and includes various C programming exercises with algorithms and sample outputs. The manual emphasizes developing programming skills using C constructs, arrays, strings, and file processing, aiming to produce competent technical professionals.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

DEPARTMENT OF COMPUTER SCIENCE AND

ENGINEERING

23GE101 PROBLEM SOLVING AND C


PROGRAMMING
Semester I

Master Manual
Regulation 2023

NAME : …………………………………………………

REGISTER NUMBER : …………………………………………………

DEPARTMENT : …………………………………………………

YEAR & SEM : …………………………………………………

SUBJECT : ………………………………………………….
NPR COLLEGE OF ENGINEERING AND TECHNOLOGY
Natham, Dindigul -624 401

Name : ………………………………………………………………………………

Year : ………………. …Semester …………………Branch ..…………………….

University Register No.

CERTIFIED that this Bonafide Record work done by the above

Student in the ......................................................................................................... Laboratory


during the year 20 - 20

Signature of Lab. In-charge Signature of Head of the Department

Submitted for practical examination held on ………………………………………..

Internal Examiner External Examiner


TABLE OF CONTENTS
S. Page
Particulars
No. No.
1. College vision and mission statement 4
2. Department Vision, Mission, POs, PEOs, PSOs 5
3. Lab syllabus 6
4. List of Experiments Mapping with COs, POs &PSOs 7
5. Prescribed lab experiments
1. I/O statements, operators, expressions:
a) For a given product with a VAT OF 7%, find the VAT amount 9
and the total value of the product.
b) C program to find area and perimeter of Circle 11
2. Programs Using Decision-Making Constructs:
12
a) C program to Find the Eligibility of a Person to Vote or Not?
b) C program to find the Largest Numbers Among Three Numbers 13
c) C program to find whether the given year is leap year or not 14
d) C program to design a calculator to perform the operations,
namely, addition, subtraction, multiplication, division and square of 15
a number.
3. Loops: For, While, Do-While 17
4. Arrays: 1D and 2D, Multi-dimensional arrays, traversal :
19
a) Sort the numbers based on the weight
b) Average height of persons 21
c) Body mass index of the individuals 22
5. String Operations:
24
a) Reverse of a given string
b) String operations 26
6. Functions: call, return, passing parameters by (value, reference),
passing arrays to function: 29
Sorting using pass by reference
7. Recursion
30
Towers of HANOI using recursion
8.a) Generate salary slip of employees using structures and pointers 31
b) Internal marks of students 33
9. Telephone directory 35
10. Banking application 39
NPR College of Engineering & Technology, Natham.

VISION
 To develop students with intellectual curiosity and technical expertise to meet the global
needs.
MISSION
 To achieve academic excellence by offering quality technical education using best
teaching techniques.
 To improve Industry – Institute interactions and expose industrial atmosphere.
 To develop interpersonal skills along with value based education in a dynamic
learning environment.
 To explore solutions for real time problems in the society.
NPR College of Engineering & Technology, Natham.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VISION
 To produce globally competent technical professionals for digitized society.

MISSION
 To establish conducive academic environment by imparting quality education and value
added training.
 To encourage students to develop innovative projects to optimally resolve the challenging
social problems.

PROGRAM EDUCATIONAL OBJECTIVES

Graduates of Computer Science and Engineering Program will be able to:

 Develop into the most knowledgeable professional to pursue higher education and Research or
have a successful carrier in industries.
 Successfully carry forward domain knowledge in computing and allied areas to solve complex
and real world engineering problems.
 Meet the technological revolution they are continuously upgraded with the technical
knowledge.
 Serve the humanity with social responsibility combined with ethics.
23GE101 PROBLEM SOLVING AND C PROGRAMMING LTPC
0 03 2
OBJECTIVES:
The student should be made to:
 To familiarize with C programming constructs.
 To develop programs in C using basic constructs.
 To develop programs in C using arrays
 To develop applications in C using strings, pointers, functions.
 To develop applications in C using structures.
 To develop applications in C using file processing.

LIST OF EXPERIMENTS
1. I/O statements, operators, expressions
2. Programs Using Decision-Making
3. Loops: For, While, Do-While
4. Arrays: 1D and 2D, Multi-dimensional arrays, traversal :
5. String Operations:
6. Functions: call, return, passing parameters by (value, reference), passing arrays to function:
7. Recursion
8. Pointers: Pointers to functions, Arrays,Strings, Pointers to Pointers, Array of Pointers
9. Structures: Nested Structures, Pointers to Structures, Arrays of Structures and Unions.
10. Files: reading and writing, File pointers, file operations, random access, processor directives

TOTAL: 30 PERIODS
OUTCOMES:
At the end of the course, the student will be able to
 Demonstrate knowledge on C programming constructs
 Develop programs in C using basic constructs.
 Develop programs in C using arrays.
 Develop applications in C using strings, pointers, functions.
 Develop applications in C using structures.
 Develop applications in C using file processing.
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

23GE101 PROBLEM SOLVING AND C PROGRAMMING

Course Outcomes

After completion of the course, Students are able to learn the listed Course Outcomes.

Knowledge
COs Course Outcomes
Level

CO1 Demonstrate knowledge on C programming constructs K2

CO2 Develop programs in C using basic constructs K3

CO3 Develop programs in C using arrays. K3

CO4 Develop applications in C using strings, pointers, functions K3

CO5 Develop applications in C using structures. K2

CO6 Develop applications in C using file processing. K3

List of Experiments with COs, POs and PSOs

Exp.
Name of the Experiment COs POs PSOs
No.

1. I/O statements, operators, expressions CO1 1,2,3,9& 11 1,2


2. Programs Using Decision-Making CO2 1,2,3,4,9& 11 1,2
3. Loops: For, While, Do-While CO2 1,2,3,4,9& 11 1,2
Arrays: 1D and 2D, Multi-dimensional arrays, traversal
4. CO3 1,2,3,6,9&12 1,2
5. String Operations: CO4 1,2,3,4,6,9&11 1,2
Functions: call, return, passing parameters by (value,
6. CO4 1,2,3,4,6,9&11 1,2
reference), passing arrays to function:
7. Recursion CO4 1,2,3,4,6,9&11 1,2
Pointers: Pointers to functions, Arrays,Strings, Pointers
8. CO3,CO4 1,2,3,4,6,9&11 1,2
to Pointers, Array of Pointers
Structures: Nested Structures, Pointers to Structures,
9. Arrays of Structures and Unions. CO5 1,2,3,4,6,9&11 1,2
Files: reading and writing, File pointers, file operations,
10. random access, processor directives CO6 1,2,3,4,6,9&11 1,2
Program Outcomes

1. Engineering Knowledge 7. Environment and Sustainability


2. Problem Analysis 8. Ethics
3. Design/Development of Solutions 9. Individual and Team Work
4. Conduct Investigations of Complex Problems 10. Communication
5. Modern Tool Usage 11. Project Management and Finance
6. The Engineer and Society 12. Life-long Learning

Program Specific Outcomes

At the end of the program students will be able to


1. Deal with real time problems by understanding the evolutionary changes in computing, applying
standard practices and strategies in software project development using open-ended
programming environments.
2. Employ modern computer languages, environments and platforms in creating innovative career
paths by inculcating moral values and ethics.
3. Achieve additional expertise through add-on and certificate programs.
Ex. No : 1(a) FOR A GIVEN PRODUCT WITH A VAT OF 7%, FIND THE
VAT AMOUNT AND THE TOTAL VALUE OF THE
Date : PRODUCT.

AIM:

To find the VAT amount and the total value of the product.

ALGORITHMS:
Step 1: Start the program.
Step 2: Read the item Details.
Step 3: Read discount and tax % details.
Step 4: Calculate amount->qty x value.
Step5: Calculate discount->(amount x discount)/100.
Step 6: Calculate taxamt->(subtot x tax)100
Step 7: Calculate totamt->(subtot + taxamt)
Step 8: Print all details
Step 9: Stop the Program

PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
float totamt, amount,subtot,disamt,taxamt,quantity,value,discount,tax;
clrscr();
printf("\n Enter the quantity of item sold:");
scanf("%f",&quantity);
printf("\n Enter the value of item:");
scanf("%f",&value);
printf("\n Enter the Discount percentage:");
Scanf("%f",&discount);
printf("\n Enter the tax:");
scanf("%f",&tax); amount=quantity * value;
disamt=(amount*discount)/100.0;
subtot=amount-disamt;
taxamt=(subtot*tax)/100.0;
totamt=subtot+taxamt;
printf("\n\n\n ******BILL****** ");
printf("\nQuantitysold: %f", quantity);
printf("\npriceperitem: %f", value);
printf("\nAmount: %f", amount);
printf(" \n Discount: %f", disamt) ;
printf("\n Discounted Total: %f", subtot) ;
printf("\n Tax:= %f", taxamt);
printf("\n Total Amount %f", totamt);
getch();
}
OUTPUT:

Enter the quantity of item sold: 5


Enter the value of item: 100
Enter the Discount percentage: 10
Enter the tax percentage: 18

RESULT:

Thus the program for a given product with a VAT OF 7% to find the VAT Amount and the total value
of the product was executed and the output was verified.
Ex. No : 1(b)
C PROGRAM TO FIND AREA AND PERIMETER OF
Date : CIRCLE

AIM:
To write a C Program to find area and perimeter of Circle.

ALGORITHM:

Step1: Start the program.


Step2: Read radius.
Step3: Area P1 * Radius * Radius , PI=3.14
Step4: .Perimeter 2 * PI * Radius
Step5: Print area, Perimeter
Step6: Stop.

PROGRAM:
#include<stdio.h>
#include<conio.h>
#define pi 3.14
void main()
{
float r,area,perimeter;
clrscr();
printf("\n Enter r value:");
scanf("%f",&r);
area=pi*r*r;
printf(" area%f:",area);
perimeter=2*pi*r;
printf("perimeter%f:",perimeter);
getch();
}

OUTPUT:
Enter radius value: 5

Area: 78.50
Perimeter: 31.40

RESULT:
Thus the program to find area and perimeter of Circle was executed and the output was verified.
Ex. No : 2(a)
C PROGRAM TO FIND THE ELIGIBILITY OF A PERSON
Date : TO VOTE OR NOT?
AIM:
To Write a C Program to find the eligibility of a Person to Vote or not?

ALGORITHM:
Step1: Start the program.
Step2: Read name, age.
Step3: IF age>=18 print “Eligible”.
Step4: ELSE print “Not Eligible”.
Step5: ENDIF.
Step6: Stop the Program.

PROGRAM:

#include<stdio.h>
#include<conio.h>
void main()
{
int age;
char name[50]; // or *name clrscr();
printf("\n Type the Name of the candidate: "); gets(name);
printf("\n Enter The Age : "); scanf("%d",&age); if(age>=18)
printf("\n %s is Eligible for Vote",name);
else
printf("\n %s is Not Eligible for Vote",name);
getch();
}

OUTPUT:
Type the Name of the candidate: Arun Kumar

Enter The Age: 20

Arun Kumar is Eligible for Vote

RESULT:
Thus the program to find the eligibility of a Person to Vote or not was executed and the output
was verified.
Ex. No : 2(b)
C PROGRAM TO FIND THE LARGEST NUMBERS AMONG
Date : THREE NUMBERS.

AIM:
To Write a C Program to find the Largest Numbers among Three Numbers.

ALGORITHM:
Step1: Start the program.
Step2: Read a, b, c.
Step3: IF (a>b and a>c) big = a.
Step 4: ELSEIF (b>a and b>c) big =b.
Step5: ELSE big = c.
Step6: ENDIF.
Step7: print big.
Step8: Stop the Program.
PROGRAM:
#include <stdio.h>
#include<conio.h>
int main()
{
int a,b,c;
int big;
clrscr();
printf("Enter three numbers:");
scanf("%d%d%d",&a,&b,&c);
if(a>b && a>c)
big=a;
else if(b>a && b>c)
big=b;
else
big=c;
printf("Largest number is = %d",big);
return 0;
getch();
}

OUTPUT:
Enter three numbers: 10 25 30
Largest number is = 30

RESULT:
Thus the program to find the Largest Numbers among Three Numbers was executed and the
output was verified.
Ex. No: 2(c) WRITE A PROGRAM TO FIND WHETHER THE
GIVEN YEAR IS LEAP YEAR OR NOT.
Date :
AIM:
To Write a program to find whether the given year is leap year or not.

ALGORITHM:
Step1: Start the program.
Step2: Read Year.
Step3: IF Year%4=0.
IF Year%100=0.
IF Year%400=0.
Print “Leap Year”.
ELSE Print “Not Leap Year.
ELSE Print “Leap Year”.
Step4: Print “Not Leap Year”.
Step5: Stop.
PROGRAM:
#include <stdio.h>
#include<conio.h>
void main()
{
int year;
clrscr();
printf("Enter a year: ");
scanf("%d",&year);
if(year%4 == 0)
{
if( year%100 == 0)
{
if ( year%400 == 0)
printf("%d is a leap year.", year);
else
printf("%d is not a leap year.", year);
}
else
printf("%d is a leap year.", year );
}
else
printf("%d is not a leap year.", year);
getch();
}
OUTPUT:

Enter a year: 2024

2024 is a leap year.

RESULT:

Thus the program to find whether the given year is leap year or not was executed and the output
was verified.
Ex. No : 2(d) DESIGN A CALCULATOR TO PERFORM THE
Date : OPERATIONS, NAMELY, ADDITION,
SUBTRACTION, MULTIPLICATION,

AIM:
Design a calculator to perform the operation, namely, addition, subtraction, multiplication,
division and square of a number.

ALGORITHM:
Step1: Start the program.
Step2: Read a, b, c.
Step3: Print menu
Step4: Read choice
Step5: Choice 1 then add
Choice 2 then Subtract
Choice 3 then multiply
Choice 4 then Divide
Choice 5 then Square
Print result
Step6: stop

PROGRAM:
#include <stdio.h>
#include <math.h>
int main() {
char operator;
double num1, num2, result;

// Get user choice


printf("1.add,2.subtract,3.multiply,4.divide,5.square");
printf("\n Enter the choice;");
scanf("%d",&ch);
switch(ch)
{ case 1:
result = num1 + num2;
printf("Result: %.2lf\n", result);
break;
case 2:
result = num1 - num2;
printf("Result: %.2lf\n", result);
break;
case 3:
result = num1 * num2;
printf("Result: %.2lf\n", result);
break;
case 4:
if (num2 != 0) {
result = num1 / num2;
printf("Result: %.2lf\n", result);
} else {
printf("Error: Division by zero!\n");
}
break;
case 6:
result = num1*num1;
printf("Result: %.2lf\n", result);
break;
default:
printf("Error: Invalid Choice!\n");
break;
}

return 0;
}

OUTPUT:

1. Add, 2. Subtract, 3. Multiply, 4. Divide, 5. Square


Enter the choice: 1
Enter the first number: 10
Enter the second number: 5
Result: 15.00

1. Add, 2. Subtract, 3. Multiply, 4. Divide, 5. Square


Enter the choice: 5
Enter the first number: 4
Result: 16.00

RESULT:

Thus the program to Design a calculator to perform the operation, namely, addition,
subtraction, multiplication, division and square of a number was executed and the output was
verified.
Ex. No : 3
LOOPS: FOR, WHILE, DO-WHILE
Date:

AIM:
To write a C Program to print positive integers from 1 to 10.

ALGORITHM:
Step1: Start
Step2: Declare variables
Step3: Read the Input number.
Step4: Sort the positive integers from the given number .
Step5: Match the result with input number.
Step6: Print the positive numbers.
Step7: Stop

PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<math.h>
//Using FOR LOOP
void main()
{
int i; for(i=1; i<=10;i++)
printf(“%d \n”, i);
getch();
}
//Using WHILE LOOP
void main()
{
int i=1;
while(i<=10)
{
printf(“%d \n”, i);
}
i++;
getch();
}
//Using DO-WHILE LOOP
void main()
{
int i=1;
do
{
printf(“%d \n”, i); i++; }
while(i<=10);
getch();
}

OUTPUT:
Using FOR LOOP:
1
2
3
4
5
6
7
8
9
10

Using WHILE LOOP:


1
2
3
4
5
6
7
8
9
10

Using DO-WHILE LOOP:


1
2
3
4
5
6
7
8
9
10

RESULT:
Thus a C program to print positive integers from 1 to 10 was executed and the output was
obtained.
Ex. No : 4A
SORT THE NUMBERS BASED ON THE
Date: WEIGHT

AIM:
To write a C Program to perform the following: Given a set of numbers like <10, 36, 54,
89, 12, 27>, find sum of weights based on the following conditions
• 5 if it is a perfect cube
• 4 if it is a multiple of 4 and divisible by 6
• 3 if it is a prime number
Sort the numbers based on the weight in the increasing order as shown below <10,its weight>,
<36,its weight> , <89,its weight>.

ALGORITHM:
Step1: Start
Step2: Declare variables
Step3: Read the number of elements .
Step4: Get the individual elements.
Step 5: Calculate the weight for each element by the conditions
5 if it is a perfect cube (pow)
4 if it is a multiple of 4 and divisible by 6 (modulus operator)
3 if it is a prime number(modulus operator)
Step6: Display the output of the weight calculations after sorting .
Step7: Stop

PROGRAM:
#include <stdio.h>
#include<conio.h>
#include <math.h>
void main()
{
int nArray[50],wArray[50],nelem,i,j,t;
clrscr();
printf("\nEnter the number of elements in an array : ");
scanf("%d",&nelem);
printf("\nEnter %d elements\n",nelem);
for(i=0;i<nelem;i++)
scanf("%d",&nArray[i]);
//Calculate the weight
for(i=0; i<nelem; i++)
{
wArray[i] = 0;
if(percube(nArray[i])) wArray[i] = wArray[i] + 5;
if(nArray[i]%4==0 && nArray[i]%6==0)
wArray[i] = wArray[i] + 4;
if(prime(nArray[i]))
wArray[i] = wArray[i] + 3;
}
// Sorting an array
for(i=0;i<nelem;i++)
for(j=i+1;j<nelem;j++)
if(wArray[i] > wArray[j])
{
t = wArray[i];
wArray[i] = wArray[j];
wArray[j] = t;
}
for(i=0; i<nelem; i++)
printf("<%d,%d>\n", nArray[i],wArray[i]);
getch();
}
int prime(int num)
{
int flag=1,i;
for(i=2;i<=num/2;
i++
if(num%i==0)
{
flag=0;
break;
}
return flag;
}
int percube(int num)
{
int i,flag=0;
for(i=2;i<=num/2;
i++
if((i*i*i)==num)
{
flag=1;
break;
}
return flag;
}
OUTPUT:
Enter the number of elements in an array: 5
Enter 5 elements
12 4 6 7 8

<7, 0>
<4, 7>
<6, 7>
<8, 7>
<12, 9>

RESULT:

Thus a C Program for Sort the numbers based on the weight was executed and the output was
obtained.
Ex. No : 4B
AVERAGE HEIGHT OF PERSONS
Date:

AIM:
To write a C Program to populate an array with height of persons and find how many persons
are above the average height.

ALGORITHM:
Step1: Start
Step2:Declare variables
Step3:Read the total number of persons and their height.
Step4:Calculate avg=sum/n and find number of persons their h>avg.
Step5:Display the output of the calculations .
Step6:Stop

PROGRAM:
#include <stdio.h>
#include <conio.h>
void main()
{
int i,n,sum=0,count=0,height[100];
float avg;
clrscr();
printf("Enter the Number of Persons : ");
scanf("%d",&n);
printf("\n Enter the Height of each person in centimeter\n");
for(i=0;i<n;i++)
{
scanf("%d",&height[i]); sum = sum + height[i];
}
avg = (float)sum/n;
for(i=0;i<n;i++)
if(height[i]>avg)
count++;
printf("\n Average Height of %d persons is : %.2f\n",n,avg);
printf("\n The number of persons above average : %d ",count);
getch();
}
OUTPUT:
Enter the Number of Persons: 5

Enter the Height of each person in centimeters:


150
160
170
180
190

Average Height of 5 persons is: 170.00 cm

The number of persons above average height: 2

RESULT:
Thus a C Program average height of persons was executed and the output was obtained.
Ex. No : 4C
BODY MASS INDEX OF THE
Date : INDIVIDUALS

AIM:
To write a C Program to Populate a two dimensional array with height and weight of persons and
compute the Body Mass Index of the individuals

ALGORITHM:
Step1: Start
Step2: Declare variables
Step3: Read the number of persons and their height and weight.
Step4: Calculate BMI=W/H2for each person
Step5: Display the output of the BMI for each person.
Step6: Stop

PROGRAM:
#include <stdio.h>
#include <conio.h>
void main()
{
int stu[100][2];`
int index[100];
int i,n;
float h;
clrscr();
printf("Enter the number of students : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the Height(cm) and Weight(kg) of student %d :",i+1);
scanf("%d%d",&stu[i][0],&stu[i][1]);
h = (float)(stu[i][0]/100.0);
index[i] = (float)stu[i][1]/(float)(h*h);
}
printf("\nStu.No.\tHeight\tWeight\tBMI\tResult\n");
for(i=0;i<n;i++)
{
printf("\n%d\t%d\t%d\t%d\t",i+1,stu[i][0],stu[i][1],index[i]);
if(index[i]<15)
printf("Starvation\n");
else if(index[i]>14 && index[i] < 18)
printf("Underweight\n");
else if(index[i] > 17 && index[i] < 26)
printf("Healthy\n");
else if(index[i] > 25 && index[i] < 31 printf("Over weight\n");
else if(index[i] > 30 && index[i] < 36)
printf("Obese\n");
else
printf("Severe Obese\n");
}
getch();
}

OUTPUT:

Enter the number of students: 3


Enter the Height(cm) and Weight(kg) of student 1: 160 50
Enter the Height(cm) and Weight(kg) of student 2: 170 80
Enter the Height(cm) and Weight(kg) of student 3: 180 100

Stu.No. Height Weight BMI Result


1 160 50 19.53 Healthy
2 170 80 27.68 Overweight
3 180 100 30.86 Obese

RESULT:

Thus a C Program Body Mass Index of the individuals was executed and the output was
obtained.
Ex. No : 5A
REVERSE OF A GIVEN STRING
Date :

AIM:
To write a C Program to perform reverse without changing the position of special
characters for the given string.

ALGORITHM:
Step1: Start
Step2:Declare variables .
Step3:Read a String.
Step4:Check each character of string for alphabets or a special character by using isAlpha() .
Step5:Change the position of a character vice versa if it is alphabet otherwise remains same.
Step6:Repeat step 4 until reach to the mid of the position of a string.
Step7:Display the output of the reverse string without changing the position of special characters .
Step8:Stop

PROGRAM:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
// Function to check if a character is a special character
int isSpecialCharacter(char c)
{
return !(isalnum(c) || c == ' ');
}
// Function to perform the reverse without changing the position of special characters
void reverseStringWithoutChangingSpecial(char str[]) {
int left = 0;
int right = strlen(str) - 1;

while (left < right) {


if (!isSpecialCharacter(str[left])) {
if (!isSpecialCharacter(str[right])) {
// Swap non-special characters
char temp = str[left];
str[left] = str[right];
str[right] = temp;

// Move pointers
left++;
right--;
} else {
// Move the right pointer if it points to a special character
right--;
}
} else {
// Move the left pointer if it points to a special character
left++;
}
}
}

int main() {
char inputString[100];

// Input string from the user


printf("Enter a string: ");
fgets(inputString, sizeof(inputString), stdin);

// Remove the newline character if present


if (inputString[strlen(inputString) - 1] == '\n') {
inputString[strlen(inputString) - 1] = '\0';
}

// Call the function to reverse the string without changing the position of special characters
reverseStringWithoutChangingSpecial(inputString);

// Output the reversed string


printf("Reversed String: %s\n", inputString);

return 0;
}

OUTPUT:

Enter a string: a,bC dEf!

Reversed String: f,E dCb a!

RESULT:
Thus a c program of given string was executed and output was obtained.
Ex. No : 5B
STRING OPERATIONS
Date :

AIM:
To write a C Program to perform string operations on a given paragraph for the following
using built-in functions:
a. Find the total number of words.
b. Capitalize the first word of each sentence.
c. Replace a given word with another word.

ALGORITHM:
Step1: Start
Step2: Declare variables
Step3: Read the text.
Step4: Display the menu options
Step5: Compare each character with tab char „\t‟ or space char „ „ to count no of words
Step6: Find the first word of each sentence to capitalize by checks to see if a Step7: character is a
punctuation mark used to denote the end of a sentence.
Step8: Replace the word in the text by user specific word if match.
Step9: Display the output of the calculations.
Step10: Repeat the step 4 till choose the option stop.
Step11: Stop

PROGRAM:
A) Counting of words:
#include<stdio.h>
#include<conio.h>
#define MAX_SIZE 100
void main()
{
char str[MAX_SIZE];
char prevChar;
int i, words;
clrscr();
printf("\nEnter any string: ");
gets(str);
i = 0;
words = 0;
prevChar = '\0';
while(1)
{
if(str[i]==' ' || str[i]=='\n' || str[i]=='\t' || str[i]=='\0')
{
if(prevChar != ' ' && prevChar != '\n' && prevChar != '\t' && prevChar != '\0')
{
words++;
}
}
prevChar = str[i];
if(str[i] == '\0') break;
else
i++;
}
printf("Total number of words = %d", words);
getch();
}

OUTPUT:
Enter any string: Hello world! This is a test.
Total number of words = 6

b. Capitalize the first word of each sentence.

#include <stdio.h>
#include <ctype.h>

void capitalizeFirstWord(char *str)


{
int i = 0;
int capitalize = 1;
while (str[i] != '\0') {
if (str[i] == '.' || str[i] == '?' || str[i] == '!')
{
capitalize = 1;
}
else if (isalpha(str[i]) && capitalize)
{
str[i] = toupper(str[i]);
capitalize = 0;
}
i++;
}
}

int main() {
char str[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
capitalizeFirstWord(str);
printf("Capitalized string: %s", str);
return 0;
}
OUTPUT:

Enter a string: hello world. how are you? i am fine!

Capitalized string: Hello world. How are you? I am fine!

C.Replace a given word with another word


#include <stdio.h>
#include <string.h>

void replaceWord(char *str, const char *oldWord, const char *newWord)


{
char *pos, temp[1000];
int index = 0;
int oldWordLength = strlen(oldWord);

while ((pos = strstr(str, oldWord)) != NULL)


{
strncpy(temp, str, pos - str);
temp[pos - str] = '\0';
strcat(temp, newWord);
strcat(temp, pos + oldWordLength);
strcpy(str, temp);
str = str + strlen(newWord);
}
}

int main()
{
char str[1000] = "The quick brown fox jumps over the lazy dog";
const char oldWord[] = "fox";
const char newWord[] = "cat";

printf("Original string: %s\n", str);


replaceWord(str, oldWord, newWord);
printf("Modified string: %s\n", str);
return 0;
}
OUTPUT:

Original string: The quick brown fox jumps over the lazy fox

Modified string: The quick brown cat jumps over the lazy cat

RESULT:

Thus a C Program String operations was executed and the output was obtained.
Ex. No : 6
SORTING USING PASS BY REFERENCE
Date :
AIM:

To write a C Program to Sort the list of numbers using pass by reference.


ALGORITHM:
Step1:Start
Step2:Declare variables and create an array
Step3:Read the Input for number of elements and each element.
Step4:Develop a function to sort the array by passing reference
Step5:Compare the elements in each pass till all the elements are sorted.
Step6:Display the output of the sorted elements .
Step7:Stop

PROGRAM:
#include <stdio.h>
#include <conio.h>
void main()
{
int n,a[100],i;
void sortarray(int*,int);
clrscr();
printf("\nEnter the Number of Elements in an array : ");
scanf("%d",&n);
printf("\nEnter the Array elements\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
sortarray(a,n);
printf("\nAfter Sorting... \n");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
getch();
}
void sortarray(int* arr,int num)
{
int i,j,temp;
for(i=0;i<num;i++)
for(j=i+1;j<num;j++)
if(arr[i] > arr[j])
{ temp=arr[i];
arr[i] = arr[j];arr[j] = temp;
}
}
OUTPUT:
Enter the number of elements in the array: 5
Enter the array elements:
34
12
25
68
4

After sorting the array:


4
12
25
34
68

RESULT:
Thus a C Program Sorting using pass by reference was executed and the output was
obtained.
Ex. No : 7
TOWERS OF HANOI USING RECURSION
Date :

AIM:
To write a C Program to Solve towers of Hanoi using recursion.

ALGORITHM:
Step1: Start
Step2: Declare variables
Step3: Read the Input for number of discs.
Step4: Check the condition for each transfer of discs using recursion.
Step5: Display the output of the each move .
Step6: Stop

PROGRAM:
#include <stdio.h>
void towers(int, char, char, char);
void main()
{
int num;
clrscr();
printf("Enter the number of disks : ");
scanf("%d", &num);
printf("The sequence of moves involved in the Tower of Hanoi are :\n");
towers(num, 'A', 'C', 'B');
getch();
}
void towers(int num, char frompeg, char topeg, char auxpeg)
{
if (num == 1)
{
printf("\n Move disk 1 from peg %c to peg %c", frompeg, topeg);
return;
}
towers(num - 1, frompeg, auxpeg, topeg);
printf("\n Move disk %d from peg %c to peg %c", num, frompeg, topeg);
towers(num - 1, auxpeg, topeg, frompeg);
}
OUTPUT:
Enter the number of disks: 3
The sequence of moves involved in the Tower of Hanoi are:
Move disk 1 from peg A to peg C
Move disk 2 from peg A to peg B
Move disk 1 from peg C to peg B
Move disk 3 from peg A to peg C
Move disk 1 from peg B to peg A
Move disk 2 from peg B to peg C
Move disk 1 from peg A to peg C

RESULT:

Thus a C Program tower of Hanoi using recursion was executed and the output was obtained.
Ex. No : 8(a)
GENERATE SALARY SLIP OF EMPLOYEES USING
Date : STRUCTURES AND POINTERS

AIM:
To write a C Program to Generate salary slip of employees using structures and pointers.

ALGORITHM:

Step 1: Start
Step 2: Declare variables
Step 3: Read the number of employees
Step 4: Read allowances, deductions and basic for each employee.
Step 5: Calculate net pay= (basic+ allowances)-deductions
Step 6: Display the output of the Pay slip calculations for each employee.
Step 7: Stop

PROGRAM:
#include<stdio.h>
#include<conio.h>
struct emp
{
int empno ;
char name[10] ;
int bpay, allow, ded, npay ;
} e[10] ;
void main()
{
int i, n ;
clrscr();
printf("Enter the number of employees : ") ;
scanf("%d", &n) ;
for(i = 0 ; i < n ; i++)
{
printf("\nEnter the employee number : ") ;
scanf("%d", &e[i].empno) ;
printf("\nEnter the name : ") ;
scanf("%s", e[i].name) ;
printf("\nEnter the basic pay, allowances & deductions : ") ;
scanf("%d %d %d", &e[i].bpay,&e[i].allow, &e[i].ded) ;
e[i].npay = e[i].bpay + e[i].allow - e[i].ded ;
}
printf("\nEmp. No. Name \t Bpay \t Allow \t Ded \t Npay \n\n") ;
for(i = 0 ; i < n ; i++)
{
printf("%d \t %s \t %d \t %d \t %d \t %d \n", e[i].empno,e[i].name, e[i].bpay, e[i].allow,
e[i].ded,e[i].npay) ;
}
getch();
}

OUTPUT:
Enter the number of employees: 2

Enter the employee number: 1


Enter the name: Alice
Enter the basic pay, allowances & deductions: 5000 1500 500

Enter the employee number: 2


Enter the name: Bob
Enter the basic pay, allowances & deductions: 6000 2000 1000

Emp. No. Name Bpay Allow Ded Npay


1 Alice 5000 1500 500 6000
2 Bob 6000 2000 1000 7000

RESULT:
Thus a C Program Salary slip of employees was executed and the output was obtained.
Ex. No : 8(b)
INTERNAL MARKS OF STUDENTS
Date :

AIM:
To write a C Program to Compute internal marks of students for five different subjects
using structures and functions.

ALGORITHM:
Step 1: Start
Step 2: Declare variables
Step 3: Read the number of students
Step 4: Read the student mark details
Step 5: Calculate internal mark by i=total of three test marks / 3 for each subject per student
Step 6: Display the output of the calculations for all the students
Step 7: Stop

PROGRAM:
#include<stdio.h>
#include<conio.h>
struct mark_sheet
{
char name[20];
long int rollno;
int marks[10];
int total;
float average;
char rem[10];
char cl[20];
}students[100];
int main()
{
int a,b,n,flag=1;
char ch;
clrscr();
printf("How many students : \n");
scanf("%d",&n);
for(a=1;a<=n;++a)
{
clrscr();
printf("\n\nEnter the details of %d students : ", n-a+1);printf("\n\nEnter student %d Name : ", a);
scanf("%s", students[a].name);
printf("\n\nEnter student %d Roll Number : ", a);
scanf("%ld", &students[a].rollno);
students[a].total=0;
for(b=1;b<=5;++b)
{
printf("\n\nEnter the mark of subject-%d : ", b);
scanf("%d", &students[a].marks[b]);
students[a].total += students[a].marks[b];
if(students[a].marks[b]<40)
flag=0;
}
students[a].average =(float)(students[a].total)/5.0;
if((students[a].average>=75)&&(flag==1))
strcpy(students[a].cl,"Distinction");
else if((students[a].average>=60)&&(flag==1))
strcpy(students[a].cl,"First Class");
else if((students[a].average>=50)&&(flag==1))
strcpy(students[a].cl,"Second Class");
else if((students[a].average>=40)&&(flag==1))
strcpy(students[a].cl,"Third Class");
if(flag==1)
strcpy(students[a].rem,"Pass");
else strcpy(students[a].rem,"Fail");
flag=1;
}
for(a=1;a<=n;++a)
{
clrscr();
printf("\n\n\t\t\t\tMark Sheet\n");
printf("\nName of Student%s",students[a].name);
printf("\t\t\t\t Roll No : %ld", students[a].rollno);
printf("\n ");
for(b=1;b<=5;b++)
{
printf("\n\n\t Subject %d \t\t :\t %d", b, students[a].marks[b]);
}
printf("\n\n \n");
printf("\n\n Totl Marks : %d", students[a].total);
printf("\t\t\t\t Average Marks : %5.2f", students[a].average);
printf("\n\n Class : %s", students[a].cl);
printf("\t\t\t\t\t Status : %s", students[a].rem);
printf("\n\n\n\t\t\t\t Press Y for continue . . . ");
ch =getche();
if((ch=="y")||(ch=="Y"))
continue;
}
return(0);
}
OUTPUT:
How many students: 2

Enter details for student 1:


Enter student 1 Name: Alice
Enter student 1 Roll Number: 101
Enter the mark for subject-1: 75
Enter the mark for subject-2: 80
Enter the mark for subject-3: 85
Enter the mark for subject-4: 90
Enter the mark for subject-5: 95

Enter details for student 2:


Enter student 2 Name: Bob
Enter student 2 Roll Number: 102
Enter the mark for subject-1: 40
Enter the mark for subject-2: 50
Enter the mark for subject-3: 60
Enter the mark for subject-4: 70
Enter the mark for subject-5: 80

Mark Sheet

Name of Student: Alice Roll No: 101


Subject 1: 75
Subject 2: 80
Subject 3: 85
Subject 4: 90
Subject 5: 95
Total Marks: 425 Average Marks: 85.00
Class: Distinction Status: Pass

Press Y to continue...
Mark Sheet
Name of Student: Bob Roll No: 102
Subject 1: 40
Subject 2: 50
Subject 3: 60
Subject 4: 70
Subject 5: 80
Total Marks: 300 Average Marks: 60.00
Class: First Class Status: Pass
Press Y to continue...
RESULT:

Thus a C Program for Internal marks of students was executed and the output was obtained.
Ex. No : 9
TELEPHONE DIRECTORY
Date :

AIM:
To write a C Program to add, delete, display, Search and exit options for telephone details of
an individual into a telephone directory using random access file.

ALGORITHM:
Step1: Start.
Step 2: Declare variables, File pointer and phonebook structures.
Step3: create menu options.
step4: Read the option .
Step5: Develop procedures for each option.
Step6: Call the procedure (Add, delete ,display ,Search and exit)for user chosen option.
Step7: Display the message for operations performed.
Step8: Stop

PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Phonebook_Contacts
{
char FirstName[20];
char LastName[20];
char PhoneNumber[20];
} phone;
void AddEntry(phone * );
void DeleteEntry(phone * );
void PrintEntry(phone * );
void SearchForNumber(phone * );
int counter = 0;
char FileName[256];
FILE *pRead;
FILE *pWrite;
int main (void)
{
phone *phonebook;
phonebook = (phone*) malloc(sizeof(phone)*100);
int iSelection = 0;
if (phonebook == NULL)
{
printf("Out of Memory. The program will now exit");
return 1;
}
else {}
do
{
printf("\n\t\t\tPhonebook Menu");
printf("\n\n\t(1)\tAdd Friend");
printf("\n\t(2)\tDelete Friend");
printf("\n\t(3)\tDisplay Phonebook Entries");
printf("\n\t(4)\tSearch for Phone Number");
printf("\n\t(5)\tExit Phonebook");
printf("\n\nWhat would you like to do? ");
scanf("%d", &iSelection);
if (iSelection == 1)
{
AddEntry(phonebook);
}
if (iSelection == 2)
{
DeleteEntry(phonebook);
}
if (iSelection == 3)
{
PrintEntry(phonebook);
}
if (iSelection == 4)
{
SearchForNumber(phonebook);
}
if (iSelection == 5)
{
printf("\nYou have chosen to exit the Phonebook.\n");
return 0;
}
} while (iSelection <= 4);
}
void AddEntry (phone * phonebook)
{
pWrite = fopen("phonebook_contacts.dat", "a");
if ( pWrite == NULL )
{
perror("The following error occurred ");
exit(EXIT_FAILURE);
}
else
{
counter++;
realloc(phonebook, sizeof(phone));
printf("\nFirst Name: ");
scanf("%s", phonebook[counter-1].FirstName);
printf("Last Name: ");
scanf("%s", phonebook[counter-1].LastName);
printf("Phone Number (XXX-XXX-XXXX): ");
scanf("%s", phonebook[counter-1].PhoneNumber);
printf("\n\tFriend successfully added to Phonebook\n");
fprintf(pWrite, "%s\t%s\t%s\n", phonebook[counter-1].FirstName, phonebook[counter-1].LastName,
phonebook[counter-1].PhoneNumber);
fclose(pWrite);
}
}
void DeleteEntry (phone * phonebook)
{
M
int x = 0;
int i = 0;
char deleteFirstName[20]; //
char deleteLastName[20];
printf("\nFirst name: ");
scanf("%s", deleteFirstName);
printf("Last name: ");
scanf("%s", deleteLastName);
for (x = 0; x < counter; x++)
{
if (strcmp(deleteFirstName, phonebook[x].FirstName) == 0)
{
if (strcmp(deleteLastName, phonebook[x].LastName) == 0)
{
for ( i = x; i < counter - 1; i++ )
{
strcpy(phonebook[i].FirstName, phonebook[i+1].FirstName);
strcpy(phonebook[i].LastName, phonebook[i+1].LastName);
strcpy(phonebook[i].PhoneNumber, phonebook[i+1].PhoneNumber);
}
printf("Record deleted from the phonebook.\n\n");
--counter;
return;
}
}
}
printf("That contact was not found, please try again.");
}
void PrintEntry (phone * phonebook)
{
int x = 0;
printf("\nPhonebook Entries:\n\n ");
pRead = fopen("phonebook_contacts.dat", "r");
if ( pRead == NULL)

{
perror("The following error occurred: ");
exit(EXIT_FAILURE);
}
else
{
for( x = 0; x < counter; x++)
{
printf("\n(%d)\n", x+1);
printf("Name: %s %s\n", phonebook[x].FirstName, phonebook[x].LastName);
printf("Number: %s\n", phonebook[x].PhoneNumber);
}
}
fclose(pRead);
}
void SearchForNumber (phone * phonebook)
{
int x = 0;
char TempFirstName[20];
char TempLastName[20];
printf("\nPlease type the name of the friend you wish to find a number for.");
printf("\n\nFirst Name: ");
scanf("%s", TempFirstName);
printf("Last Name: ");
scanf("%s", TempLastName);
for (x = 0; x < counter; x++)
{
if (strcmp(TempFirstName, phonebook[x].FirstName) == 0)
{
if (strcmp(TempLastName, phonebook[x].LastName) == 0)
{
printf("\n%s %s's phone number is %s\n", phonebook[x].FirstName,
phonebook[x].LastName, phonebook[x].PhoneNumber);
}
}
}
}
OUTPUT:
Phonebook Menu

(1) Add Friend


(2) Delete Friend
(3) Display Phonebook Entries
(4) Search for Phone Number
(5) Exit Phonebook

What would you like to do? 1

First Name: John


Last Name: Doe
Phone Number (XXX-XXX-XXXX): 123-456-7890

Friend successfully added to Phonebook

Phonebook Menu

(1) Add Friend


(2) Delete Friend
(3) Display Phonebook Entries
(4) Search for Phone Number
(5) Exit Phonebook

What would you like to do? 3

Phonebook Entries:

(1)
Name: John Doe
Number: 123-456-7890

RESULT:

Thus a C Program was executed and the output was obtained.


Ex. No : 10
BANKING APPLICATION
Date :

AIM:
To write a C Program to Count the number of account holders whose balance is less than the
minimum balance using sequential access file.

ALGORITHM:
Step 1: Start
Step 2: Declare variables and file pointer.
Step 3: Display the menu options.
Step 4: Read the Input for transaction processing.
Step 5: Check the validation for the input data.
Step 6: Display the output of the calculations .
Step 7: Repeat step 3 until choose to stop.
Step 8: Stop

PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#define MINBAL 500
struct Bank_Account
{
char no[10];
char name[20];
char balance[15];
};
struct Bank_Account acc;
void main()
{
long int pos1,pos2,pos;
FILE *fp;
char *ano,*amt;
char choice;
int type,flag=0;
float bal;
do
{
clrscr(); fflush(stdin);
printf("1. Add a New Account Holder\n"); printf("2. Display\n");
printf("3. Deposit or Withdraw\n");
printf("4. Number of Account Holder Whose Balance is less than the Minimum Balance\n");
printf("5. Delete All\n"); printf("6. Stop\n"); printf("Enter your choice : "); choice=getchar();
switch(choice)
{
case '1' :
fflush(stdin);
fp=fopen("acc.dat","a");
printf("\nEnter the Account Number : ");
gets(acc.no);
printf("\nEnter the Account Holder Name : ");
gets(acc.name);
printf("\nEnter the Initial Amount to deposit : ");
gets(acc.balance);
fseek(fp,0,2);
fwrite(&acc,sizeof(acc),1,fp);
fclose(fp);
break;
case '2' :
fp=fopen("acc.dat","r");
if(fp==NULL)
printf("\nFile is Empty");
else
{
printf("\nA/c Number\tA/c Holder Name Balance\n");
while(fread(&acc,sizeof(acc),1,fp)==1)
printf("%-10s\t\t%-20s\t%s\n",acc.no,acc.name,acc.balance);
fclose(fp);
}
break;
case '3' :
fflush(stdin);
flag=0;
fp=fopen("acc.dat","r+");
printf("\nEnter the Account Number : ");
gets(ano);
for(pos1=ftell(fp);
fread(&acc,sizeof(acc),1,fp)==1;
pos1=ftell(fp))
{
if(strcmp(acc.no,ano)==0)
{
printf("\nEnter the Type 1 for deposit & 2 for withdraw : ");
scanf("%d",&type);
printf("\nYour Current Balance is : %s",acc.balance);
printf("\nEnter the Amount to transact : ");
fflush(stdin);
gets(amt);
if(type==1)
bal = atof(acc.balance) + atof(amt);
else
{
bal = atof(acc.balance) - atof(amt);
if(bal<0)
{
printf("\nRs.%s Not available in your A/c\n",amt);
flag=2;
break;
}
}
flag++;
break;
}
}
if(flag==1)
{
pos2=ftell(fp);
pos = pos2-pos1;
fseek(fp,-pos,1);
sprintf(amt,"%.2f",bal);
strcpy(acc.balance,amt);
fwrite(&acc,sizeof(acc),1,fp);
}
else if(flag==0)
printf("\nA/c Number Not exits... Check it again");
fclose(fp);
break;
case '4' :
fp=fopen("acc.dat","r");
flag=0;
while(fread(&acc,sizeof(acc),1,fp)==1)
{
bal = atof(acc.balance);
if(bal<MINBAL)
flag++;
}
printf("\nThe Number of Account Holder whose Balance less than the Minimum Balance :
%d",flag); fclose(fp);
break;
case '5' :
remove("acc.dat");
break;
case '6' :
fclose(fp);
exit(0);
}
printf("\nPress any key to continue ");
getch();
} while (choice!='6');
}
OUTPUT:
1. Add a New Account Holder
2. Display All Accounts
3. Deposit or Withdraw
4. Number of Accounts with Balance Less Than Minimum Balance
5. Delete All Accounts
6. Exit
Enter your choice: 1

Enter the Account Number: 1001


Enter the Account Holder Name: John
Enter the Initial Amount to deposit: 1000.00

Account successfully added.

Press any key to continue...

RESULT:
Thus a C Program for Banking Application was executed and the output was obtained.

You might also like