Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Xbc106 Lab_Programming in C_Manual.doc

The document is a lab manual for the B.Sc Computer Science first semester course on Programming in C, detailing 11 lab exercises with procedures, code, and sample outputs. It aims to enhance students' understanding of programming concepts and algorithms in C, enabling them to create applications and solve real-time problems. The manual includes various programming tasks such as formatted I/O operations, control structures, loops, arrays, strings, functions, structures, pointers, and file operations.

Uploaded by

gokulvarma985
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Xbc106 Lab_Programming in C_Manual.doc

The document is a lab manual for the B.Sc Computer Science first semester course on Programming in C, detailing 11 lab exercises with procedures, code, and sample outputs. It aims to enhance students' understanding of programming concepts and algorithms in C, enabling them to create applications and solve real-time problems. The manual includes various programming tasks such as formatted I/O operations, control structures, loops, arrays, strings, functions, structures, pointers, and file operations.

Uploaded by

gokulvarma985
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 88

B.

Sc Degree Course

B.Sc Computer Science,

(First Semester)

Department of Software Engineering

LAB MANUAL
XBC106- PROGRAMMING IN C LAB
Department of Software Engineering
Periyar Nagar,Vallam,Thanjavur-613 403,Tamil Nadu India

Page : 1
XBC106- PROGRAMMING IN C LAB

Certificate

This Lab Manual is submitted to the I Semester B.Sc Computer Science students for their
“XBC106- PROGRAMMING IN C LAB”. This manual consists of 11 lab exercises. Each
exercise has been explained with procedures, code and sample outputs. Students to practice and to
enrich their knowledge in C, 50 programs are given as sample programs for examination practice.

Prepared by Checked by
Dr.K.Thiyagarajan Dr.D.Magesh Kumar
Asst.Prof Head of the Department

Page : 2
COURSE DETAILS

Course Objective(s)
● Students will gain the ability to implement the algorithms in C.

● Getting more knowledge about Programming concepts.

Learning outcome
At the end of the course student will be able to:

1. Create simple applications

2. Learn various concepts of C language.

3. Understand real time problems.

4. Design and solve the problem using C concepts.

Page : 3
Table of Content
Sl.No List of Programs Page No.
1 Program to implement formatted I/O operations& unformatted I/O operations
1.1 Program to find area and circumference of a circle
1.2Program to find simple interest and compound interest
1.3 To convert temperature from degree Centigrade to Fahrenheit,
2 Implement Various Control Structures
2.1 Find whether given number is Even or Odd,
2.2 Find the greatest of Three numbers
2.3 Write a program to find whether the given year is leap year or Not
3 Program to implement various loop structures
3.1 Find the greatest of N numbers.
3.2 Program to print prime numbers between 1 and 100
3.3 To write a C Program to Check whether a given number is Armstrong number or not
4 Program to Implement Multiple branching Statement
4.1 Write a Program to display Monday to Sunday using switch statement
4.2 To write a C Program to Design a calculator to perform the operations, namely, addition,
subtraction, multiplication, division and square of a number.
5 Program to implement one dimensional and two dimensional arrays
5.1 Program to sort the elements in an array
5.2 Program to Addition and subtraction two matrices
4.3 Program to multiply two 2 x 2 matrices
6. String manipulations using string functions
6.1 Find the String length, string comparison, string copy on a given string
6.2 Find the total number of words in the paragraph
6.3 Program to check whether a string is a palindrome or not
7. Program to implement calling the function
7.1 Program to swap two numbers using call by values
7.2 Program to swap two numbers using call by reference
8. Program to implement Structures
8.1 To Create a simple employee data using Structure
8.2 To Create a simple Student data using Structure with array
8.3 Program to calculate EB bill for 5 consumers using structure with member
variables for customer name, customer No, previous reading, current reading, units
consumed, and bill amount. The Electricity bill is to be calculated with the
following condition
Units Consumed Rate/unitUnits Consumed Rate/unit
Upto 100 Re.1/- Above 100 and below 201 Rs.2/-
Above 200 and below 501 Rs.3/-Above 500 Rs.5/-Prepare
and display the EB bill with customer name, units consumed and chargeable amount.
9 Program to implement Pointers
9.1Write a program to swap two numbers using pointers
9.2 Demonstrates pointer arithmetic by accessing array elements using pointers:
9.3 Program to implement pointer to function
9.4 Program to implement dynamic memory allocation
10 Program to implement various file operations in a standard file
Program to copy the content of one file into another file
Page : 4
Page : 5
1. Program to implement formatted I/O operations

1.1 Program to find area and circumference of a circle


AIM :

To write a C program to find area and circumference of a circle.

ALGORITHM:

Step 1 : start
Step 2 : read radius r
Step 3 : compute area 3.14 * r * r
Step 4 : compute circumference 2 * 3.14 * r
Step 5 : display area
Step 6 : display circumference
Step 7 : stop.

PROGRAM:

#include<stdio.h>
#include<conio.h>
void main()
{
float r, area,cir;
clrscr();printf("Enter the radius of the circle:");
scanf(“%f”,&r);
area = 3.14 * r * r;
cir = 2 * 3.14 *r;
printf(“Area of the circle = %6.2f”, area);
printf(“Circumference of the circle = %6.2f”, cir);
getch();
}

Page : 6
Sample Output:
Enter the radius of the circle: 1.4
Area of the circle = 6.15
Circumference of the circle = 8.79

RESULT:

Thus the area and circumference of the circle were calculated.

Page : 7
1.2 Program to find simple interest and compound interest
AIM :

To write a C program to find simple interest and compound interest.

ALGORITHM:

Step 1 : start
Step 2 : read p, n, r;
Step 3 : compute si = p * n * r
Step 4 : compute ci = p*(1 + r/100)n
Step 5 : display si
Step 6 : display ci
Step 7 : stop.
PROGRAM:

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float p, n, r, si, ci;
clrscr();
printf("Enter the principal, interest and no. of years:");
scanf(“%f%f%f”,&p,&n,&r);
si = p * n * r;
ci = p * pow((1 + r/100),n);
printf(“Simple Interest = %f”, si);
printf(“Compound Interest = %f”, ci);
getch();
}

Page : 8
Sample Output:

Enter the principal, interest and no. of years:


1000
10
2
Simple Interest = 200.000000
Compound Interest = 1210.000000

RESULT:

Thus the simple interest and compound interest were calculated.

1.3 To convert temperature from degree Centigrade to Fahrenheit

Page : 9
Aim
To convert Celsius to Fahrenheit, we will be using the same C to F formula given below

°F = °C × (9/5) + 32

ALGORITHM:

Step 1 : Start
Step 2: Get input the temperature value in Celsius.
Step 3: compute °F = °C × (9/5) + 32
Step 4: display °F
Step 5 : stop.

PROGRAM:

#include <stdio.h>
int main()
{
float celsius, fahrenheit;
printf("Enter temperature in Celsius: ");
scanf("%f", &celsius);
//celsius to fahrenheit conversion formula
fahrenheit = (celsius * 9 / 5) + 32;
printf("%.2f Celsius = %.2f Fahrenheit", celsius, fahrenheit);
return 0;
}

Sample Output:

Page : 10
Enter temperature in Celsius: 10
10.00 Celsius = 50.00 Fahrenheit

