[go: up one dir, main page]

0% found this document useful (0 votes)
129 views47 pages

Lab Manual

The document contains 7 examples of C programs covering topics like input/output statements, decision making, expressions, calculators, Armstrong numbers, weights calculation, and average height. Each example provides the aim, algorithm, program code, output and result. The programs demonstrate basic programming concepts in C like data types, control structures, functions etc. and show how to write, compile and test simple C programs.

Uploaded by

suganya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
0% found this document useful (0 votes)
129 views47 pages

Lab Manual

The document contains 7 examples of C programs covering topics like input/output statements, decision making, expressions, calculators, Armstrong numbers, weights calculation, and average height. Each example provides the aim, algorithm, program code, output and result. The programs demonstrate basic programming concepts in C like data types, control structures, functions etc. and show how to write, compile and test simple C programs.

Uploaded by

suganya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
You are on page 1/ 47

EX NO 1 (a) PROGRAMS USING I/O STATEMENTS

DATE

AIM
To write a C program using I/O statements.

ALGORITHM
STEP 1: Start the program.
STEP 2: Declare the variable using char datatype.
STEP 3: get the input and display it using printf ().
STEP 4: Stop.

PROGRAM
#include <stdio.h>
int main()
{
int testInteger = 5;
printf("Number = %d", testInteger);
return 0;
}

OUTPUT
Number = 5

RESULT
Thus the C using I/O statements was completed successfully and verified.
EX NO 1 (b) PROGRAMS USING I/O STATEMENTS
DATE

AIM
To write a C program using I/O statements.

ALGORITHM
STEP 1: Start the program.
STEP 2: Declare the variable using char datatype.
STEP 3: get the input and display it using printf ().
STEP 4: Stop.

PROGRAM
#include <stdio.h>
int main()
{
char chr;
printf("Enter a character: ");
scanf("%c",&chr);
printf("You entered %c.",chr);
return 0;
}

OUTPUT
Enter a character: g
You entered g.

RESULT
Thus the C using I/O statements was completed successfully and verified.
EX NO 1 (c) PROGRAMS USING EXPRESSIONS
DATE

AIM
To write a C program using expressions.

ALGORITHM
STEP 1: Start the program.
STEP 2: declare a variable a,b,c,d and result.
STEP 3: calculate result for sub, mul,div
STEP 4: Calculate a+b*c and then a*b+c*d
STEP 5: Stop.

PROGRAM
#include <stdio.h>
int main (void)
{
int a = 100;
int b = 2;
int c = 25;
int d = 4;
int result;
result = a - b; // subtraction
printf ("a - b = %i\n", result);

result = b * c; // multiplication
printf ("b * c = %i\n", result);

result = a / c; // division
printf ("a / c = %i\n", result);

result = a + b * c; // precedence
printf ("a + b * c = %i\n", result);

printf ("a * b + c * d = %i\n", a * b + c * d);


return 0;
}
OUTPUT
a - b = 98
b * c = 50
a/c=4
a + b * c = 150
a * b + c * d = 300

RESULT
Thus the C using expressions was completed successfully and verified.
EX NO 2 (a) DECISION MAKING FOR EVEN OR ODD
DATE

AIM
To write a C Program to find whether the given number is even or odd number.

ALGORITHM
STEP 1: Start the Program.
STEP 2: Initialize the variables.
STEP 3: Using the expression (n% 2==0) find the even or odd numbers.
STEP 4: If the given number is divisible by 2 and the result is zero then print it is even.
STEP 5: If the number is not divided by 2 then it is odd number.
STEP 6: Stop the program.

PROGRAM

#include<stdio.h>
int main()
{
int n;
printf("Enter an integer ");
scanf("%d",&n);
if ( n%2 == 0 )
printf("Even ");
else
printf("Odd ");
return 0;
}

OUTPUT
Enter an integer : 6
Even
RESULT:
Thus the ‘C’ program to find even or odd number was created and verified successfully.

