CS8261-C Programming Lab - by LearnEngineering - in
CS8261-C Programming Lab - by LearnEngineering - in
in
n
g.i
rin
ee
gin
CS8261 C PROGRAMMING LABORATORY
En
LABORATORY MANUAL
o Students must wear ID card and shoes before entering into the lab.
o Boys should wear formal shirt, pant and should “tuck in” theshirts.
o You must shutdown the system, switch off the power supply and arrange the
n
chairs properly before leaving the lab.
g.i
o Maintain Observation Notebook and Lab Record neatly and complete them then and there after
rin
completion of each exercise.
ee
o Maintain discipline in the lab and be silent throughout the lab session.
gin
En
arn
Le
w.
ww
OBJECTIVES:
To develop programs in C using basic constructs.
To develop applications in C using strings, pointers, functions, structures
To develop applications in C using file processing
LIST OF EXPERIMENTS:
1. Programs using I/O statements and expressions.
2. Programs using decision-making constructs.
3. Write a program to find whether the given year is leap year or Not? (Hint: not every centurion
year is a leap. For example 1700, 1800 and 1900 is not a leap year)
n
4. Design a calculator to perform the operations, namely, addition, subtraction, multiplication,
division and square of a number.
g.i
5. Check whether a given number is Armstrong number or not?
6. Given a set of numbers like <10, 36, 54, 89, 12, 27>, find sum of weights based on the
rin
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
ee
Sort the numbers based on the weight in the increasing order as shown below <10,its
weight>,<36,its weight><89,its weight>
gin
7. Populate an array with height of persons and find how many persons are above the average
height.
8. Populate a two dimensional array with height and weight of persons and compute the Body
En
11. From a given paragraph perform the following using built-in functions:
a. Find the total number of words.
b. Capitalize the first word of each sentence.
w.
Mini Project
18. Create a ―Railway reservation system‖ with the following modules
Booking
Availability checking
Cancellation
Prepare chart
TOTAL: 60 PERIODS OUTCOMES: Upon completion of the course, the students will be able to
Develop C programs for simple applications making use of basic constructs, arrays and
strings.
Develop C programs involving functions, recursion, pointers, and structures.
Design applications using sequential and random access file processing
n
g.i
rin
ee
gin
En
arn
Le
w.
ww
Table of Contents
Ex. Page
Name of the Experiment
No. No.
1 Programs using I/O statements and expressions. 7
n
g.i
4 Arithmetic operations. 13
rin
5 Armstrong number. 15
7 ee
Average height of persons. 20
gin
8 Body Mass Index of the individuals. 22
9 24
11 String operations. 29
Le
13 35
16 Telephone directory. 43
17 Banking Application 49
n
g.i
rin
ee
gin
En
arn
Le
w.
ww
DATE :
AIM
ALGORITHM
n
g.i
1. Start
2. Declare variables and initializations
rin
3. Read the Input variable.
4. Using I/O statements and expressions for computational processing.
ee
5. Display the output of the calculations.
gin
6. Stop
En
PROGRAM
/*
arn
* Sum the odd and even numbers, respectively, from 1 to a given upperbound.
* Also compute the absolute difference.
* (SumOddEven.c)
*/
Le
int main() {
w.
n
g.i
// Print the results
printf("The sum of odd numbers is %d.\n", sumOdd);
rin
printf("The sum of even numbers is %d.\n", sumEven);
printf("The absolute difference is %d.\n", absDiff);
}
return 0;
ee
gin
OUTPUT
En
RESULT:
Thus a C Program using i/o statements and expressions was executed and the output was
obtained.
DATE :
AIM
ALGORITHM
n
1. Start
g.i
2. Declare variables and initializations
3. Read the Input variable.
rin
4. Codes are given to different categories and da is calculated as follows:
For code 1,10% of basic salary.
ee
For code 2, 15% of basic salary.
gin
For code 3, 20% of basic salary.
For code >3 da is not given.
5. Display the output of the calculations .
En
6. Stop
arn
PROGRAM
Le
#include <stdio.h>
#include<conio.h>
void main ()
w.
{
float basic , da , salary ;
int code ;
ww
char name[25];
da=0.0;
printf("Enter employee name\n");
scanf("%[^\n]",name);
printf("Enter basic salary\n");
scanf("%f",&basic);
printf("Enter code of the Employee\n");
scanf("%d",&code);
switch (code)
{
case 1:
da = basic * 0.10;
break;
case 2:
da = basic * 0.15;
break;
case 3:
da = basic * 0.20; break;
default :
da = 0;
}
salary = basic + da;
printf("Employee name is\n");
printf("%s\n",name);
printf ("DA is %f and Total salary is =%f\n",da, salary);
n
getch();
g.i
}
rin
OUTPUT
ee
gin
Enter employee name
sriram
Enter basic salary
5000
En
sriram
DA is 500.000000 and Total salary is =5500.000000
Le
w.
ww
RESULT
Thus a C Program using decision-making constructs was executed and the output was
obtained.
10
DATE :
AIM
To write a C Program to find whether the given year is leap year or Not .
ALGORITHM
n
1. Start
g.i
2. Declare variables
3. Read the Input .
rin
4. Take a year as input and store it in the variable year.
5. Using if,else statements to,
ee
a) Check whether a given year is divisible by 400.
gin
b) Check whether a given year is divisible by 100.
c) Check whether a given year is divisible by 4.
6. If the condition at step 5.a becomes true, then print the ouput as “It is a leap year”.
En
7. If the condition at step 5.b becomes true, then print the ouput as “It is not a leap
year”.
arn
8. If the condition at step 5.c becomes true, then print the ouput as “It is a leap year”.
9. If neither of the condition becomes true, then the year is not a leap year and print
Le
the same.
10. Display the output of the calculations .
w.
11. Stop
ww
PROGRAM
/*
*/
void main()
11
int year;
scanf("%d", &year);
if ((year % 400) == 0)
n
g.i
printf("%d is a not leap year \n", year);
else if ((year % 4) == 0)
rin
printf("%d is a leap year \n", year);
else
ee
gin
printf("%d is not a leap year \n", year);
}
En
arn
Le
OUTPUT
Enter a year
w.
2012
2012 is a leap year
ww
Enter a year
2009
2009 is not a leap year
RESULT
Thus a C Program for Leap year checking was executed and the output was obtained.
12
DATE :
AIM
ALGORITHM
n
g.i
1. Start
2. Declare variables
rin
3. Read the Inputs .
4. Calculate Arithmetic operations(+,-,*,/,pow) for the input of two numbers.
ee
5. Display the output of the calculations .
gin
6. Stop
En
PROGRAM
/*
arn
#include <conio.h>
int main(){
w.
/* Variable declation */
int firstNumber, secondNumber;
ww
13
n
g.i
getch();
return 0;
}
rin
ee
gin
En
OUTPUT
Sum = 29
Le
Difference = 21
Multiplication = 100
Division = 6.250
w.
Square = 625
ww
RESULT
Thus a C Program for Arithmetic operations was executed and the output was obtained.
14
DATE :
AIM
ALGORITHM
n
g.i
1. Start
2. Declare variables
rin
3. Read the Input number.
4. Calculate sum of cubic of individual digits of the input.
ee
5. Match the result with input number.
gin
6. If match, Display the given number is Armstrong otherwise not.
7. Stop
En
PROGRAM
arn
/*
*/
w.
#include <stdio.h>
#include <math.h>
ww
void main()
15
scanf("%d", &number);
temp = number;
while (number != 0)
n
sum = sum + cube;
g.i
number = number / 10;
rin
}
if (sum == temp)
ee
printf ("The given no is armstrong no");
gin
else
}
arn
Le
w.
OUTPUT
enter a number370
ww
RESULT
Thus a C Program for Armstrong number checking was executed and the output was
obtained.
16
DATE :
AIM
n
3 if it is a prime number
g.i
Sort the numbers based on the weight in the increasing order as shown below <10,its
rin
weight>,<36,its weight><89,its weight>
ee
gin
ALGORITHM
1. Start
En
2. Declare variables
3. Read the number of elements .
arn
7. Stop
PROGRAM
#include <stdio.h>
#include <math.h>
void main()
{
int nArray[50],wArray[50],nelem,i,j,t;
17
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;
n
wArray[i] = wArray[i] + 4;
g.i
if(prime(nArray[i]))
wArray[i] = wArray[i] + 3;
rin
}
// Sorting an array
for(i=0;i<nelem;i++)
for(j=i+1;j<nelem;j++) ee
gin
if(wArray[i] > wArray[j])
{
t = wArray[i];
wArray[i] = wArray[j];
En
wArray[j] = t;
}
arn
}
w.
for(i=2;i<=num/2;i++)
if(num%i==0)
{
flag=0;
break;
}
return flag;
}
int percube(int num)
{
int i,flag=0;
18
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
n
Enter 5 elements:
g.i
8
11
216
rin
24
34
<34,0> ee
gin
<11,3>
<24,4>
<8,5>
<216,9>
En
Explanation:
8 is a perfect cube of 2, not a prime number and not a multiple of 4 & divisible of 6 so the
arn
answer is 5
11 is a prime number so the answer is 3
216 is a perfect cube and multiple of 4 & divisible by 6 so the answer is 5+4 = 9
24 is not a perfect cube and not a prime number and multiple of 4 & divisible by 6 so the
Le
answer is 4
34 not satisfied all the conditions so the answer is 0
w.
ww
RESULT
Thus a C Program for Sort the numbers based on the weight was executed and the output
was obtained.
19
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.
n
ALGORITHM
g.i
1. Start
rin
2. Declare variables
3. Read the total number of persons and their height.
ee
4. Calculate avg=sum/n and find number of persons their h>avg.
gin
5. Display the output of the calculations .
6. Stop
En
PROGRAM
arn
#include <conio.h>
void main()
{
w.
int i,n,sum=0,count=0,height[100];
float avg;
clrscr();
ww
20
//Counting
for(i=0;i<n;i++)
if(height[i]>avg)
count++;
//display
printf("\nAverage Height of %d persons is : %.2f\n",n,avg);
printf("\nThe number of persons above average : %d ",count);
getch();
}
OUTPUT
Enter the Number of Persons : 5
n
Enter the Height of each person in centimeter
g.i
150
155
162
rin
158
154
ee
Average Height of 5 persons is : 155.8
gin
The number of persons above average : 2
En
arn
Le
w.
ww
RESULT
Thus a C Program average height of persons was executed and the output was obtained.
21
DATE :
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
n
g.i
1. Start
2. Declare variables
rin
3. Read the number of persons and their height and weight.
4. Calculate BMI=W/H2for each person
ee
5. Display the output of the BMI for each person.
gin
6. Stop
En
PROGRAM
#include<stdio.h>
arn
#include<math.h>
int main(void){
Le
int n,i,j;
scanf("%d",&n);
ww
float massheight[n][2];
float bmi[n];
for(i=0;i<n;i++){
for(j=0;j<2;j++){
switch(j){
case 0:
printf("\nPlease enter the mass of the person %d in kg: ",i+1);
scanf("%f",&massheight[i][0]);
break;
22
case 1:
printf("\nPlease enter the height of the person %d in meter: ",i+1);
scanf("%f",&massheight[i][1]);
break;}
}
}
for(i=0;i<n;i++){
bmi[i]=massheight[i][0]/pow(massheight[i][1],2.0);
printf("Person %d's BMI is %f\n",i+1,bmi[i]);
}
n
return 0;
g.i
}
rin
ee
gin
OUTPUT
How many people's BMI do you want to calculate?
2
Please enter the mass of the person 1 in kg: 88
En
RESULT
Thus a C Program Body Mass Index of the individuals was executed and the output was
obtained.
23
DATE :
AIM
ALGORITHM
n
g.i
1. Start
2. Declare variables .
rin
3. Read a String.
4. Check each character of string for alphabets or a special character by using
isAlpha() . ee
gin
5. Change the position of a character vice versa if it is alphabet otherwise remains
same.
6. Repeat step 4 until reach to the mid of the position of a string.
En
7. Display the output of the reverse string without changing the position of special
characters .
arn
8. Stop
Le
PROGRAM
#include <stdio.h>
w.
#include <string.h>
#include <conio.h>
void swap(char *a, char *b)
ww
{
char t;
t = *a;
*a = *b;
*b = t;
}
// Main program
void main()
{
char str[100];
24
// Function Prototype
void reverse(char *);
int isAlpha(char);
void swap(char *a ,char *b);
clrscr();
printf("Enter the Given String : ");
// scanf("%[^\n]s",str);
gets(str);
reverse(str);
printf("\nReverse String : %s",str);
getch();
}
n
{
g.i
// Initialize left and right pointers
int r = strlen(str) - 1, l = 0;
rin
// Traverse string from both ends until
// 'l' and 'r'
while (l < r)
{
// Ignore special characters ee
gin
if (!isAlpha(str[l]))
l++;
else if(!isAlpha(str[r]))
r--;
En
else
{
arn
swap(&str[l], &str[r]);
l++;
r--;
Le
}
}
}
w.
int isAlpha(char x)
{
return ( (x >= 'A' && x <= 'Z') ||
(x >= 'a' && x <= 'z') );
}
25
OUTPUT
n
g.i
rin
ee
gin
En
arn
Le
w.
ww
RESULT
Thus a C Program for reverse of a given String was executed and the output was obtained.
26
DATE :
AIM
To write a C Program to Convert the given decimal number into binary, octal and
hexadecimal numbers using user defined functions.
ALGORITHM
n
g.i
1. Start
2. Declare variables.
rin
3. Read a decimal number.
4. Develop the procedure for conversion of different base by modulus and divide
operator. ee
gin
5. Display the output of the conversion value.
6. Stop
En
PROGRAM
arn
#include <stdio.h>
#include <conio.h>
void swap(char *s1, char *s2)
Le
{
char temp;
temp = *s1;
w.
*s1 = *s2;
*s2 = temp;
}
ww
27
n
}
g.i
str[i] = '\0'; // Append string terminator
// Reverse the string
reverse(str, i);
rin
return str;
}
void main()
{
char str[100]; ee
gin
int n;
clrscr();
printf("Enter the given decimal number : ");
scanf("%d",&n);
En
getch();
}
Le
w.
OUTPUT
RESULT
Thus a C Program for conversion of decimal number into other bases was executed and the
output was obtained.
28
DATE :
AIM
n
g.i
ALGORITHM
rin
1. Start
2. Declare variables ee
gin
3. Read the text.
4. Display the menu options
5. Compare each character with tab char ‘\t’ or space char ‘ ‘ to count no of words
En
6. Find the first word of each sentence to capitalize by checks to see if a character is a
punctuation mark used to denote the end of a sentence. (! . ?)
7. Replace the word in the text by user specific word if match.
arn
PROGRAM
#include <stdio.h>
ww
#include <stdlib.h>
#include <string.h>
void replace (char *, char *, char *);
int main()
{
char choice.str[200];
int i, words;
char s_string[200], r_string[200];
/* Input text from user */
printf("Enter any text:\n ");
gets(str);
29
do
{
printf("\n1. Find the total number of words \n");
printf("2. Capitalize the first word of each sentence \n");
printf("3. Replace a given word with another word \n");
printf("4. Stop\n");
printf("Enter your choice : ");
choice=getchar();
switch(choice)
{
case '1' :
i = 0;
words = 1;
n
g.i
/* Runs a loop till end of text */
while(str[i] != '\0')
{
rin
/* If the current character(str[i]) is white space */
if(str[i]==' ' || str[i]=='\n' || str[i]=='\t')
{
}
words++;
ee
gin
i++;
}
En
case '2' :
i = 0;
Le
{
i++;
while(str[i]!=' ' || str[i]!='\n' || str[i]!='\t || str[i] != '\0'’)
{putchar (toupper(str[++i]));
i++;
}
}
else
putchar (str[i]);
i++;
30
}
break;
case '3' :
Write a user defined function to replace the first occurrence of the search string with the
replace string.
Recursively call the function until there is no occurrence of the search string.*/
n
fflush(stdin);
gets(s_string);
g.i
printf("\nPlease enter the replace string ");
rin
fflush(stdin);
gets(r_string);
puts(str);
ee
gin
break;
case '4' :
En
exit(0);
}
printf("\nPress any key to continue....");
arn
getch();
}
while(choice!=’4’);
Le
return 0;
}
w.
char buffer[200];
//to store the pointer returned from strstr
char * ch;
//copy all the content to buffer before the first occurrence of the search string
strncpy(buffer, str, ch-str);
31
buffer[ch-str] = 0;
n
g.i
OUTPUT
rin
Enter any text:
I like C and C++ programming!
RESULT
Thus a C Program String operations was executed and the output was obtained.
32
DATE :
AIM
ALGORITHM
n
1. Start
g.i
2. Declare variables
3. Read the Input for number of discs.
rin
4. Check the condition for each transfer of discs using recursion.
5. Display the output of the each move .
6. Stop ee
gin
PROGRAM
En
/*
Rules of Tower of Hanoi:
arn
can be moved.
Larger disk cannot be placed over smaller disk; placing of disk should be in
increasing order.
w.
*/
#include <stdio.h>
#include <conio.h>
ww
33
int main()
{
int n;
clrscr();
printf("Enter the number of disks : ");
scanf("%d",&n); // Number of disks
towerofhanoi(n, 'A', 'C', 'B'); // A, B and C are names of peg
getch();
return 0;
}
n
g.i
rin
OUTPUT
Enter the number of disks : 3
Move disk 1 from peg A to peg C
Move disk 2 from peg A to peg B ee
gin
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
En
RESULT
Thus a C Program Towers of Hanoi using Recursion was executed and the output was
obtained.
34
DATE :
AIM
ALGORITHM
n
g.i
1. Start
2. Declare variables and create an array
rin
3. Read the Input for number of elements and each element.
4. Develop a function to sort the array by passing reference
ee
5. Compare the elements in each pass till all the elements are sorted.
gin
6. Display the output of the sorted elements .
7. Stop
En
PROGRAM
arn
#include <stdio.h>
#include <conio.h>
Le
void main()
{
w.
int n,a[100],i;
void sortarray(int*,int);
clrscr();
ww
35
n
g.i
rin
OUTPUT
ee
Enter the Number of Elements in an array : 5
gin
Enter the Array elements
33
67
21
En
45
11
After Sorting....
arn
11
21
33
Le
45
67
w.
ww
RESULT
Thus a C Program Sorting using pass by reference was executed and the output was
obtained.
36
DATE :
AIM
1. Start
n
2. Declare variables
g.i
3. Read the number of employees .
rin
4. Read allowances, deductions and basic for each employee.
5. Calculate net pay= (basic+ allowances)-deductions
ee
6. Display the output of the Pay slip calculations for each employee.
7. Stop
gin
PROGRAM
En
#include<stdio.h>
#include<conio.h>
#include "stdlib.h"
arn
struct emp
{
int empno ;
char name[10], answer ;
Le
void main()
{
ww
int I,n=0;
int more_data = 1;
struct emp e *current_ptr, *head_ptr;
clrscr() ;
head_ptr = (struct emp *) malloc (sizeof(struct emp));
current_ptr = head_ptr;
while (more_data)
{
{
printf("\nEnter the employee number : ") ;
scanf("%d", & current_ptr->empno) ;
printf("\nEnter the name : ") ;
37
scanf("%s",& current_ptr->name) ;
printf("\nEnter the basic pay, allowances & deductions : ") ;
scanf("%d %d %d", & current_ptr ->bpay, & current_ptr ->allow, & current_ptr -
>ded) ;
e[i].npay = e[i].bpay + e[i].allow - e[i].ded ;
n++;
printf("Would you like to add another employee? (y/n): ");
scanf("%s", answer);
if (answer!= 'Y')
{
current_ptr->next = (struct eme *) NULL;
more_data = 0;
}
n
else
g.i
{
current_ptr->next = (struct emp *) malloc (sizeof(struct emp));
current_ptr = current_ptr->next;
rin
}
}
}
ee
printf("\nEmp. No. Name \t Bpay \t Allow \t Ded \t Npay \n\n") ;
gin
current_ptr = head_ptr;
for(i = 0 ; i < n ; i++)
{
printf("%d \t %s \t %d \t %d \t %d \t %d \n", current_ptr->empno,
En
}
getch() ;
}
Le
w.
ww
OUTPUT
38
n
g.i
rin
ee
gin
En
arn
Le
w.
ww
RESULT
Thus a C Program Salary slip of employees was executed and the output was obtained.
39
DATE :
AIM
n
ALGORITHM
g.i
1. Start
rin
2. Declare variables
3. Read the number of students .
ee
4. Read the student mark details
gin
5. Calculate internal mark by i=total of three test marks / 3 for each subject per
student.
En
PROGRAM
#include<stdio.h>
Le
#include<conio.h>
struct stud{
char name[20];
w.
}students[10];
void calcinternal(int);
int main(){
int a,b,j,n;
clrscr();
printf("How many students : \n");
scanf("%d",&n);
for(a=0;a<n;++a){
clrscr();
printf("\n\nEnter the details of %d student : ", a+1);
40
n
clrscr();
g.i
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);
rin
printf("\n------------------------------------------------------------------------");
for(b=0;b<5;b++){
printf("\n\n\t Subject %d internal \t\t :\t %d", b+1, students[a].i[b]);
}
ee
printf("\n\n------------------------------------------------------------------------\n");
gin
getch();
}
return(0);
}
En
void calcinternal(int n)
{
arn
int a,b,j,total;
for(a=1;a<=n;++a){
for(b=0;b<5;b++){
Le
total=0;
for(j=0;j<=2;++j){
total += students[a].marks[b,j];
w.
}
students[a].i[b]=total/3;
}
ww
}
}
OUTPUT
41
n
g.i
Mark Sheet
Name of Student : H.Xerio Roll No : 536435
rin
------------------------------------------------------------------------
subject 1 internal : 59
subject 2 internal : 78
ee
subject 3 internal : 74
subject 4 internal : 40
gin
subject 5 internal : 60
------------------------------------------------------------------------
En
arn
Le
w.
ww
RESULT
Thus a C Program for Internal marks of students was executed and the output was
obtained.
42
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.
n
ALGORITHM
g.i
1. Start.
rin
2. Declare variables, File pointer and phonebook structures.
3. Create menu options.
4. Read the option . ee
gin
5. Develop procedures for each option.
6. Call the procedure (Add, delete ,display ,Search and exit)for user chosen option.
En
PROGRAM
Le
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
w.
{
char FirstName[20];
char LastName[20];
char PhoneNumber[20];
} phone;
void AddEntry(phone * );
void DeleteEntry(phone * );
void PrintEntry(phone * );
void SearchForNumber(phone * );
43
int counter = 0;
char FileName[256];
FILE *pRead;
FILE *pWrite;
n
if (phonebook == NULL)
g.i
{
rin
return 1;
}
else {}
do ee
gin
{
printf("\n\t\t\tPhonebook Menu");
printf("\n\n\t(1)\tAdd Friend");
printf("\n\t(2)\tDelete Friend");
En
if (iSelection == 1)
{
w.
AddEntry(phonebook);
}
ww
if (iSelection == 2)
{
DeleteEntry(phonebook);
}
if (iSelection == 3)
{
PrintEntry(phonebook);
44
if (iSelection == 4)
{
SearchForNumber(phonebook);
}
if (iSelection == 5)
{
printf("\nYou have chosen to exit the Phonebook.\n");
n
return 0;
g.i
}
} while (iSelection <= 4);
}
rin
void AddEntry (phone * phonebook)
{
ee
pWrite = fopen("phonebook_contacts.dat", "a");
gin
if ( pWrite == NULL )
{
perror("The following error occurred ");
exit(EXIT_FAILURE);
En
}
else
{
arn
counter++;
realloc(phonebook, sizeof(phone));
Le
scanf("%s", phonebook[counter-1].LastName);
printf("Phone Number (XXX-XXX-XXXX): ");
scanf("%s", phonebook[counter-1].PhoneNumber);
ww
45
int i = 0;
char deleteFirstName[20]; //
char deleteLastName[20];
n
{
g.i
for ( i = x; i < counter - 1; i++ )
{
strcpy(phonebook[i].FirstName, phonebook[i+1].FirstName);
rin
strcpy(phonebook[i].LastName, phonebook[i+1].LastName);
strcpy(phonebook[i].PhoneNumber, phonebook[i+1].PhoneNumber);
}
ee
printf("Record deleted from the phonebook.\n\n");
--counter;
gin
return;
}
}
}
En
int x = 0;
46
}
fclose(pRead);
}
printf("\nPlease type the name of the friend you wish to find a number for.");
printf("\n\nFirst Name: ");
scanf("%s", TempFirstName);
n
printf("Last Name: ");
g.i
scanf("%s", TempLastName);
for (x = 0; x < counter; x++)
{
rin
if (strcmp(TempFirstName, phonebook[x].FirstName) == 0)
{
if (strcmp(TempLastName, phonebook[x].LastName) == 0)
{
ee
gin
printf("\n%s %s's phone number is %s\n", phonebook[x].FirstName,
phonebook[x].LastName, phonebook[x].PhoneNumber);
}
}
En
}
}
arn
OUTPUT
Le
Phonebook Menu
(1) Add Friend
(2) Delete Friend"
w.
47
Phonebook Menu
(1) Add Friend
(2) Delete Friend"
n
g.i
rin
ee
gin
En
arn
Le
w.
ww
RESULT
48
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.
n
ALGORITHM
g.i
1. Start
rin
2. Declare variables and file pointer.
3. Display the menu options.
ee
4. Read the Input for transaction processing.
gin
5. Check the validation for the input data.
6. Display the output of the calculations .
En
PROGRAM
/* Count the number of account holders whose balance is less than the minimum balance
Le
#include <stdlib.h>
#include <conio.h>
#include <string.h>
ww
49
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");
n
printf("5. Stop\n");
g.i
printf("Enter your choice : ");
choice=getchar();
switch(choice)
rin
{
case '1' :
fflush(stdin);
fp=fopen("acc.dat","a");
ee
printf("\nEnter the Account Number : ");
gin
gets(acc.no);
printf("\nEnter the Account Holder Name : ");
gets(acc.name);
printf("\nEnter the Initial Amount to deposit : ");
En
gets(acc.balance);
fseek(fp,0,2);
fwrite(&acc,sizeof(acc),1,fp);
arn
fclose(fp);
break;
case '2' :
Le
fp=fopen("acc.dat","r");
if(fp==NULL)
printf("\nFile is Empty");
w.
else
{
printf("\nA/c Number\tA/c Holder Name Balance\n");
ww
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);
50
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
{
n
bal = atof(acc.balance) - atof(amt);
g.i
if(bal<0)
{
printf("\nRs.%s Not available in your A/c\n",amt);
rin
flag=2;
break;
}
}
flag++; ee
gin
break;
}
En
}
if(flag==1)
{
arn
pos2=ftell(fp);
pos = pos2-pos1;
fseek(fp,-pos,1);
Le
sprintf(amt,"%.2f",bal);
strcpy(acc.balance,amt);
fwrite(&acc,sizeof(acc),1,fp);
w.
}
else if(flag==0)
printf("\nA/c Number Not exits... Check it again");
ww
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++;
51
}
printf("\nThe Number of Account Holder whose Balance less than the Minimum Balance :
%d",flag);
fclose(fp);
break;
case '5' :
fclose(fp);
exit(0);
}
printf("\nPress any key to continue....");
getch();
} while (choice!='5');
}
n
g.i
OUTPUT
rin
1. Add a New Account Holder
2. Display
3. Deposit or Withdraw
ee
4. Number of Account Holder Whose Balance is less than the Minimum Balance
5. Stop
gin
Enter your choice : 1
Enter the Account Number : 547898760
Enter the Account Holder Name : Rajan
Enter the Initial Amount to deposit : 2000
En
4. Number of Account Holder Whose Balance is less than the Minimum Balance
5. Stop
Enter your choice : 4
w.
The Number of Account Holder whose Balance less than the Minimum Balance : 0
ww
RESULT
Thus a C Program for Banking Application was executed and the output was obtained.
52
DATE :
AIM
Create a Railway reservation system in C with the following modules
Booking
Availability checking
Cancellation
Prepare chart
n
.
g.i
rin
ALGORITHM
1. Start
2. Declare variables
ee
gin
3. Display the menu options
4. Read the option.
En
7. Stop
Le
PROGRAM
#include<stdio.h>
w.
#include<conio.h>
int first=5,second=5,thired=5;
struct node
ww
{
int ticketno;
int phoneno;
char name[100];
char address[100];
}s[15];
int i=0;
void booking()
{
printf("enter your details");
53
printf("\nname:");
scanf("%s",s[i].name);
printf("\nphonenumber:");
scanf("%d",&s[i].phoneno);
printf("\naddress:");
scanf("%s",s[i].address);
printf("\nticketnumber only 1-10:");
scanf("%d",&s[i].ticketno);
i++;
}
void availability()
{
int c;
printf("availability cheking");
n
printf("\n1.first class\n2.second class\n3.thired class\n");
g.i
printf("enter the option");
scanf("%d",&c);
switch(c)
rin
{
case 1:if(first>0)
{
printf("seat available\n");
first--; ee
gin
}
else
{
printf("seat not available");
En
}
break;
case 2: if(second>0)
arn
{
printf("seat available\n");
second--;
Le
}
else
{
w.
case 3:if(thired>0)
{
printf("seat available\n");
thired--;
}
else
{
printf("seat not available");
}
break;
default:
54
break;
}
}
void cancel()
{
int c;
printf("cancel\n");
printf("which class you want to cancel");
printf("\n1.first class\n2.second class\n3.thired class\n");
printf("enter the option");
scanf("%d",c);
switch(c)
{
case 1:
n
first++;
g.i
break;
case 2:
second++;
rin
break;
case 3:
thired++;
break;
default: ee
gin
break;
}
printf("ticket is canceled");
}
En
void chart()
{
int c;
arn
for(c=0;c<I;c++)
{
printf(“\n Ticket No\t Name\n”);
Le
printf(“%d\t%s\n”,s[c].ticketno,s[c].name)
}
}
w.
main()
{
int n;
ww
clrscr();
printf("welcome to railway ticket reservation\n");
while(1) {
printf("1.booking\n2.availability cheking\n3.cancel\n4.Chart \n5. Exit\nenter your
option:");
scanf("%d",&n);
switch(n)
{
case 1: booking();
break;
case 2: availability();
55
break;
case 3: cancel();
break;
case 4:
chart();
break;
case 5:
printf(“\n Thank you visit again!”);
getch();
exit(0);
default:
break;
}
}
n
getch();
g.i
}
rin
OUTPUT
availability cheking
1.first class
2.second class
arn
3.thired class
enter the option 1
seat available
1.booking
Le
2.availability cheking
3.cancel
4.Chart
w.
5. Exit
enter your option: 5
ww
RESULT
Thus a C Program for Railway reservation system was executed and the output was
obtained.
56
#include<stdio.h>
#include<conio.h>
void main()
int mat[10][10];
n
int i,j;
g.i
int m,n;
rin
int sumrow,sumcol;
clrscr();
ee
printf("\nTO FIND THE ROW SUM AND COLUMN SUM OF A GIVEN MATRIX:");
gin
printf("\n-- ---- --- --- --- --- ------ --- -- - ----- ------:");
scanf("%d%d",&m,&n);
for(i=0;i<m;i++)
{
Le
for(j=0;j<n;j++)
w.
scanf("%d",&mat[i][j]);
ww
printf("\n\nOUTPUT:");
printf("\n---------------------------------------");
for(i=0;i<m;i++)
sumrow=0;
57
for(j=0;j<n;j++)
sumrow=sumrow+mat[i][j];
printf("\n---------------------------------------");
for(j=0;j<n;j++)
n
sumcol=0;
g.i
for(i=0;i<m;i++)
sumcol=sumcol+mat[i][j];
rin
printf("\nTHE SUM OF %d COLUMN IS %d",j+1,sumcol);
}
ee
gin
printf("\n---------------------------------------");
getch();
En
}
arn
2. Program to read a string and print the first two characters of each word in the
string.
#include<stdio.h>
#include<conio.h>
Le
void main( )
{
char s[100];
w.
int i,l;
clrscr( );
ww
printf(“Enter a string”);
gets(s);
l=strlen(s);
for(i=0;i<l;i++)
{
if(s[i]!=’ ‘ && s[i]=’ ‘)
{
printf(“%c %c”,s[i],s[i+1])
i=i+2;
while(s[i]!=’ ‘)
i++;
58
}
}
getch( );
}
n
getch();
g.i
return 0;
}.
rin
4. Program to calculate Standard Deviation.
#include <stdio.h>
#include <math.h>
ee
float standard_deviation(float data[], int n);
int main()
gin
{
int n, i;
float data[100];
printf("Enter number of datas( should be less than 100): ");
En
scanf("%d",&n);
printf("Enter elements: ");
for(i=0; i<n; ++i)
arn
scanf("%f",&data[i]);
printf("\n");
printf("Standard Deviation = %.2f", standard_deviation(data,n));
Le
return 0;
}
float standard_deviation(float data[], int n)
w.
{
float mean=0.0, sum_deviation=0.0;
int i;
ww
for(i=0; i<n;++i)
{
mean+=data[i];
}
mean=mean/n;
for(i=0; i<n;++i)
sum_deviation+=(data[i]-mean)*(data[i]-mean);
return sqrt(sum_deviation/n);
}
59
n
{
g.i
if ( exp!=1 )
return (base*power(base,exp-1));
}
rin
6. Program to find the ASCII value of a Character.
#include <stdio.h>
int main(){ ee
gin
char c;
printf("Enter a character: ");
scanf("%c",&c); /* Takes a character from user */
printf("ASCII value of %c = %d",c,c);
En
return 0;
}
arn
void main( )
{
int a,b,c,d,big;
w.
clrscr( );
printf(“enter value a”);
scanf(“%d”,&a);
ww
60
8. Program for temperature conversion from Celsius to Fahrenheit and vice versa.
#include<stdio.h>
main()
{
float cel, fah ,c ,f;
clrscr();
printf(“\nEnter the fahrenheit value:”);
scanf(“%f”,&f);
cel=(5.0/9.0)*(f-32);
printf(“Celsius=%d”,cel);
printf(“\nEnter the Celsius value:”);
scanf(“%f”,&c);
n
fah=(9.0/5.0)*c+32;
g.i
printf(“Fahrenheit=%d”,fah);
getch();
rin
}
ee
9. Program to find the reverse and the given Number is Palindrome or not.
#include<stdio.h>
gin
main()
{
unsigned long int a, num, r_ num=0,rem;
En
while(num!=0)
{
rem=num%10;
Le
r_ num=r_ num*10+rem;
num=num/10;
}
w.
61
int n,r;
clrscr();
printf("\nPRG TO FIND nCr USING RECURSION\n");
printf("\n-----------------------------------------------\n");
printf("\nEnter the value of n: ");
scanf("%d",&n);
printf("\nEnter the value of r: ");
scanf("%d",&r);
ncr=fact(n)/(fact(r)*fact(n-r));
printf("\nThe value of %dC%d is %ld",n,r,ncr);
getch();
}
n
g.i
rin
ee
gin
En
arn
Le
w.
ww
62
n
� Primary constants
� Secondary constants
g.i
3. What are the types of C instructions?
There are basically three types of instructions in C:
rin
� Type Declaration Instruction
� Arithmetic Instruction
� Control Instruction
4. What is a pointer?
ee
gin
Pointers are variables which stores the address of another variable. That variable may be a
scalar (including another pointer), or an aggregate (array or structure). The pointed-to
object may be part of a larger object, such as a field of a structure or an element in an
En
array.
5. What is an array?
Array is a variable that hold multiple elements which has the same data type.
arn
struct,or union type. It points to the object for which the member function is called. Static
member functions do not have a “this” pointer.
63
n
� Register
g.i
� Static
rin
Structure constitutes a super data type which represents several different data types in a
single unit. A structure can be initialized if it is static or global.
A destructor is called for a class object when that object passes out of scope or is explicitly
deleted. A destructors as the name implies is used to destroy the objects that have been
created by a constructors. Like a constructor, the destructor is a member function whose
arn
its class. The compiler will implicitly define A::A() when the compiler uses this constructor
to create an object of type A. The constructor will have no constructor initializer and a null
body.
ww
64
� It also reduces the Time to run a program. In other way, it’s directly proportional to
Complexity.
� It’s easy to find-out the errors due to the blocks made as function definition outside the
main function.
n
A Union contains one of the named members at a given time and is large enough to hold
g.i
the largest member. Union element can be of different sizes.
rin
The main difference between an array and a list is how they internally store the data
whereas Array is collection of homogeneous elements. List is collection of heterogeneous
elements.
ee
21. What is the difference between a string copy (strcpy) and a memory copy (memcpy)?
gin
The strcpy() function is designed to work exclusively with strings. It copies each byte of
the source string to the destination string and stops when the terminating null character ()
has been moved.
On the other hand, the memcpy() function is designed to work with any type of data.
En
Because not all data ends with a null character, you must provide the memcpy() function
with the number of bytes you want to copy from the source to the destination.
arn
22. What is the difference between const char*p and char const* p?
const char*p - p is pointer to the constant character. i.e value in that address location is
constant.
Le
const char* const p - p is the constant pointer which points to the constant string, both
value and address are constants.
w.
altered.
� The second argument n specifies the new size. The size may be increased or decreased.
65
n
A recursion function is one which calls itself either directly or indirectly it must halt at a
g.i
definite point to avoid infinite recursion.
rin
� An array holds elements that have the same data type.
� Array elements are stored in subsequent memory locations
� Two-dimensional array elements are stored row by row in subsequent memory
locations.
ee
� Array name represents the address of the starting element
gin
30. Differentiate between for loop and a while loop? What are it uses?
For executing a set of statements fixed number of times we use for loop while when the
number of iterations to be performed is not known in advance we use while loop.
En
A conversion constructor declared with the explicit keyword. The compiler does not use an
explicit constructor to implement an implied conversion of types. Explicit constructors are
simply constructors that cannot take part in an implicit conversion.
w.
66
37. What are macros? What are its advantages and disadvantages?
Macros are abbreviations for lengthy and frequently used statements. When a macro is
called the entire code is substituted by a single line though the macro definition is of
several lines.
The advantage of macro is that it reduces the time taken for control transfer as in case of
function. The disadvantage of it is here the entire code is substituted so the program
becomes lengthy if a macro is called several times.
n
g.i
38. What are register variables? What are the advantages of using register variables?
If a variable is declared with a register storage class, it is known as register variable. The
register variable is stored in the CPU register instead of main memory. Frequently used
rin
variables are declared as register variable as it’s access time is faster.
39. What is storage class? What are the different storage classes in C?
ee
Storage class is an attribute that changes the behavior of a variable. It controls the
lifetime,scope and linkage. The storage classes in c are auto, register, and extern, static,
gin
typedef.
41. In C, why is the void pointer useful? When would you use it?
arn
The void pointer is useful because it is a generic pointer that any pointer can be cast into
and back again without loss of information.
Le
42. What is the difference between the functions memmove() and memcpy()?
The arguments of memmove() can overlap in memory. The arguments of memcpy()
cannot.
w.
67
n
48. What is the difference between syntax vs logical error?
g.i
Syntax Error
� These involve validation of syntax of language.
� Compiler prints diagnostic message.
rin
Logical Error
� Logical error are caused by an incorrect algorithm or by a statement mistyped in such
a way that it doesn’t violet syntax of language.
� Difficult to find.
ee
gin
49. Explain enumerated types.
� Enumerated types allow the programmers to use more meaningful words as values to
a variable.
� Each item in the enumerated type variable is actually associated with a numeric code.
En
program written by the user. The preprocessor directives begines with hash (#) followed
by the command. e.g #include – it is a directive to include file.
ww
68