RESULT:

Thus a C Program using i/o statements and expressions was executed and the Fahrenheit output
was obtained

Page : 11
2. Implement Various Control Structures.

2.1 Find whether given number is Even or Odd

Aim

Finding that a given number is even or odd


ALGORITHM:

Step 1 : Start
Step 2: Take value for integer variable n
Step 3 : Perform n modulo 2 and check result if output is 0
Step 4 : If true print ‘n’ is even
Step 5 : If false print ‘n’ is odd
Step 6 : stop.

Page : 12
PROGRAM:

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

Output:

RESULT:

Thus a C Program using decision-making constructs was executed and the output was
obtained.

Page : 13
2.2 Find the greatest of Three numbers

Aim

Finding Input three integers from the user and find the largest number
among them
ALGORITHM:

Step 1 : Start
Step 2: Ask the user to enter three integer values.
Step 3: Read the three integer values in num1, num2, and num3 (integer variables).
Step 4: Assign big = num1 then
Step 5: Check if num2 is greater than big.
If true, then assign big = num2 then
Step 6: check if num3 is greater than big .
If true, then assign big = num3
Step 7: print ‘big’ as the greatest number.
Step 8: Stop

PROGRAM:

#include <stdio.h>
void main()
{
int num1,num2,num3,big;
printf ("Enter a Value of three numbers num1,num2 and num3");
scanf(“%d%d%d”,&num1, &num2, &num3);

big= num1;
if (big < num2)
big = num2;
if (big < num3)
big = num3;
printf("Biggest among %d, %d, and %d is: %d", num1, num2, num3,big);

Page : 14
Sample Output:

Enter a Value of three numbers num1,num2 and num3 :


50
77
65
Biggest among 50,77 and 65 is: 77

RESULT:

Thus a C Program for Biggest number checking was executed and the output was obtained

Page : 15
2.4 Write a C Program to find whether the given year is leap year or Not

Aim
To write a C Program to find whether the given year is leap year or Not

ALGORITHM

Step 1 : Start
Step 2 : Read the Input .
Step 3 : Take a year as input and store it in the variable year.
Step 4 : Using if,else statements to,
4.1 Check whether a given year is divisible by 400.
4.2 Check whether a given year is divisible by 100.
4.3 Check whether a given year is divisible by 4.
Step 5 : If the condition at step 5.a becomes true, then print the ouput as
“It is a leap year”.
Step 6 : If the condition at step 5.b becomes true, then print the ouput as
“It is not a leap year”.
Step 7 : If the condition at step 5.c becomes true, then print the ouput as
“It is a leap year”.
Step 8 : If neither of the condition becomes true, then the year is not a leap year and
print the same.
Step 9 : Display the output
Step 10: Stop

Page : 16
PROGRAM:
#include<stdio.h>
#include<conio.h>

void main()
{
int year;
printf("Enter a year \n");
scanf("%d", &year);
if ((year % 400) == 0)
printf("%d is a leap year \n", year);
else if ((year % 100) == 0)
printf("%d is a not leap year \n", year);
else if ((year % 4) == 0)
printf("%d is a leap year \n", year);
else
printf("%d is not a leap year \n", year);
}

Output:

RESULT:

Thus a C Program for Leap year checking was executed and the
output was obtained.

Page : 17
3 Program to implement various loop structures

3.1 Find the greatest of N numbers.

Aim

To write a C Program to find greatest of N numbers

ALGORITHM

Step 1 : Start
Step 2: Create a local variable n, lar(Larger_Number) and initiate it to arr[100] to store the
maximum among the list
Step 3: Initiate an integer i = 0 and repeat steps 4 to 5 till i reaches the end of the array.
Step 4: Enter Numbers of terms in Array input in 'n'
Step 5: Enter input element of arr[0]
Step 6: Compare arr[i] with max.
Step 7: If arr[i] > max, update max = arr[i].
Step 8: Increment i once.
Step 9: Display Larger_Number (After the iteration is over)
Step 10: Stop

Page : 18
PROGRAM:

# include < stdio.h >


void main( )
{
int a[120], n, i, lar=0 ;
printf(" Enter the Numbers of terms in Array: ") ;
scanf("%d ",& n) ;
printf("\n Enter the Numbrs in Array: \n") ;
for ( i = 1 ; i < = n ; i++)
{
scanf("%d ",& a[i]) ;
}
for ( i = 1 ; i < = n ; i++)
{
if ( a[i] > lar )
{
lar = a[i] ;
}
}
printf("\n The Larger Number is : %d",lar) ;
}

RESULT:

Thus a C Program for Find the greatest of N numberschecking was executed and the output was
obtained

Page : 19
3.2 Write a program to print prime numbers between 1 and 100
AIM :

To write a C program to print the prime numbers between 1 and 100.

ALGORITHM:

Step 1: Start
Step 2: While (N < 100)
I=2, I<Num
Step 4: While (I<N)
Step 5: IF N%I == 0
goto Step 7
Step 6: I++
Step 7: IF I==NUM
Print NUM
Step 7: N++
Step 8: Stop
PROGRAM:

#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,f;
clrscr();
printf("Prime numbers between 1 and 100 are:";
for(i=2;i<=100;i++)
{
f=0;
for(j=2;j<i;j++)
{
if(i%j==0)
{
f=1;
break;
}
}
if(f==0)
printf(“ %d”,i);
}
getch();
}

Page : 20
Sample Output:

Prime numbers between 1 and 100 are:

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

RESULT:

Thus the prime numbers between a and 100 is printed.

3.3 To write a C Program to Check whether a given number is Armstrong


number or not

Page : 21
AIM

To write a C Program to Check whether a given number is Armstrong number or not

ALGORITHM:

Step 1: start
Step 2. Declare variables
Step 3:Read the Input number.
Step 4: Calculate sum of cubic of individual digits of the input.
Step 5. Match the result with input number.
Step 6. If match, Display the given number is Armstrong otherwise not.
Step 7. Stop

Program
/*
* C Program to Check whether a given Number is Armstrong
*/
#include <stdio.h>
#include <math.h>
void main()
{
int number, sum = 0, rem = 0, cube = 0, temp;
printf ("enter a number");
scanf("%d", &number);
temp = number;
while (number != 0)
{
rem = number % 10;
cube = pow(rem, 3);
sum = sum + cube;
number = number / 10;
}
if (sum == temp)
printf ("The given no is armstrong no");
else
printf ("The given no is not a armstrong no");
}

Output :

Page : 22
RESULT

Thus a C Program for Armstrong number checking was executed and the output
was obtained.

Page : 23
4 Program to implement multiple branching Statement

4.1 Write a Program to display Monday to Sunday using switch statement.

Aim:
The aim of this program is to take a user-input number representing a day of the week (1
to 7) and use a switch statement to display the corresponding day's name.

Algorithm:
Step 1: Start the program.
Step 2: Declare an integer variable day.
Step 3: Print a prompt to the user:
Display "Enter a number (1-7): ".
Step 4: Read the user's input:
Use scanf to read an integer from the user and store it in the variable day.
Step 5: Implement a switch statement based on the value of day:
Step 6: End the program.

Page : 24
Program
#include <stdio.h>
void main()
{
int day;
printf("Enter a number (1-7): ");
scanf("%d", &day);
switch (day)
{
case 1: printf("Monday\n");
break;
case 2: printf("Tuesday\n");
break;
case 3: printf("Wednesday\n");
break;
case 4: printf("Thursday\n");
break;
case 5: printf("Friday\n");
break;
case 6: printf("Saturday\n");
break;
case 7: printf("Sunday\n");
break;
default: printf("Invalid input! Please enter a number
between 1 and 7.\n");
}
}

RESULT:

In this program, the user enters a number representing a day of the week. The switch
statement then maps the input number to the corresponding day's name and displays it

Page : 25
4.2 To write a C Program to Design a calculator to perform the operations,
namely, addition, subtraction, multiplication and division of a number.

Aim:
The aim of this lab program is to design a basic calculator using C programming to
perform four arithmetic operations (addition, subtraction, multiplication, and division) on two
input numbers.

Algorithm
/* Calculator Program */
Step 1: Start the program.
Step 2: Declare variables: first and second to store the operands.
Step 3: Print a prompt to the user:- Display "Enter an operator (+, -, *, /, ^): ".
Step 4: Read the operator: -
Use scanf to read a character from the user and store it in the variable op.
Step 5: Print a prompt to the user: - Display "Enter two operands: ".
Step 6: Read the operands: - Use scanf to read two floating-point numbers from the user and
store them in first and second.
Step 7: Implement a switch statement based on the operator (op):
Start the switch statement depending on 'op' variable
Step 8: Perform Calculate Operations
Step 9:If the operator doesn't match any of the above cases, display an error message that the
operator is not correct
Step 10: End the program

Page : 26
Program
#include <stdio.h>
void main()
{
char op;
double first, second;
printf("Enter an operator (+, -, *, /, ^): ");
scanf("%c", &op);
printf("Enter two operands: ");
scanf("%lf %lf", &first, &second);

switch (op)
{
case '+':
printf("%f + %f = %f", first, second, first + second);
break;
case '-':
printf("%f - %f = %f", first, second, first - second);
break;
case '*':
printf("%f * %f = %f", first, second, first * second);
break;
case '/':
printf("%f / %f = %f", first, second, first / second);
break;
// operator doesn't match any case constant
default:
printf("Error! operator is not correct");
}

}
Output :

RESULT:

Thus the arithmetic operation is done as simple calculator

Page : 27
5 Program to implement one dimensional and two dimensional arrays

5.1 Program to sort the elements in an array

Aim
The aim of this program is to sort an array of integers in ascending order using the selection sort
algorithm.

Algorithm
Step 1: Start the program.
Step 2: Declare integer variables: i, j, temp, n, and an integer array arr of size 100.
Step 3: Print a prompt: "Enter the number of elements: ".
Step 4: Read the value of n (number of elements) from the user.
Step 5: Use a loop with i ranging from 0 to n-1.
Inside the loop, read arr[i] from the user.
Step 6: Implement the selection sort algorithm:
Compare arr[j] with arr[i]:
If arr[j] is smaller than arr[i], swap the elements using a temporary variable temp.
Step 7: Print the sorted array
Step 8: Print the sorted array:

Page : 28
Program
/* Program to sort the elements in an array */
#include <stdio.h>
void main()
{
int i,j,temp,n,arr[100];
printf("Enter the number of elements: ");
scanf("%d", &n);

printf("Enter %d elements:\n", n);


for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Selection sort algorithm


for (i = 0; i < n - 1; i++)
{
for (j = i + 1; j < n; j++)
{
if (arr[j] < arr[i])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
printf("Sorted array in ascending order:\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}

Output :

RESULT:

Thus the arithmetic operation is done as simple calculator

5.2 Write a Program to Addition and subtraction two matrices


Page : 29
Aim
To create a C program that performs addition and subtraction of two matrices.
Algorithm
Step 1: Start
Step 2: Declare matrix mat1[row][col];
and matrix mat2[row][col];
and matrix sum[row][col]; row= no. of rows, col= no. of columns
Step 3: Read row, col, mat1[][] and mat2[][]
Step 3: Enter the element of matrices using loops.
Step 4: Declare variable i=0, j=0
Step 5: Repeat until i < row
Step 5.1: Repeat until j < col
sum[i][j]=mat1[i][j] + mat2[i][j]
Set j=j+1
Step 5.2: Set i=i+1
Step 6: Repeat until i < row, i=0 and j=0
Step 6.1: Repeat until j < col
sub[i][j]=mat1[i][j] - mat2[i][j]
Set j=j+1
Step 6.2: Set i=i+1
step 9: Display Addition and subtraction matrix
Step 10: Stop

Page : 30
Program
#include<stdio.h>
main()
{
int a[10][10],b[10][10],m,n,i,j;
int sum[10][10],sub[10][10];
printf("Enter the size of the matrices:\nNo. of rows (m): ");
scanf("%d",&m);
printf("\nNo. of columns(n): ");
scanf("%d",&n);
printf("\nEnter the elements of matrix A:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\nEnter the elements of matrix B:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&b[i][j]);
}
}
printf("\nThe sum of the matrices A and B is:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{ sum[i][j]=a[i][j]+b[i][j];
printf("%d \t",sum[i][j]);
}
printf("\n");
}
printf("\nThe Subtract of the matrices A subtract B is:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
sub[i][j]=a[i][j]-b[i][j];
printf("%d \t",sub[i][j]);
}
printf("\n");
}
}

Page : 31
RESULT:

To input elements for two 2x2 matrices, calculates the sum and difference
of the matrices, and displays the results accordingly.

Page : 32
5.3 Program to multiply two 2 x 2 matrices

Aim
To create a C program that performs addition and subtraction of two matrices.

Algorithm
Step 1: Start the Program.
Step 2: Enter the row and column of the first (a) matrix.
Step 3: Enter the row and column of the second (b) matrix.
Step 4: Enter the elements of the first (a) matrix.
Step 5: Enter the elements of the second (b) matrix.
Step 6: Print the elements of the first (a) matrix in matrix form.
Step 7: Print the elements of the second (b) matrix in matrix form.
Step 8: Set a loop up to row.
Step 9: Set an inner loop up to the column.
Step 10: Set another inner loop up to the column.
Step 11: Multiply the first (a) and second (b) matrix and store the element in the
third matrix (c)
Step 12: Print the final matrix.
Step 13: Stop the Program.

Page : 33
#include<stdio.h>
main()
{
int a[10][10],b[10][10],m,n,i,j,k;
int mul[10][10];
printf("Enter the size of the matrices:\nNo. of rows (m): ");
scanf("%d",&m);
printf("\nNo. of columns(n): ");
scanf("%d",&n);
printf("\nEnter the elements of matrix A:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\nEnter the elements of matrix B:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&b[i][j]);
}
}
printf("\nMultiply the first(a)& second (b) matrix is:\n");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
mul[i][j] = 0;
for (k = 0; k < n; k++)
{
mul[i][j] = mul[i][j] + a[i][k] * b[k][j];
}
printf("%d \t",mul[i][j]);
}
Printf (“\n”);
}
}