EX NO 2 (b) DECISION MAKING FOR REVERSE OF NUMBER


DATE

AIM
To write a C Program to find reverses of number.

ALGORITHM:

STEP 1: Start the program.


Step 2: Initialize the variables n, sum=0, i=0.
Step 3: while the given number is greater than zero. Perform the following for reverse
i.e., i=n%10;
Sum=sum*10+i;
n=n/10;
Step 4: Print the reversed number.
Step 5: Stop the program.

PROGRAM

#include<stdio.h>
Void main ()
{
int n,sum=0,i=0;
printf("Enter the number");
scanf("%d",&n);
while (n>0)
{
i=n%10;
sum=sum*10+i;
n=n/10;
}
printf("The reversed number is %d",sum);
}

OUTPUT

Enter the number: 5564


The reversed number is: 4655
RESULT

Thus the ‘C’ program to reverse number was created and verified successfully.
EX NO 3 LEAP YEAR OR NOT
DATE

AIM
To write a program to find whether the given year is leap year or Not? (Hint: not every centurion year
is a leap.

ALGORITHM
STEP 1: Start
STEP 2: Read year
STEP 3: if (year%4==0 && year%100! =0 || year%400==0) then go to step 4
STEP 4: else go to step 5
STEP 5: Print a leap year
STEP 6: Print a leap year
STEP 7: Stop.

PROGRAM
#include <stdio.h>
#include <conio.h>
void main()
{
int year;
clrscr();
printf("Enter the Year (YYYY) : ");
scanf("%d",&year);
if(year%4==0 && year%100!=0 || year%400==0)
printf("\nThe Given year %d is a Leap Year");
else
printf("\nThe Given year %d is Not a Leap Year");
getch();
}

OUTPUT
Enter the Year (YYYY): 1991

The Given year 1991 is Not a Leap Year

RESULT
Thus the C Program to find whether the given year is leap year or not was completed successfully
and verified.
EX NO 4 DESIGN A CALCULATOR
DATE:

AIM
To design a calculator to perform the operations, namely, addition, subtraction, multiplication, division
and square of a number.

ALGORITHM
STEP 1: Start
STEP 2: Get two numbers to perform calculator operations.
STEP 3: Using switch case design a calculator, get a char to select the case.
STEP 4: case ‘+’ to perform addition, case ‘-‘ to perform subtraction and so on.
STEP 5: Perform the operation based on the case selection.
STEP 6: Stop

PROGRAM
/* Design a Calculator to perform Addition, Subtraction, Multiplication,
Division and Square of a number */
#include <stdio.h>
#include <conio.h>
void main()
{
int fn,sn,c;
float r;
char c1;
clrscr();
printf("Enter the First Number : ");
scanf("%d",&fn);
printf("\nEnter the Second Number : ");
scanf("%d",&sn);
do
{
printf("\nWhich operations you want to perform (+,-,*,/,s)\n");
c=getch();
switch(c)
{
case '+':
r = fn+sn;
break;
case '-':
r = fn-sn;
break;
case '*':
r = fn*sn;
break;
case '/':
r = fn/(float)sn;
break;
case 's':
r = fn*fn;
break;
} // switch
if(c=='/')
printf("\nResult = %f\n",r);
else
printf("\nResult = %.f\n",r);
printf("\ndo you want continue (y/n) :");
c1 = getch();
} while (c1=='y' || c1=='Y');
} // main

OUTPUT
Enter the first number and second number
5
10

You type + for addition , - for subtraction , * for multiplication , / for division & s for square of the first
number
-
Result = 5
RESULT
Thus the C Program for design a calculator to perform the operations, namely, addition,
subtraction, multiplication, division and square of a number was successfully completed and verified.

EX NO 5 ARMSTRONG NUMBER OR NOT


DATE:

AIM
To check whether a given number is Armstrong number or not.

ALGORITHM
STEP 1: Take integer variable Arms
STEP 2 :Assign value to the variable
STEP 3 :Split all digits of Arms
STEP 4 :Find cube-value of each digits
STEP 5 :Add all cube-values together
STEP 6: Save the output to Sum variable
STEP 7: If Sum equals to Arms print Armstrong Number
STEP 8: If Sum not equals to Arms print Not Armstrong Number.

PROGRAM
#include <stdio.h>
#include <conio.h>
#include <math.h>
void main()
{
long int num,result;
long int armstrong(long);
int base;
clrscr();
printf("Enter the given number : ");
scanf("%ld",&num);
result = armstrong(num);
if(result==num)
printf("\nThe given number %ld is an Armstrong number",num);
else
printf("\nThe given number %ld is not an Armstrong number",num);
getch();
} // main
long int armstrong(long int num)
{
long int num1=num,res;
double r,count=0;
double sum=0.0;
for(;num1!=0;count++,num1/=10);
num1=num;
while(num1!=0)
{
r = num1%10;
sum = sum+pow(r,count);
num1 = num1/10;
}
res = sum;
return res;
}

OUTPUT
Enter the given number
The given number 153 is an Armstrong number
RESULT
Thus the C Program to check whether a given number is Armstrong number or not was
successfully completed and verified.

EX NO 6 SUM OF WEIGHTS
DATE

AIM
To find sum of weights based on the following conditions for the given set of numbers like <10,
36, 54, 89, 12, 27>,
 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
STEP 1: Start the program.
STEP 2: Declare the variable nArray[50],wArray[50],nelem,sq,i,j,t.
STEP 3: Enter the number of elements in an array.
STEP 4: Sorting an array using for () and if(nArray[i] > nArray[j])
STEP 5: Calculate the weight

PROGRAM
#include <stdio.h>
#include <math.h>
void main()
{ int nArray[50],wArray[50],nelem,sq,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]);
// Sorting an array
for(i=0;i<nelem;i++)
for(j=i+1;j<nelem;j++)
if(nArray[i] > nArray[j])
{
t = nArray[i];
nArray[i] = nArray[j];
nArray[j] = t; }
//Calculate the weight
for(i=0; i<nelem; i++)
{ wArray[i] = 0;
// sq =(int) sqrt(nArray[i]);
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;
}
for(i=0; i<nelem; i++)
printf("<%d,%d>", 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: 3

Enter 3 elements
10
34
23
<10,0><23,3><34,0>

RESULT
Thus the C Program to find sum of weights was completed and verified successfully.
EX NO 7 AVERAGE HEIGHT
DATE:

AIM
To populate an array with height of persons and find how many persons are above the average
height.

PROGRAM
/* Get a Height of Different Persons and find how many of them
are are above average */
#include <stdio.h>
#include <conio.h>
void main()
{
int i,n,sum=0,count=0,height[100];
float avg;
clrscr();
//Read Number of persons
printf("Enter the Number of Persons : ");
scanf("%d",&n);
//Read the height of n persons
printf("\nEnter 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;
//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

Number of Person : 5

Persons Heights are : 150 155 162 158 154

Average Height is : 155.8

Number of persons above average : 2


RESULT
Thus the C Program to populate an array with height of persons and find how many persons are
above the average height was completed and verified successfully.

EX NO 8 TWO DIMENSIONAL ARRAY


DATE:

AIM
To populate a two dimensional array with height and weight of persons and compute the Body
Mass Index of the individuals.
/* As Indians BMI rate be not more than 25
Starvation - less than 15
Underweight - 15 to 17
Healthy range - 18 to 25
Overweight - 26 to 30
Obese - 31 to 35
Severely Obese - Above 35
*/

ALGORITHM
STEP 1: Start the program.
STEP 2: Declare an two dimensional array of variable stu and index[100].
STEP 3: Using for () enter the height and weight of students.
STEP 4: h = (float)(stu[i][0]/100.0);
index[i] = (float)stu[i][1]/(float)(h*h); //calculate the height and weight
STEP 5: if the index[i] is between 14 and 18, then the student is underweight.
STEP 6: if the index[i] is between 17 and 26, then the student is underweight.
STEP 7: if the index[i] is between 25 and 31, then the student is underweight.
STEP 8: if the index[i] is between 30 and 36, then the student is underweight.
STEP 9: otherwise, print student is obese.
STEP 10: Stop the program.

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");
} // for loop
getch();
}

OUTPUT
Enter the number of students: 6
Enter the Height(cm) and Weight(kg) of student 1 140 20
Enter the Height(cm) and Weight(kg) of student 2 140 35
Enter the Height(cm) and Weight(kg) of student 3 150 45
Enter the Height(cm) and Weight(kg) of student 4 140 60
Enter the Height(cm) and Weight(kg) of student 5 140 70
Enter the Height(cm) and Weight(kg) of student 6 140 80

RESULT
Thus the C Program to populate a two dimensional array with height and weight of persons and
compute the Body Mass Index of the individuals was completed and verified successfully.

EX NO 9 REVERSE A STRING
DATE:

AIM
To find the reverse without changing the position of special characters for the given a string
―a$bcd./fg‖

ALGORITHM
STEP 1: Start the program.
STEP 2: Using pointer variable swap a,b with t (temp) variable.
STEP 3: Create a function prototype inside main function and give the input string.
STEP 4: Using reverse function reverse the input string.
STEP 5: Initialize left and right pointers.
STEP 6: Traverse string from both ends until ‘l’ and ‘r’.
STEP 7: Ignore special characters using isalpha().
STEP 8: To check x is alphabet or not if it an alphabet then returns 0 else 1.
STEP 9: Stop the program.

PROGRAM
#include <stdio.h>
#include <string.h>
#include <conio.h>
void swap(char *a, char *b)
{
char t;
t = *a;
*a = *b;
*b = t;
}

// Main program
void main()
{
char str[100];
// 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("Reverse String : %s",str);
getch();
}

void reverse(char str[100])


{
// Initialize left and right pointers
int r = strlen(str) - 1, l = 0;

// Traverse string from both ends until


// 'l' and 'r'
while (l < r)
{
// Ignore special characters
if (!isAlpha(str[l]))
l++;
else if(!isAlpha(str[r]))
r--;

else
{
swap(&str[l], &str[r]);
l++;
r--;
}
}
}
// To check x is alphabet or not if it an alphabet then return 0 else 1
int isAlpha(char x)
{
return ( (x >= 'A' && x <= 'Z') ||
(x >= 'a' && x <= 'z') );
}

OUTPUT
Enter the Given String: -a$bcd./fg||
Reverse string :-g$fdc./ba||

RESULT
Thus the C Program to find the reverse without changing the position of special characters for the
given a string was completed and verified successfully.

EX NO 10 NUMBER CONVERSION
DATE:

AIM
To convert the given decimal number into binary, octal and hexadecimal numbers using user
defined functions.

ALGORITHM:
STEP 1: Start the program.
STEP 2: Using pointer variable swap the variables with temporary variables.
STEP 3: Create a function as reverse and reverse the string.
STEP 4: Convert the given decimal input intobinary, octal and hexa decimal values using convert function
().
STEP 5: Stop the program.

PROGRAM
#include <stdio.h>
#include <conio.h>
void swap(char *s1, char *s2)
{
char temp;
temp = *s1;
*s1 = *s2;
*s2 = temp;
}
void reverse(char *str, int length)
{
int start = 0;
int end = length -1;
while (start < end)
{
swap(&str[start], &str[end]);
start++;
end--;
}
}
char* convert(int num, char str[100], int base)
{
int i = 0;
if (num == 0)
{
str[i++] = '0';
str[i] = '\0';
return str;
}
while (num != 0)
{
int rem = num % base;
str[i++] = (rem > 9)? (rem-10) + 'a' : rem + '0';
num = num/base;
}
str[i] = '\0'; // Append string terminator
// Reverse the string
reverse(str, i);
return str;
}
void main()
{
char str[100];
int n;
clrscr();
printf("Enter the given decimal number : ");
scanf("%d",&n);
printf("The Binary value : %s\n",convert(n,str,2));
printf("The Octal value : %s\n",convert(n,str,8));
printf("The Hexa value : %s\n",convert(n,str,16));
getch();
}

OUTPUT
Enter the given decimal number : 120
The Binary value :1111000
The Octal value :170
The Hexa value :78

RESULT
Thus the C Program to convert the given decimal number into binary, octal and hexadecimal
numbers using user defined functions was completed and verified successfully.

EX NO 11 BUILT IN FUNCTIONS
DATE:
AIM
To write a C program using built-in functions to do the following
a. Find the total number of words.
b. Capitalize the first word of each sentence.
c. Replace a given word with another word.

ALGORITHM

Step:1 Start
Step:2 Declare variables
Step:3 Read the text.
Step:4 Display the menu options
Step:5 Compare each character with tab char ‘\t’ or space char ‘ ‘ to count no of words
Step: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. (! . ?)
Step:7 Replace the word in the text by user specific word if match.
Step:8 Display the output of the calculations .
Step:9 Repeat the step 4 till choose the option stop.
Step 10. Stop

PROGRAM

#include <stdio.h>
#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);
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;
/* Runs a loop till end of text */
while(str[i] != '\0')
{
/* If the current character(str[i]) is white space */
if(str[i]==' ' || str[i]=='\n' || str[i]=='\t')
{
words++;
}
i++;
}
printf("\nTotal number of words = %d", words); break;

case '2' :

i = 0;
/* Runs a loop till end of text */
while(str[i] != '\0')
{
/* Checks to see if a character is a punctuation mark used to denote
the end of a sentence. (! . ?) */
if(str[i]=='!' || str[i]=='.' || str[i]=='?')
{
i++;
while(str[i]!=' ' || str[i]!='\n' || str[i]!='\t || str[i] != '\0'’)
{putchar (toupper(str[++i])); i++;
}
}
else
putchar (str[i]);
i++;
}
break;
case '3' :

/*Get the search and replace string from the user.

 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.*/

printf("\nPlease enter the string to search: ");


fflush(stdin);
gets(s_string);

printf("\nPlease enter the replace string ");


fflush(stdin);
gets(r_string);

replace(str, s_string, r_string);


puts(str);
break;
case '4' :
exit(0);
}
printf("\nPress any key to continue....");
getch();
}
while(choice!=’4’);

return 0;
}

void replace(char * str, char * s_string, char * r_string) {


//a buffer variable to do all replace things char
buffer[200];
//to store the pointer returned from strstr char *
ch;

//first exit condition


if(!(ch = strstr(str, s_string)))
return;

//copy all the content to buffer before the first occurrence of the search string
strncpy(buffer, str, ch-str);

//prepare the buffer for appending by adding a null to the end of it


buffer[ch-str] = 0;

//append using sprintf function


sprintf(buffer+(ch -str), "%s%s", r_string, ch + strlen(s_string));

//empty str for copying


str[0] = 0;
strcpy(str, buffer);
//pass recursively to replace other occurrences return
replace(str, s_string, r_string);
}
OUTPUT
Enter any text:
I like C and C++ programming!

1.Find the total number of words


2.Capitalize the first word of each sentence
3.Replace a given word with another word
4.Stop
Enter your choice : 1
Total number of words = 6

Press any key to continue....


1. Find the total number of words
2. Capitalize the first word of each sentence
3. Replace a given word with another word
4. Stop
Enter your choice : 4

RESULT

Thus a C Program String operations was executed and the output was obtained.
EX NO 12 TOWERS OF HANOI
DATE:

AIM
To Write a C Program to solve towers of Hanoi using recursion.
/*
Rules of Tower of Hanoi:

Only a single disc is allowed to be transferred at a time.


Each transfer or move should consist of taking the upper disk from one of the stacks and then placing it on
the top of another stack i.e. only a topmost disk on the stack can be moved.
Larger disk cannot be placed over smaller disk; placing of disk should be in increasing order.
*/