Page : 34
Page : 35
6. String manipulations using string functions

6.1 Find the String length, string comparison, string copy on a given string

Aim: To create a program that takes two strings as input and performs the
following tasks:

- Calculate the length of the first string.

- Compare the two strings lexicographically.

- Copy the contents of the first string into a new string.

Algorithm:

Step 1 : Start the program.


Step 2 : Declare three character arrays str1, str2, and str3 to store the input strings
and the copied string, respectively.
Step 3 : Use the gets() function to input the first string into the str1and str2 array.
Step 4 : Calculate the length of the first string using the strlen() function and store
it in an integer variable
Step 5 : Compare the two strings using the strcmp() function and store the result in
an integer variable compare_result.
Step 6 : Use conditional statements to check the value of compare_result: If
compare_result is 0, display that the strings are equal.else not equl
Step 7 : Copy the contents of the first string into the str3 array using the strcpy()
function.
Step 8 : Display the string1, String2 and String3 using the printf() function.
Step 9 : End the program.

Page : 36
#include <stdio.h>
#include <string.h>
#include <conio.h>

void main()
{
char str1[100],str2[100],str3[100];
int compare_result, length;
clrscr(); /* Clear the screen */

printf("Enter a string: "); /* Input strings */


gets(str1);

printf("Enter another string: ");


gets(str2);

length = strlen(str1); /* Finding string length */


printf("Length of the first string: %d\n", length);

compare_result = strcmp(str1, str2); /*String comparison */


if (compare_result == 0)
{
printf("The strings are equal.\n");
}
else
{
printf("The string are Not equal.\n");
}

strcpy(str3, str1); /* String copy */


printf("string 1: %s\n", str1);
printf("string 2: %s\n", str2);
printf("string 3: %s\n", str3);
getch(); /* Wait for a key press before exiting */
}