PROGRAM
#include <stdio.h>
#include <conio.h>
void towerofhanoi(int n, char from, char to, char aux)
{
if (n == 1)
{
printf("\n Move disk 1 from Peg %c to Peg %c", from, to);
return;
}
towerofhanoi(n-1, from, aux, to);
printf("\n Move disk %d from Peg %c to Peg %c", n, from, to);
towerofhanoi(n-1, aux, to, from);
}

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;
}
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
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 the C Program to solve towers of Hanoi using recursion was completed and verified and
completed successfully.

EX NO 13 PASS BY REFERENCE
DATE:

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

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-1;i++)
for(j=0;j<num-i-1;j++)
if(arr[j] > arr[j+1])
{
temp=arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}

OUTPUT
Enter the number of elements in an array: 4

Enter the Array elements:


23
45
34
21

After Sorting…
21
23
34
45
RESULT:

To write a C Program to sort the list of numbers using pass by reference was verified and
completed successfully.

EX NO 14 STRUCTURES AND POINTERS


DATE:

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

PROGRAM
#include<stdio.h>
#include<conio.h>
#include "stdlib.h"
struct emp
{
int empno ;
char name[10], answer ; int
bpay, allow, ded, npay ; struct
emp *next;
} ;
void main()
{
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 : ") ;
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;
}
else
{
current_ptr->next = (struct emp *) malloc (sizeof(struct emp));
current_ptr = current_ptr->next;
}

}
}
printf("\nEmp. No. Name \t Bpay \t Allow \t Ded \t Npay \n\n") ;
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, current_ptr->name,
current_ptr->bpay, current_ptr->allow, current_ptr->ded,
current_ptr->npay) ;
current_ptr=current_ptr->next;
}
getch() ;
}

OUTPUT

Enter the number of employees : 2


Enter the employee number : 101 Enter
the name : Arun
Enter the basic pay, allowances & deductions : 5000 1000 250
Enter the employee number : 102
Enter the name : Babu
Enter the basic pay, allowances & deductions : 7000 1500 750 Emp.No. Name
Bpay Allow Ded Npay
101 Arun 5000 1000 250 5750
102 Babu 7000 1500 750 7750

RESULT

Thus a C Program Salary slip of employees was executed and the output was obtained.

EX NO 15 STRUCTURES AND FUNCTIONS


DATE:

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

PROGRAM
#include<stdio.h>
#include<conio.h>
struct stud
{
int rollno, s1, s2, tot ;
char name[10] ;
float avg ;
} s[10] ;
void main()
{
int i, n ;
clrscr() ;
printf("Enter the number of students : ") ;
scanf("%d", &n) ;
for(i = 0 ; i < n ; i++)
{
printf("\nEnter the roll number : ") ;
scanf("%d", &s[i].rollno) ;
printf("\nEnter the name : ") ;
scanf("%s", s[i].name) ;
printf("\nEnter the marks in 2 subjects : ") ;
scanf("%d %d", &s[i].s1, &s[i].s2) ;
s[i].tot = s[i].s1 + s[i].s2 ;
s[i].avg = s[i].tot / 2.0 ;
}
printf("\nRoll No. Name \t\tSub1\t Sub2\t Total\t Average\n\n") ;
for(i = 0 ; i < n ; i++)
{
printf("%d \t %s \t\t %d \t %d \t %d \t %.2f \n",
s[i].rollno,s[i].name,s[i].s1,s[i].s2,s[i].tot,s[i].avg);
}
getch() ;
}