Page : 37
RESULT:

Thus the The program calculates the length of the first string, compares the two strings
(first and Second ) , and then copies the first string into another string.

Page : 38
6.2 Find the total number of words in the paragraph
AIM :

To create a C program that takes a paragraph as input and calculates the total number of words
in it.
ALGORITHM:

Step 1: Start the program.


Step 2: Declare a character array paragraph to store the input paragraph.
Step 3: Initialize an integer variable wordCount to store the count of words and set it to 0.
Step 4: Use the gets() function to input the paragraph into the paragraph array.
Step 5: Loop through each character in the paragraph array:
Step 6: If the current character is a space, tab, or newline, reset the isWord flag to 0.
Step 7 : If the current character is not a space, tab, or newline, and the isWord flag is not set (0),
increment the wordCount and set the
isWord flag to 1 (true).
Step 8: Display the total number of words using the printf() function.
Step 9: End the program.

#include <stdio.h>
#include <conio.h>
#include <string.h>
void main()
{
char paragraph[1000];
int wordCount = 0,i;
int isWord = 0; /* Flag to track if a word is being read */

clrscr(); /* Clear the screen */

printf("Enter a paragraph:\n");
gets(paragraph);

/* Loop through the characters in the paragraph */


for ( i = 0; paragraph[i] != '\0'; i++)
{ /* Check if the current character is a space, tab, or
newline */
if (paragraph[i] == ' ' || paragraph[i] == '\t' ||
paragraph[i] == '\n')
{
isWord = 0; /* Reset the word flag */
}
Page : 39
/* If the current character is not a space, tab, or
newline, and the word flag is not set,
it means we've encountered a new word */
else if (isWord == 0)
{
isWord = 1; /* Set the word flag */
wordCount++; /* Increment the word count */
}
}
printf("Total number of words: %d\n", wordCount);
getch(); /* Wait for a key press before exiting */

RESULT:

Thus the program takes the provided paragraph as input and counts the total number of words,
correctly identifies words based on spaces between them and provides the expected result.

Page : 40
Page : 41
AIM :

Aim: To create a C program that takes a string as input and determines whether the string is a
palindrome or not.
ALGORITHM:

Step 1 : Start the program.


Step 2 : Declare a character array str to store the input string.
Step 3 : Initialize an integer variable isPalindrome and set it to 1.
Step 4 : Use the gets() function to input the string into the str array.
Step 5 : Iterate while i is less than j:
Step 5.1 : If str[i] is not equal to str[j], set isPalindrome to 0 and break the loop.
Step 5.2 : Increment i and decrement j.
Step 5.3 : Check the value of isPalindrome:
Step 5.4 : If isPalindrome is 1, display that the string is a palindrome.
Step 5.5 : If isPalindrome is 0, display that the string is not a palindrome.
Step .6 : End the program.

PROGRAM:

#include <stdio.h>
#include <conio.h>
#include <string.h>
void main()
{
char str[100];
int i, j;
int Pali = 1; /* Flag to track if the string is a palindrome
*/
clrscr(); /* Clear the screen */
printf("Enter a string: ");
gets(str);

Page : 42
/*Compare characters from the beging and end of the string */
for (i = 0, j = strlen(str) - 1; i < j; i++, j--)
{
if (str[i] != str[j])
{ /*Set the flag to indicate not a palindrome */
Pali = 0;
break;
}
}

if (Pali)
{
printf("The string is a palindrome.\n");
}
else
{
printf("The string is not a palindrome.\n");
}

getch(); // Wait for a key press before exiting


}

RESULT:

Thus the the program takes the provided string "radar" as input and correctly identifies it as a
palindrome,

Page : 43
7. Program to implement calling the function
AIM :

To create a C program that swaps two numbers using the call by value mechanism.

ALGORITHM:

Step 1 : Start the program.


Step 2 : Declare two integer variables num1 and num2 to store the numbers.
Step 3 : Use the scanf() function to input the first number (num1) and second number (num2)
variable.
Step 4 : Call a swap function and pass the values of num1 and num2 as arguments.
Step 5 : Inside the swap function, swap the values of the two arguments using a temporary
variable.
Step 6 : Display the values of num1 and num2 after swapping (inside the main function).
Step 7 : End the program.

PROGRAM:
#include <stdio.h>
#include <conio.h>
/* Function to swap two numbers using call by value */
void swap(int a, int b)
{
int temp = a;
a = b;
b = temp;
printf("Inside the swap function: a = %d, b = %d\n", a, b);
}
void main()
{
int num1, num2;
clrscr();
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
printf("Before swapping: num1 = %d, num2 = %d\n", num1, num2);
/* Call the swap function */
swap(num1, num2);
printf("After swapping (main function): num1 = %d, num2 =
%d\n", num1, num2);
getch();
}

Page : 44
RESULT:

Thus the the program takes the values inside the swap function are indeed swapped, but due to
call by value, the original variables in the main function remain unchanged.

Page : 45
AIM :

To create a C program that swaps two numbers using the call by reference mechanism.

ALGORITHM:

Step 1 : Start the program.


Step 2 : Declare two integer variables num1 and num2 to store the numbers.
Step 3 : Use the scanf() function to input into the num1 & num2 variable.
Step 4 : Display the values of num1 and num2 before swapping.
Step 5 : Call a swap function and pass the addresses of num1 and num2 as arguments.
Step 6 : Inside the swap function, swap the values of the two numbers using pointers.
Step 7 : Display the values of num1 and num2 after swapping (inside the main function).
Step 8 : End the program.

PROGRAM:

#include <stdio.h>
#include <conio.h>
/* Function to swap two numbers using call by reference */
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}

void main()
{
int num1, num2;
clrscr();
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
printf("Before swapping: num1 = %d, num2 = %d\n", num1, num2);
// Call the swap function with pointers
swap(&num1, &num2);
printf("After swapping: num1 = %d, num2 = %d\n", num1, num2);
getch(); // Wait for a key press before exiting
}

Page : 46
RESULT:

Thus the values inside the swap function are swapped, and due to call by reference, the original
variables in the main function are changed.

Page : 47
AIM :
To create a program that defines a structure to store employee data and then inputs and
displays employee information.

ALGORITHM:

Step 1 : Start the program.


Step 2 : Define a structure named Employee with members empId, empName, and empSalary.
Step 3 : Declare a structure variable emp of type Employee to store employee data.
Step 4 : Use the scanf() function to input the empId, empName, and empSalary.
Step 5 : Display a message indicating that the employee details are being displayed.
Step 6 : End the program.

PROGRAM:

#include <stdio.h>
#include <conio.h>
/* Define a structure to represent an employee */
struct Employee
{
int empId;
char empName[50];
float empSalary;
};

void main()
{
struct Employee emp; /* Declare a structure variable */
clrscr();
/* Input employee details */
printf("Enter Employee ID: ");
scanf("%d", &emp.empId);

printf("Enter Employee Name: ");


fflush(stdin); // Clear input buffer
gets(emp.empName);
printf("Enter Employee Salary: ");
scanf("%f", &emp.empSalary);

// Display employee details


printf("\nEmployee Details\n");
printf("ID: %d\n", emp.empId);
printf("Name: %s\n", emp.empName);
printf("Salary: %.2f\n", emp.empSalary);
getch();
}

Page : 48
RESULT:

Thus the program prompts the user to input the employee's ID, name, and salary. After input, it
displays the entered employee details using the structure Employee.

Page : 49
Write a program that defines a structure to store student data and then inputs and displays
student information using an array of structures.

AIM :

To create program that defines a structure to store student data and then inputs and displays
student information using an array of structures.

ALGORITHM:

Step 1 : Start the program.


Step 2 : Define a structure named Student with members rollNumber, name, and marks.
Step 3 : Declare an array of structures named students to store student data.
Step 4 : Loop over the array index and input student details for each student using the scanf()
and gets() functions.
Step 5 : Display student details for each student using the printf() function.
Step 6 : End the program.

PROGRAM:

#include <stdio.h>
#include <conio.h>
/* Define a structure to represent a student */
struct Student
{
int rollNumber;
char name[50];
float marks;
};

int main()
{
int i;
struct Student students[3]; /* Declare an array of
structures to store student data */
clrscr();
/* Input student details */
for (int i = 0; i < 3; i++)
{
printf("Enter details for student %d:\n", i + 1);
printf("Enter Roll Number: ");
scanf("%d", &students[i].rollNumber);
printf("Enter Name: ");
fflush(stdin); // Clear input buffer
gets(students[i].name);

Page : 50
printf("Enter Marks: ");
scanf("%f", &students[i].marks);
printf("\n");
}

/* Display student details */


printf("Student Details:\n");
for (int i = 0; i < 3; i++)
{
printf("Student %d\n", i + 1);
printf("Roll Number: %d\n", students[i].rollNumber);
printf("Name: %s\n", students[i].name);
printf("Marks: %.2f\n\n", students[i].marks);
}

getch(); // Wait for a key press before exiting


return 0;
}
Sample Output:

RESULT:

Thus the program prompts the user to input the student's roll number, name, and marks
for each student. After input, it displays the entered student details using the structure array
students

Page : 51
1 Program to calculate EB bill for 5 consumers using structure with member
variables for customer name, customer No, previous reading, current
reading, units consumed, and bill amount. The Electricity bill is to be
calculated with the following condition
Units Consumed Rate/unit
Upto 100 Re.1/-
Above 100 and below 201 Rs.2/-
Above 200 and below 501 Rs.3/-
Above 500 Rs.5/-
Prepare and display the EB bill with customer name, units consumed and
chargeable amount.
AIM:

To write a C program for Electricity Bill calculation.

ALGORITHM:

1. Display user instructions


2. Get data: unpaid balance and electricity unit used
3. Determine electricity unit used and compute use charge
4. Determine unpaid balance and compute amount
5. Compute total charge
6. Display the total bill amount

Page : 52
PROGRAM:

#include<stdio.h>
// #include<conio.h>
struct eb
{
char n[10][10];
int en[10],pr[10],cr[10],u[10];
float amt[10];
}e[5];

void main()
{
int i;
clrscr();
for(i=0;i<5;i++)
{
printf("\nEnter the name:");
scanf(“%s”,e.n[i]);
printf("\nEnter the EB number:");
scanf(“%d”,&e.en[i]);
printf("\nEnter the previous reading:");
scanf(“%d”,&e.pr[i]);
printf("\nEnter the current reading:");
scanf(“%d”.&e.cr[i];
}
for(i=0;i<5;i++)
{
e.u[i]=e.cr[i]-e.pr[i];
if(e.u[i]<=100)
e.amt[i]=e.u[i]*1;
elseif(e.u[i]>100&&e.u[i]<=200)
e.am[i]=100+(e.u[i]-100)*2;
elseif(e.u[i]>200&&e.u[i]<=500)
e.am[i]=300+(e.u[i]-200)*3;
else
e.am[i]=1200+(e.u[i]-500)*5;
printf("Name: %s",e.n[i]);
printf("EB.No:%d",e.en[i]);
printf("Previous Reading:%d",e.pr[i]);
printf("Current Reading:%d",e.cr[i]);
printf("Unit:=%d",e.u[i]);
printf("Amount= Rs.=%d",e.am[i]); //%f
}
getch;
}

Page : 53
Sample Output:

Enter the name: Raja


Enter the EB number: 101
Enter the previous reading: 500
Enter the current reading: 590
Name: Raja
EB.No: 101
Previous Reading: 500
Current Reading: 590
Unit: 90
Amount= Rs.90

Enter the name: SREE


Enter the EB number: 102
Enter the previous reading: 1000
Enter the current reading: 1250
Name: SREE
EB.No: 102
Previous Reading: 1000
Current Reading: 1250
Unit: 250
Amount= Rs.450

RESULT:

Thus the Electricity Bill is calculated

Page : 54
Write a program to swap two numbers using pointers

AIM :

To create a program that swaps two numbers using pointers.

ALGORITHM:

Step 1: Start the program.


Step 2: Declare integer variables num1, num2, and temp to store the numbers and a temporary
value.
Step 3: Declare integer pointers ptr1 and ptr2 to store addresses.
Step 4: Assign the address of num1 to ptr1 and num2 to ptr2.
Step 5: Store the value pointed to by ptr1 in temp.
Step 6: Assign the value pointed to by ptr2 to the value pointed to by ptr1.
Step 7: Assign the value of temp to the value pointed to by ptr2.
Step 8: Display the values of num1 and num2 after swapping using printf.
Step 9: End the program.

PROGRAM:
#include <stdio.h>
#include <conio.h>

int main()
{
int num1, num2, *ptr1, *ptr2, temp;
clrscr();
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
printf("Before swapping: num1 = %d, num2 = %d\n", num1, num2);
ptr1 = &num1; /* Point ptr1 to num1 */
ptr2 = &num2; /* Point ptr2 to num2 */

/* Swap using pointers */


temp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = temp;

printf("After swapping: num1 = %d, num2 = %d\n", num1, num2);


getch();
}

Page : 55
RESULT:

Thus swaps the numbers using pointers, and then displays the values after swapping.

Page : 56
9.3 Program to implement pointer to function
AIM :
To Create a program that demonstrates the usage of a pointer to a function by
performing addition and subtraction using the same pointer.

ALGORITHM:
Step 1: Start the program.
Step 2: Declare integer variables a, b to hold input values and result to store the function result.
Step 3: Declare a function pointer named operation that can point to functions returning an
integer and taking two integer parameters.
Step 4: Assign the address of the add function to the operation pointer.
Step 5: Get two integer inputs a and b from the user.
Step 6: Perform addition using the operation pointer by passing a and b as arguments and
storing the result in result.
Step 7: Display the addition result using printf.
Step 8: Assign the address of the subtract function to the operation pointer.
Step 9: Perform subtraction using the operation pointer by passing a and b as arguments and
storing the result in result.
Step 10: Display the subtraction result using printf.
Step 11: End the program.

PROGRAM:
#include <stdio.h>
#include <conio.h>
int add(int a, int b) /* Function to add two numbers */
{
return a + b;
}
int subtract(int a, int b)/*Function to subtract two numbers */
{
return a - b;
}
void main()
{
int (*operation)(int, int); /* Declare a pointer Function */
clrscr();
/*Assign the address of the 'add' function to the pointer */
operation = add;

/* Call the 'add' function using the pointer */


printf("Addition result: %d\n", operation(5, 3));

operation = subtract;
/* Call the 'subtract' function using the pointer */
printf("Subtraction result: %d\n", operation(10, 4));
getch();

}
Page : 57
RESULT:

Thus demonstrates how a single pointer can be used to switch between different functions and
perform operations dynamically.

Page : 58
C program that demonstrates dynamic memory allocation using the malloc() function

AIM :

To create a program that demonstrates dynamic memory allocation using the malloc()
function to allocate memory for an integer array based on user input.

ALGORITHM:

Step 1: Start the program.


Step 2: Declare an integer variable n to store the size of the array and an integer pointer arr to
store the dynamically allocated memory.
Step 3: Prompt the user to input the size of the array (n).
Step 4: Allocate memory for an integer array of size n using the malloc() function.
Step 5: Prompt the user to input n integer elements and store them in the allocated memory
(arr).
Step 6: Display the entered array elements using a loop and printf.
Step 7: Free the dynamically allocated memory using the free() function.
Step 8: End the program.

PROGRAM:

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

int main()
{
int n;
int *arr;
clrscr();
printf("Enter the size of the array: ");
scanf("%d", &n);

/* Allocate memory for an integer array of size 'n' */


arr = (int *)malloc(n * sizeof(int));

if (arr == NULL)
{
printf("Memory allocation failed.\n");
getch();
return 1;
}

printf("Enter %d elements:\n", n);


for (int i = 0; i < n; i++)
scanf("%d", &arr[i]);

Page : 59
printf("Array elements are:\n");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);

/* Free the allocated memory */


free(arr);

getch();
return 0;
}

Sample Output:

RESULT:

Thus the demonstrates how dynamic memory allocation allows you to create arrays with sizes
determined at runtime

Page : 60
Page : 61
Program for preparation of student result for three marks m1,m2,m3 as
follows: Min pass mark 50 in each sub, If avg>=75 – Distinction, avg>=60 I
Class, avg>=50 II Class3 Program to implement various loop structures

3.1 Find the greatest of N numbers.

AIM :

To write a C program to find student result.

ALGORITHM:

Step 1 : start
Step 2 : read marks m1, m2, m3
Step 3 : total  m1+m2+m3
Step 4 : avg  total/3
Step 5 : if average >= 75 then result  Distinction , go to step 9
Step 6 : if average >= 60 then result  I Class, go to step 9
Step 7 : if total >=50 then result  II Class, go to step 9
Step 8 : else result  Fail, go to step 9
Step 9 : display grade.
Step 10 : stop.
PROGRAM:

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int m1,m2,m3;
long avg,total;
printf("Enter first subject mark m1:");
scanf(“%d%”,m1);
printf("Enter second subject mark m2:");
scanf(“%d%”,m2);
printf("Enter third subject mark m3:");
scanf(“%d%”,m3);
total=(m1+m2+m3);
avg=(total*100)/300;
printf("Percentage: %d",avg);

Page : 62
if(m1<50||m2<50||m3<50)
printf("Fail");
else
{
if(avg>=75)
printf("Distinction");
else
{
if(avg>=60)
printf("First Class");
else
{
printf("Second Class");
}
}
}
getch();
}