OUTPUT
Enter the number of students : 2
Enter the roll number : 101
Enter the name : Arun
Enter the marks in 2 subjects : 75 85
Enter the roll number : 102
Enter the name : Babu
Enter the marks in 2 subjects : 65 75
Roll No. Name Sub1 Sub2 Total Average
101 Arun 75 85 160 80.00
102 Babu 65 75 140 70.00
RESULT
Thus the C Program to compute internal marks of students for five different subjects using
structures and functions was verified and completed successfully.

EX NO 16 RANDOM ACCESS FILE


DATE:

AIM
To write a C Program to insert, update, delete and append telephone details of an individual or a company
into a telephone directory using random access file.

#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)


{
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: Ram
Last Name: Mohan
Phone Number (XXX-XXX-XXXX): 717-675-0909

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? 5


You have chosen to exit the Phonebook.

RESULT

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


EX NO 17 SEQUENTIAL ACCESS FILE.
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.
/* Count the number of account holders whose balance is less than the minimum balance using sequential
access file.
*/

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
3. Deposit or Withdraw
4. Number of Account Holder Whose Balance is less than the Minimum Balance
5. Delete All
6. Stop
Enter your choice : 1
Enter the Account Number : 1233
Enter the Account Holder Name: Anu
Enter the Initial Amount to deposit :2000

Press any key to continue…..

Enter your choice : 2


A/C Number A/C Holder Name Balance
2344 Anu 2345
1233 Anu 2000

Press any key to continue…..


Enter your choice : 6

RESULT

Thus the C program to count the number of account holders whose balance is less than the
minimum balance using sequential access file was completed and verified successfully.
EX.No. : 18 Railway reservation system
DATE :

AIM
Create a Railway reservation system in C with the following modules
 Booking
 Availability checking
 Cancellation
 Prepare chart

.
ALGORITHM

1. Start
2. Declare variables
3. Display the menu options
4. Read the option.
5. Develop the code for each option.
6. Display the output of the selected option based on existence .
7. Stop

PROGRAM

#include<stdio.h>
#include<conio.h>
int first=5,second=5,thired=5;
struct node
{
int ticketno;
int phoneno;
char name[100]; char
address[100];
}s[15];

int i=0;
void booking()
{
printf("enter your details");
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");
printf("\n1.first class\n2.second class\n3.thired class\n");
printf("enter the option");
scanf("%d",&c);
switch(c)
{
case 1:if(first>0)
{
printf("seat available\n");
first--;
}
else
{
printf("seat not available");
}
break;
case 2: if(second>0)
{
printf("seat available\n");
second--;
}
else
{
printf("seat not available");
}
break;
case 3:if(thired>0)
{
printf("seat available\n");
thired--;
}
else
{
printf("seat not available");
}
break;
default:
55
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:
first++;
break;
case 2:
second++;
break;
case 3:
thired++;
break;
default:
break;
}
printf("ticket is canceled");
}
void chart()
{
int c;
for(c=0;c<I;c++)
{
printf(“\n Ticket No\t Name\n”);
printf(“%d\t%s\n”,s[c].ticketno,s[c].name)
}
}
main()
{
int n;
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();
56
break;
case 3: cancel(); break;
case 4: chart();
break; case 5:
printf(“\n Thank you visit again!”); getch();
exit(0);
default:
break;
}
}
getch();
}

OUTPUT

welcome to railway ticket reservation 1.booking


2.availability cheking 3.cancel
4. Chart
5. Exit
enter your option: 2
availability cheking 1.first
class

2.second class 3.thired


class enter the option 1
seat available 1.booking

2.availability cheking 3.cancel


4. Chart
5. Exit
enter your option: 5 Thank you
visit again!

RESULT

Thus a C Program for Railway reservation system was executed and the output was obtained.

57

You might also like