Sample Output:

Enter first subject mark m1:


70
Enter second subject mark m2:
80
Enter third subject mark m3:
90
Percentage: 80
Distinction

RESULT:

Thus the student result is calculated.

3.2 Write a Program for simple calculator


AIM :

To write a C program for simple mathematical calculation like addition, subtraction.

ALGORITHM:

Step 1: Start
Step 2: Read the numbers.
Step 3: Read the operator
Page : 63
Step 4: Perform the arithmetic operations using switch case.
Step 5: Print the desired output
Step 6: Stop
PROGRAM:

#include<stdio.h>
#include<conio.h>
int main()
{
char opr;
float x,y;
printf("Enter operator:");
scanf(“%c”,&opr);
printf("Enter two operands");
scanf(“%d%d”,&x,&y);
switch(opr)
{
case'+':
printf("x + y = %d",x+y);
break;
case'-':
printf("x - y = %d",x-y);
break;
case'*':
printf("x * y = %d",x*y);
break;
case'/':
printf("x / y =%d ",x/y);
break;
}
return o;
getch();
}

Sample Output:

Enter operator:
+
Enter two operands
10
20
x + y = 30

Page : 64
RESULT:

Thus the arithmetic operation is done as simple calculator.

3.3 Write a program to print prime numbers between 1 and 100


AIM :

To write a C program to print the prime numbers between 1 and 100.

ALGORITHM:

Step 1: Start
Step 2: While (N < 100)
I2, INum
Step 4: While (I<N)
Step 5: IF N%I == 0
goto Step 7
Step 6: I++
Step 7: IF I==NUM
Print NUM
Step 7: N++
Step 8: Stop
PROGRAM:

#include<stdio.h>
#include<conio.h>

Page : 65
void main()
{
int i,j,f;
clrscr();
printf("Prime numbers between 1 and 100 are:";
for(i=2;i<=100;i++)
{
f=0;
for(j=2;j<i;j++)
{
if(i%j==0)
{
f=1;
break;
}
}
if(f==0)
printf(“ %d”,i);
}
getch();
}

Sample Output:

Prime numbers between 1 and 100 are:

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

Page : 66
RESULT:

Thus the prime numbers between a and 100 is printed.

4. Program to implement one dimensional and two dimensional arrays

4.1 Program to sort the elements in an array


AIM :

To write a C program to sort the elements of an array.

ALGORITHM:

Step 1: Start
Step 2: read n
Step 3: Read the elements one by one
Step 4: While (the first element > the next element)
afirst element, first elementnext element
next element  a
Step 5: Print the element one by one
Step 6: Stop
PROGRAM:

#include<stdio.h>
#include<conio.h>
void main()
{
int i, j, a, n, number[30];

printf("Enter the value of N \n");


scanf("%d",&n);
printf("Enter the numbers \n");
for(i =0; i < n;++i)
scanf("%d",&number[i]);
for(i =0; i < n;++i)
{
for(j = i +1; j < n;++j)
{
if(number[i]> number[j])
{
a = number[i];
number[i]= number[j];
Page : 67
number[j]= a;
}
}
}
printf("The numbers arranged in ascending order are given below \n");
for(i =0; i < n;++i)
printf("%d\n", number[i]);
}

Sample Output:

Enter the value of N:

Enter the numbers:

17 5 45 8 13

The numbers arranged in ascending order are given below

5 8 13 17 45

RESULT:

Thus the prime numbers between a and 100 is printed.

4.2 Program to multiply two 3 x 3 matrices

Page : 68
AIM :

To write a C program to multiply two 3 x 3 matrices

ALGORITHM:

Step 1: Start
Step 2: read the order of the matrices a and b
Step 3: Read the elements of the first matrix a
Step 4: Read the elements of the second matrix b
Step 5: compute the matrix c sum of the multiplication of row and column elements
Step 6: Print the elements of the matrix c
Step 7: Stop
PROGRAM:

#include<stdio.h>
#include<conio.h>
int main()
{
int a[10][10], b[10][10], c[10][10], i, j, k;
int sum = 0;

printf("\nEnter First Matrix : n");


for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
scanf("%d", &a[i][j]);
}
}

printf("\nEnter Second Matrix:n");


for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
scanf("%d", &b[i][j]);
}
}

printf("The First Matrix is: \n");


for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf(" %d ", a[i][j]);
}
printf("\n");
}

printf("The Second Matrix is : \n");


for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf(" %d ", b[i][j]);

Page : 69
}
printf("\n");
}

//Multiplication Logic
for (i = 0; i <= 2; i++) {
for(j = 0; j <= 2; j++) {

sum = 0;
for (k = 0; k <= 2; k++) {
sum = sum + a[i][k] * b[k][j];
}
c[i][j] = sum;
}
}

printf("\nMultiplication Of Two Matrices : \n");


for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf(" %d ", c[i][j]);
}
printf("\n");
}

return (0);
}

Sample Output:

Enter first matrix:


1 2 0
0 1 1
2 0 1
Enter the second matrix
Page : 70
1 1 2
2 1 1
1 2 1
Multiplication two matrices:
5 3 4
3 3 2
3 4 5

RESULT:

Thus the matrix multiplication is done

5. Program to implement calling the function through call by value method &
call by reference

5.1 Program to swap two numbers using call by values


AIM :

To write a C program to swap two numbers using call by values.

ALGORITHM:

Step 1: Start the program.


Step 2: read a and b
Step 3: Call the function swap(a,b)
Step 4: Start function
Step 5: Assign t ← x
Page : 71
Step 6: Assign x ← y
Step 7: Assign y ← t
Step 8: End function
Step 9: Print x and y.
Step 10: Stop the program.
PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
printf("Enter Value Of 1st no.:");
scanf(“%d”,&a);
printf("Enter Value of 2nd no.:");
scanf(“%d”,&b);
printf("Before swapping\nValue of 1st no. is %d \nValue of 2nd no. is %d ", a,b);
swap(a,b);
printf("\nOutside function after swapping\nValue of 1st no. is %d \nValue of 2nd no. is %d
",a,b);
}
void swap(int a,int b)
{
int c;
c=a;
a=b;
b=c;
printf("\nInside function after swapping\nValue of 1st no. is %d \nValue of 2nd no. is %d ",a,b);
}

Sample Output:

Enter Value Of 1st no.:


10
Enter Value of 2nd no.:"
20
Before swapping
Value of 1st no. is
10
Value of 2nd no. is
20
Outside function after swapping
Value of 1st no. is
10
Value of 2nd no. is
Page : 72
20
Inside function after swapping
Value of 1st no. is
20
Value of 2nd no. is
10

RESULT:

Thus the swapping of two numbers is done using call by value.

5.2 Program to swap two numbers using call by reference


AIM :

To write a C program to swap two numbers using call by reference.

ALGORITHM:

Step 1: Start the program.


Step 2: read a and b
Step 3: Call the function swap(&a,&b)
Step 4: Start function
Step 5: Assign t ← *x
Step 6: Assign *x ← *y
Step 7: Assign *y ← t
Step 8: End function
Step 9: Print x and y.
Step 10: Stop the program.

PROGRAM:

#include<stdio.h>
#include<conio.h>
void main()

Page : 73
{
int a,b;
printf("Enter Value Of 1st no.:");
scanf(“%d”,&a);
printf("Enter Value of 2nd no.:");
scanf(“%d”,&b);
printf("Before swapping\nValue of 1st no. is %d \nValue of 2nd no. is %d ", a,b);
swap(&a,&b);
printf("\nOutside function after swapping\nValue of 1st no. is %d \nValue of 2nd no. is %d
",a,b);
}
void swap(int *a,int *b)
{
int c;
c=*a;
*a=*b;
*b=c;
printf("\nInside function after swapping\nValue of 1st no. is %d \nValue of 2nd no. is %d ",a,b);
}

Sample Output:

Enter Value Of 1st no.:


10
Enter Value of 2nd no.:"
20
Before swapping
Value of 1st no. is
10
Value of 2nd no. is
20
Outside function after swapping
Value of 1st no. is
20
Value of 2nd no. is
10
Inside function after swapping
Value of 1st no. is
20
Value of 2nd no. is
10

Page : 74
RESULT:

Thus the swapping of two numbers is done using call by reference.

6. Program to implement Structures

6.1 Program to calculate EB bill for 5 consumers using structure with


member variables for customer name, customer No, previous reading,
current reading, units consumed, and bill amount. The Electricity bill is to
be calculated with the following condition
Units Consumed Rate/unit
Upto 100 Re.1/-
Above 100 and below 201 Rs.2/-
Above 200 and below 501 Rs.3/-
Above 500 Rs.5/-
Prepare and display the EB bill with customer name, units consumed and
chargeable amount.
AIM:

To write a C program for Electricity Bill calculation.

ALGORITHM:

1. Display user instructions


2. Get data: unpaid balance and electricity unit used
3. Determine electricity unit used and compute use charge
4. Determine unpaid balance and compute amount
5. Compute total charge
6. Display the total bill amount

PROGRAM:

#include<stdio.h>
// #include<conio.h>
Page : 75
struct eb
{
char n[10][10];
int en[10],pr[10],cr[10],u[10];
float amt[10];
}e[5];

void main()
{
int i;
// clrscr();
for(i=0;i<5;i++)
{
printf("\nEnter the name:");
scanf(“%s”,e.n[i]);
printf("\nEnter the EB number:");
scanf(“%d”,&e.en[i]);
printf("\nEnter the previous reading:");
scanf(“%d”,&e.pr[i]);
printf("\nEnter the current reading:");
scanf(“%d”.&e.cr[i];
}
for(i=0;i<5;i++)
{
e.u[i]=e.cr[i]-e.pr[i];
if(e.u[i]<=100)
e.amt[i]=e.u[i]*1;
elseif(e.u[i]>100&&e.u[i]<=200)
e.am[i]=100+(e.u[i]-100)*2;
elseif(e.u[i]>200&&e.u[i]<=500)
e.am[i]=300+(e.u[i]-200)*3;
Page : 76
else
e.am[i]=1200+(e.u[i]-500)*5;
printf("Name: %s",e.n[i]);
printf("EB.No:%d",e.en[i]);
printf("Previous Reading:%d",e.pr[i]);
printf("Current Reading:%d",e.cr[i]);
printf("Unit:=%d",e.u[i]);
printf("Amount= Rs.=%d",e.am[i]); //%f
}
//getch;
}

Sample Output:

Enter the name: Raja


Enter the EB number: 101
Enter the previous reading: 500
Enter the current reading: 590
Name: Raja
EB.No: 101
Previous Reading: 500
Current Reading: 590
Unit: 90
Amount= Rs.90

Enter the name: Bala


Enter the EB number: 102
Enter the previous reading: 1000
Enter the current reading: 1250
Name: Bala
EB.No: 102
Previous Reading: 1000
Current Reading: 1250
Unit: 250
Amount= Rs.450

Page : 77
RESULT:

Thus the Electricity Bill is calculated

7. Program to implement dynamic memory allocation

7.1 program to sort number in ascending order by using malloc function. Use
free to release memory.
AIM:

To write a C program to sort the numbers using malloc() function.

ALGORITHM:

● Start
● Read n and the numbers
● Compare first number with all the numbers
● Pick the largest number among the numbers
● Repeat steps 3 and 4 for the remaining numers
● Print the numbers
● Stop
PROGRAM:

#include<stdio.h>
#include<stdlib.h>
int main()
{
int i,j,temp,n;
int *p;
printf("Enter value of n: ");
scanf("%d",&n);
p=(int*)malloc(n*sizeof(int));
printf("Enter values\n");
for(i=0;i<n;i++)
scanf("%d",&p[i]);
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(p[i]>p[j])
Page : 78
{
temp=p[i];
p[i]=p[j];
p[j]=temp;
}
}
}
printf("Ascending order\n");
for(i=0;i<n;i++)
printf("%d\n",p[i]);
free(p);
return 0;
}
Sample Output:

Enter value of n: 5
Enter values
40
30
20
50
10
Ascending order
10
20
30
40
50

Page : 79
RESULT:

Thus the given numbers are sorted malloc() function.

8. Program to implement pointer to function


8.1 Program to add two numbers using function pointer.
AIM:

To write a C program to add two numbers using function pointer.

ALGORITHM:

1. Define a function to add two numbers


2. Declare a pointer to call the function
3. Call the function without pointer
4. Call the function using pointer.
5. Display the result
6. Stop

PROGRAM:

#include<stdio.h>
#include<conio.h>
int sum (int num1, int num2)
{
return num1+num2;
}
int main()
{
int (*f2p) (int, int);
f2p = sum;
int op1 = f2p(10, 13);
int op2 = sum(10, 13);
printf("Output1: Call using function pointer: %d",op1);
printf("\nOutput2: Call using function name: %d", op2);
return0;
}

Page : 80
Sample Output:

Output1: Callusingfunction pointer: 23


Output2: Callusingfunction name: 23

RESULT:

Thus the function pointer is invoked.

9. Program to implement an array of pointers


9.1 Program to sort the list of names

Page : 81
AIM:

To write a C program to sort the names using array of pointers

ALGORITHM:

step 1. Define a function to sort


step 2. Declare pointer an array to store the names
step 3. Get n as number of names
step 4. Read the names
step 5. Call the function to sort the name
step 6. Print the sorted names
step 7. Stop
PROGRAM:

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char *x[20];
int i,n=0;
void reorder(int n,char *x[]);
clrscr();
printf("Enter no. of String : ");
scanf("%d",&n);
printf("\n");
for(i=0;i<n;i++)
{
printf("Enter the Strings %d : ",i+1);
x[i]=(char *)malloc(20*sizeof(char));
scanf("%s",x[i]);
}
reorder(n,x);
printf("\nreorder list is : \n");

Page : 82
for(i=0;i<n;i++)
{
printf("%d %s\n",i+1,x[i]);
}
getch();
}
void reorder(int n,char *x[])
{
int i,j;
char t[20];
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
if(strcmp(x[i],x[j])>0)
{
strcpy(t,x[j]);
strcpy(x[j],x[i]);
strcpy(x[i],t);
}
return;
}

Sample Output:

Enter the number of strings:


3
Enter the string 1 : Raja
Enter the string 1 : Arun
Enter the string 1 : Saran

Reorder list is :
Page : 83
1.Arun
2.Raja
3.Saran

RESULT:

Thus the names are sorted using pointer array

10. Program to implement various file operations in a standard file

10.1 Program to create a file and store the information


AIM:

To write a C program to create a file and to store the information

ALGORITHM:

Step 1: Start the program.


Step 2: Declare a pointer to a FILE named fptr.
Step 3: Declare character array name to store the employee name, and variables age (integer)
and salary (float) to store employee age and salary.
Step 4: Open the file "emp.rec" in write mode using fopen().
If the file cannot be opened, display an error message and return.
Write employee details to the file using fprintf() function.
Step 5: Close the file using fclose().
Step 6: End the program.
Page : 84
PROGRAM:

#include <stdio.h>
void main()
{
FILE *fptr;
char name[20];
int age;
float salary;
/* open for writing */
fptr =fopen("emp.rec","w");
if(fptr == NULL)
{
printf("File does not exists \n");
return;
}

Page : 85
printf("Enter the name \n");
scanf("%s", name);
fprintf(fptr,"Name = %s\n", name);
printf("Enter the age\n");
scanf("%d",&age);
fprintf(fptr,"Age = %d\n", age);
printf("Enter the salary\n");
scanf("%f",&salary);
fprintf(fptr,"Salary = %.2f\n", salary);
fclose(fptr);
}

Sample Output:

Enter the name


raj
Enter the age
40
Enter the salary
4000000

ESULT:

Thus the file is created and stored the information.

10.2 Program to implement various file operations in text file


AIM:
Page : 86
To write a C program to copy a file into another file.

ALGORITHM:
1. Start
2. Open two file pointers
3. The first file contains some text and in read mode
4. The second file is opened to copy the first file in write mode
5. Set the position of the first file in starting position
6. Copy the characters until the position becomes the end of file
7. Stop

PROGRAM:
#include<stdio.h>
void main()
{
FILE *fp1, *fp2;
char ch;
int pos;
if ((fp1 = fopen("File_1.txt","r")) == NULL)
{
printf("\nFile cannot be opened");
return;
}
else
{
printf("\nFile opened for copy...\n ");
}
fp2 = fopen("File_2.txt", "w");
fseek(fp1, 0L, SEEK_END); // file pointer at end of file
pos = ftell(fp1);
fseek(fp1, 0L, SEEK_SET); // file pointer set at start
while (pos--)
{
ch = fgetc(fp1); // copying file character by character
fputc(ch, fp2);
}
printf(“File copied”);
fcloseall();
}

Page : 87
Sample Output:

File opened for copy …

File copied

RESULT:
Thus content of one file is copied into another file

Page : 88

You might also like