TSP Lab Record
TSP Lab Record
DEPARTMENT OF
INFORMATION TECHNOLOGY
I YEAR–II SEMESTER
LAB RECORD
Name: Roll No :
Reg. No.: Section:
1
PANIMALAR ENGINEERING COLLEGE, CHENNAI
(AN AUTONOMOUS INSTITUTION)
JAISAKTHI EDUCATIONAL TRUST
ACCREDITED BY NATIONAL BOARD OF ACCREDITATION
AN ISO 9001:2000 CERTIFIED INSTITUTION
Bangalore Trunk Road,
Varadharajapuram, Nasarathpettai,
Poonamallee, Chennai – 600 123.
DEPARTMENT OF
INFORMATION TECHNOLOGY
BONAFIDE CERTIFICATE
This is a Certified Bonafide Record Book of
Mr. /Ms. .…………………………....................................................................................
University Register Number …………
STAFF-IN-CHARGE
2
VISION AND MISSION OF THE INSTITUTION
VISION
MISSION
3
VISION AND MISSION OF THE DEPARTMENT
VISION
To provide an academically conducive environment for individuals to develop
as technologically superior, socially conscious and nationally responsible citizens.
MISSION
M1: To develop our department as a centre of excellence, imparting quality
education, generating competent and skilled manpower.
M2: To prepare our students with high degree of credibility, integrity, ethical
standards and social concern.
M3: To train our students to devise and implement novel systems based on
Education and Research.
4
KNOWLEDGE AND ATTITUDE PROFILE (WK)
WK8: Engagement with selected knowledge in the current research literature of the
discipline, awareness of the power of critical thinking and creative
approaches to evaluate emerging issues.
5
PROGRAM OUTCOMES (POs)
PO2: Problem Analysis: Identify, formulate, review research literature and analyze complex
engineering problems reaching substantiated conclusions with consideration for sustainable
development. (WK1 to WK4)
PO5: Engineering Tool Usage: Create, select and apply appropriate techniques, resources and
modern engineering & IT tools, including prediction and modelling recognizing their limitations
to solve complex engineering problems. (WK2 and WK6)
PO6: The Engineer and The World: Analyze and evaluate societal and environmental aspects
while solving complex engineering problems for its impact on sustainability with reference to
economy, health, safety, legal framework, culture and environment. (WK1, WK5, and WK7).
PO7: Ethics: Apply ethical principles and commit to professional ethics, human values, diversity
and inclusion; adhere to national & international laws. (WK9)
PO8: Individual and Collaborative Team work: Function effectively as an individual, and as a
member or leader in diverse/multi-disciplinary teams.
PO10: Project Management and Finance: Apply knowledge and understanding of engineering
management principles and economic decision-making and apply these to one’s own work, as a
member and leader in a team, and to manage projects and in multidisciplinary environments.
PO11: Life-Long Learning: Recognize the need for, and have the preparation and ability for i)
independent and life-long learning ii) adaptability to new and emerging technologies and iii)
critical thinking in the broadest context of technological change. (WK8)
6
7
INDEX
11 Recursion 57
12 strings 60
13 Pointers 67
14 Command Line Arguments, Pre- 71
processors
15 File handling and exception handling 73
16 Additional Exercises 77
8
EX.NO.1 DATA TYPES, VARIABLES, OPERATORS
DATE:
AIM
To demonstrate Data Types, Variables, Operators in C.
return 0;
}
OUTPUT
Integer: 10
Float: 5.50
Character: A
Double: 3.141590
PROGRAM-2 //operators
#include <stdio.h>
int main()
{
int x = 10, y = 4;
// Arithmetic Operators
printf("Addition: %d\n", x + y);
printf("Subtraction: %d\n", x - y);
printf("Multiplication: %d\n", x * y);
printf("Division: %d\n", x / y);
printf("Modulus: %d\n", x % y);
// Relational Operators
printf("x > y: %d\n", x > y);
printf("x == y: %d\n", x == y);
// Logical Operators
printf("(x > 5) && (y < 10): %d\n", (x > 5) && (y < 10));
printf("(x < 5) || (y < 10): %d\n", (x < 5) || (y < 10));
return 0;
}
9
OUTPUT
Addition: 14
Subtraction: 6
Multiplication: 40
Division: 2
Modulus: 2
x > y: 1
x == y: 0
(x > 5) && (y < 10): 1
(x < 5) || (y < 10): 1
EXERCISE -compute the perimeter and area of a rectangle, taking the length and breadth
as input
PROGRAM
#include<stdio.h>
#include<conio.h>
int main()
{
/* Declaring variables */
float length, breadth, area, perimeter;
/* Reading length and breadth from user */
printf("Enter length of the rectangle = ");
scanf("%f", &length);
printf("Enter breadth of the rectangle = ");
scanf("%f", &breadth);
/* Calculating area and perimeter */
area = length * breadth;
perimeter = 2 * (length * breadth);
/* Displaying result */
printf("Area of rectangle = %f", area);
printf("\nPerimeter of rectangle = %f", perimeter);
return 0;
}
OUTPUT
Enter length of the rectangle = 12.4
Enter breadth of the rectangle = 6.7
Area of rectangle = 83.079994
Perimeter of rectangle = 166.159988
RESULT
Thus the programs on data types, variables and operators are demonstrated.
10
EX.NO.2 EXPRESSIONS, PRECEDENCE , OPERATORS
DATE:
AIM
To demonstrate Expressions, Precedence and Operators in C
PROGRAM #expressions
#include <stdio.h>
int main() {
int a = 5, b = 10;
int sum = a + b; // Expression
int product = a * b; // Expression
int result = (sum + product) / 2; // Expression using other expressions
OUTPUT
Sum = 15
Product = 50
Result = 32
11
printf("Result 2 ((a + b) * (c / d)) = %d\n", result);
return 0;
}
OUTPUT
Result 1 (a + b * c / d) = 9
Result 2 ((a + b) * (c / d)) = 12
// Arithmetic Operators
printf("Addition: %d\n", x + y);
printf("Subtraction: %d\n", x - y);
printf("Multiplication: %d\n", x * y);
printf("Division: %d\n", x / y);
printf("Modulus: %d\n", x % y);
// Relational Operators
printf("x > y: %d\n", x > y);
printf("x == y: %d\n", x == y);
// Logical Operators
printf("(x > 5) && (y < 5): %d\n", (x > 5) && (y < 5));
return 0;
}
OUTPUT
Addition: 9
Subtraction: 3
Multiplication: 18
Division: 2
Modulus: 0
x > y: 1
x == y: 0
(x > 5) && (y < 5): 1
RESULT
12
EX.NO.3 CONDITIONAL STATEMENTS , SWITCH STATEMENTS
DATE:
AIM
PROGRAM
include <stdio.h> // Include the standard input/output header file.
void main()
{
char ch; // Declare a variable to store a single character.
printf("Input any alphabet : "); // Prompt user for input.
scanf("%c", &ch); // Read and store the character input.
Test case- 2
Input any alphabet : e
output-2
The alphabet is a vowel.
Test case- 3
Input any alphabet : w
output-3
The alphabet is a consonant.
13
EXERCISE-Write a C program to find the maximum of 3 numbers.
PROGRAM
#include <stdio.h>
int main()
{
float n1, n2, n3;
printf("Enter three different numbers: \n");
scanf("%f%f%f",&n1,&n2,&n3);
// if n1 is greater than both n2 and n3, n1 is the largest
if (n1 >= n2 && n1 >= n3)
printf("%.1f is the largest number.", n1);
// if n2 is greater than both n1 and n3, n2 is the largest
if (n2 >= n1 && n2 >= n3)
printf("%.1f is the largest number.", n2);
// if n3 is greater than both n1 and n2, n3 is the largest
if (n3 >= n1 && n3 >= n2)
printf("%.1f is the largest number.", n3);
return 0;
}
OUTPUT
Test case-1
Enter three different numbers:
34
56
78
output-1
78.0 is the largest number.
Test case-2
Enter three different numbers:
45.6
78.9
11.2
output-2
78.9 is the largest number.
Note
• Read N in the first line
• Print output in the second
14
PROGRAM
#include <stdio.h>
int main()
{
int n,flag=1;
scanf("%d",&n);
while(n!=1)
{
if(n%2!=0)
{
flag=0;
break;
}
n=n/2;
}
if(flag)
printf("Yes");
else
printf("No");
return 0;
}
OUTPUT
Test case- 1
16
output-1
Yes
Test case- 2
12
output-2
No
PROGRAM
#include<stdio.h>
void main()
{
int balance=0, deposit, withdraw;
float ci;
char op;
while(1)
{
printf("\nBanking System");
15
printf("\n. .............. ");
printf("\nD ->Deposit");
printf("\nW ->Withdraw");
printf("\nB ->Balance");
printf("\nI ->Interest");
printf("\nQ ->Quit");
printf("\nEnter operation: ");
scanf(" %c", &op);
switch(op)
{
case 'D':
printf("\nEnter deposit amount: ");
scanf("%d", &deposit);
balance += deposit;
break;
case 'W':
printf("\nEnter withdraw amount ");
scanf("%d", &withdraw);
if (balance>withdraw)
{
balance -= withdraw;
break;
}
else
{
printf("withdraw impossible as low balance\n");
break;
}
case 'B':
printf("Balance: Rs.%d", balance);
break;
case 'I':
ci = (float)balance*4/100;
balance += ci;
printf("\nInterest: Rs%.1f", ci);
break;
case 'Q':
return;
default:
printf("Invalid Operation!");
}
}
}
16
B ->Balance
I ->Interest
Q ->Quit
Enter operation: D
Banking System
................
D ->Deposit
W ->Withdraw
B ->Balance
I ->Interest
Q ->Quit
Enter operation: B
Balance: Rs.10000
Banking System
................
D ->Deposit
W ->Withdraw
B ->Balance
I ->Interest
Q ->Quit
Enter operation: I
Interest: Rs400.0
Banking System
................
D ->Deposit
W ->Withdraw
B ->Balance
I ->Interest
Q ->Quit
Enter operation: W
Banking System
................
D ->Deposit
W ->Withdraw
B ->Balance
I ->Interest
Q ->Quit
Enter operation: B
Balance: Rs.7400
Banking System
................
D ->Deposit
W ->Withdraw
17
B ->Balance
I ->Interest
Q ->Quit
Enter operation: Q
// to exit
if (ch == 'x')
exit(0);
printf("Enter two first and second operand: ");
scanf("%lf %lf", &a, &b);
// For Addition
case '+':
printf("%.1lf + %.1lf = %.1lf\n", a, b, a + b);
break;
// For Subtraction
case '-':
printf("%.1lf - %.1lf = %.1lf\n", a, b, a - b);
break;
// For Multiplication
case '*':
printf("%.1lf * %.1lf = %.1lf\n", a, b, a * b);
break;
// For Division
case '/':
printf("%.1lf / %.1lf = %.1lf\n", a, b, a / b);
break;
18
// If operator doesn't match any case constant
default:
printf(
"Error! please write a valid operator\n");
}
printf("\n");
}
}
RESULT
Thus programs written based on conditional statements , switch statements are demonstrated.
19
EX.NO.4 LOOPING AND NESTED LOOPS
DATE:
AIM
Demonstrate looping and nested loops
#include<stdio.h>
int main()
{
long int n,sum=0, term=1,i;
printf("Enter the number of terms\n");
scanf("%ld", &n);
for(i=1;i<=n; i++)
{
printf("%ld ",term);
sum+=term;
term=term*10+1;
}
printf("\n%ld", sum);
return 0;
}
testcase-1
Enter the number of terms
3
output-1
1 11 111
123
testcase-2
4
output-2
1 11 111 1111
1234
20
EXERCISE : Write a C program to find the sum of an Arithmetic Progression (AP) series.
PROGRAM
#include <stdio.h>
int main()
{
int a,n,d,tn,i; //Variable Declaration
int sum = 0; //Sum declaration and initialization
printf("Enter First Number of an A.P Series:\n");
scanf("%d",&a); //First element initialization
printf("Enter the Total Numbers in this A.P Series:\n");
scanf("%d",&n); //total number of elements initialization
printf("Enter the Common Difference:\n");
scanf("%d", &d); //Common difference initialization
sum=(n*(2*a+(n-1)*d))/2; //total sum Formula
tn=a+(n-1)*d; //Last term formula
printf("\nThe Sum of Series A.P. :\n ");
for(i=a;i<= tn;i=i+d)
{
if(i!= tn)
printf("%d + ", i);
else
printf("%d = %d", i, sum);
}
printf("\n");
return 0;
}
testcase-1
Enter First Number of an A.P Series:
1
Enter the Total Numbers in this A.P Series:
5
Enter the Common Difference:
6
output-1
The Sum of Series A.P. :
1 + 7 + 13 + 19 + 25 = 65
testcase-2
Enter First Number of an A.P Series:
6
Enter the Total Numbers in this A.P Series:
6
Enter the Common Difference:
6
expected output-2
The Sum of Series A.P. :
6 + 12 + 18 + 24 + 30 + 36 = 126
21
EXERCISE : Write a C program to determine whether a given number is a perfect number
or not. A positive number is said to be a perfect number if it is equal to the sum of all its
proper divisors. Proper divisors include all the divisors of a number except the number itself.
For example find whether 28 is a perfect number
Step1: Divisors of 28 are 1, 2, 4, 7, 14 and 28
Step 2: Sum of all proper divisor of 28 is
1 + 2 + 4 + 7 + 14 = 28
So 28 is a perfect number.
testcase-1
enter the number:
626
output-1
626 is not a perfect number
testcase-2
enter the number:
496
output-2
496 is a perfect number
22
EXERCISE -program to calculate the sum of squares of digits using a do-while loop.
PROGRAM
#include <stdio.h>
int main()
{
int num, digit, sum = 0;
// Prompt the user to enter a positive integer
printf("Input a positive integer: ");
scanf("%d", &num);
// Check if the entered number is positive
if (num<= 0)
{
printf("Please input a positive integer.\n");
return 1; // Return an error code
}
// Calculate the sum of the squares of each digit
do
{
digit = num % 10; // Extract the last digit
sum += digit * digit; // Add the square of the digit to the sum
num /= 10; // Remove the last digit
} while (num != 0); // Continue the loop until there are no more digits
// Print the sum of the squares of each digit
printf("Sum of the squares of each digit: %d\n", sum);
return 0; // Indicate successful program execution
}
Testcase-1
Input a positive integer: 6
output-1
Sum of the squares of each digit: 36
Testcase-2
Input a positive integer: 100
expected output-1
Sum of the squares of each digit: 1
EXERCISE : Write a C program to display the sum of series 1 + 1/2 + 1/3 + .............. + 1/n.
PROGRAM
#include<stdio.h>
int main()
{
int num,i, sum =0;
// Prompt the user to input a number
printf("Input the number of terms\n");
scanf("%d",&num);
// Display the initial part of the series
23
printf("1 + ");
// Print the series
for(i=2;i<=num-1;i++)
printf(" 1/%d +",i);
EXERCISE : Write a C program to find prime numbers between two intervals, using
a while loop.
PROGRAM
#include<stdio.h>
#include<math.h>
int main()
{
int start, end, count, prime, inum;
printf("Enter start and end value\n");
scanf("%d%d", &start, &end);
printf("\n\nPrime Numbers from %d to %d are:\n", start, end);
while(start <= end)
{
inum = sqrt(start);
count = 2;
prime = 1;
while(count <= inum)
24
{
if(start%count == 0)
{
prime = 0;
break;
}
count++;
}
if(prime) printf("%d, ", start);
start++;
}
printf("\n\n");
return 0;
}
NESTED LOOPS
EXERCISE : Write a C program to display frequency histograms of each group.
PROGRAM
#include <stdio.h>
int main()
{
int marks[50],i,index;
int group[10]={0};
printf("\n enter the marks of 10 students :\n");
for(i=0; i<10; i++)
{
25
printf("marks[%d]= ", i);
scanf("%d", &marks[i]);
++group[(int)(marks[i])/10];
}
printf("\n *************");
i=0;
printf("\n\n FREQUENCY HISTOGRAM");
for (index=0; index<10; index++)
{
printf("\n GROUP %d | ", index);
for(i=0; i<group[index]; i++)
printf(" * ");
}
return 0;
}
*************
FREQUENCY HISTOGRAM
GROUP 0 |
GROUP 1 |
GROUP 2 |
GROUP 3 |
GROUP 4 | *
GROUP 5 |
GROUP 6 |
GROUP 7 | * *
GROUP 8 | * * *
GROUP 9 | * * * *
26
marks[5]= 74
marks[6]= 73
marks[7]= 23
marks[8]= 11
marks[9]= 13
*************
FREQUENCY HISTOGRAM
GROUP 0 | *
GROUP 1 | * *
GROUP 2 | *
GROUP 3 |
GROUP 4 |
GROUP 5 |
GROUP 6 |
GROUP 7 | * * * * * *
GROUP 8 |
GROUP 9 |
*************
FREQUENCY HISTOGRAM
GROUP 0 |
GROUP 1 | *
GROUP 2 | *
GROUP 3 | *
GROUP 4 | *
GROUP 5 | *
GROUP 6 | *
GROUP 7 | *
GROUP 8 | *
GROUP 9 | *
27
EXERCISE: pattern printing
PROGRAM
#include <stdio.h>
int main() {
int i, j;
OUTPUT
*
**
***
****
*****
RESULT
Thus programs based on loops and nested loops are demonstrated.
28
EX.NO.5 PROBLEMS ON BIT MANIPULATION
DATE:
AIM
// Bitwise AND with 1 checks the least significant bit (LSB). If LSB is 1 → odd; If 0 → even.
PROGRAM
#include <stdio.h>
int main() {
int num = 7;
if (num & 1)
printf("%d is Odd\n", num);
else
printf("%d is Even\n", num);
return 0;
}
OUTPUT
7 is Odd
#include <stdio.h>
int main()
{
int a = 5, b = 3;
a = a ^ b;
b = a ^ b;
a = a ^ b;
printf("After swap: a = %d, b = %d\n", a, b);
return 0;
}
OUTPUT
After swap: a = 3, b = 5
29
EXERCISE: Count number of 1s (set bits) in an integer
PROGRAM
#include <stdio.h>
int main() {
int num = 13; // Binary: 1101
int count = 0;
while (num) {
count += num & 1;
num >>= 1;
}
printf("Number of set bits: %d\n", count);
return 0;
}
OUTPUT
Number of set bits: 3
RESULT
Thus the programs based on bit manipulation are demonstrated.
30
EX.NO.6 PATTERNS
DATE:
AIM:
Demonstrate patterns in C
PROGRAM
#include<stdio.h>
int main()
{
int i,j,n;
int count = 1;
printf("\n enter the value of n\n");
scanf("%d",&n);
for (i = 0; i <= n; i++) {
printf("\n");
for (j = 0; j < i; j++) {
printf("%d ", count);
count++;
}
}
return(0);
}
Test case-1
enter the value of n
4
output-1
1
23
45 6
7 8 9 10
Test case-2
enter the value of n
7
output-2
1
23
45 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
31
EXERCISE -Write a C program to print the following N lines of pattern after reading
value for N.
1
11
101
1001
10001
111111
Note
● Read N in the first line
● Print output in the rest of the lines
Constraint on inputs and output:
● N is non negative
● First and last lines contain sequence of 1 always
PROGRAM
#include <stdio.h>
int main()
{
int n,i,j;
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
if(i==1 || i==n ||j==1 || j==i)
printf("1");
else
printf("0");
}
printf("\n");
}
return 0;
}
Sample Input -1
enter n value
2
output-1
1
11
Sample Input -2
enter n value
3
32
output-2
1
11
111
Sample Input- 3
enter n value
6
output
1
11
101
1001
10001
111111
PROGRAM
#include <stdio.h>
int main() {
int i, j, n;
printf("Enter number of rows: ");
scanf("%d", &n);
33
PROGRAM
#include <stdio.h>
int main() {
int i, j, n;
printf("Enter number of rows: ");
scanf("%d", &n);
PROGRAM
#include <stdio.h>
int main() {
int i, j, n;
printf("Enter number of rows: ");
scanf("%d", &n);
RESULT:
Thus the programs based on patterns are demonstrated
34
EX.NO.7 Number problems
DATE:
AIM
#include <stdio.h>
int main() {
int num, i, isPrime = 1;
printf("Enter a number: ");
scanf("%d", &num);
if(isPrime)
printf("%d is a prime number.\n", num);
else
printf("%d is not a prime number.\n", num);
return 0;
}
OUTPUT
Enter a number: 78
78 is not a prime number
int main() {
int num, reversed = 0, remainder, original;
printf("Enter an integer: ");
35
scanf("%d", &num);
original = num;
while (num != 0) {
remainder = num % 10;
reversed = reversed * 10 + remainder;
num /= 10;
}
if (original == reversed)
printf("Palindrome number.\n");
else
printf("Not a palindrome.\n");
return 0;
}
OUTPUT
Enter an integer: 789
Not a palindrome.
int main() {
int num, temp, digits = 0, sum = 0, remainder;
printf("Enter an integer: ");
scanf("%d", &num);
temp = num;
while(temp != 0) {
digits++;
temp /= 10;
}
temp = num;
while(temp != 0) {
remainder = temp % 10;
sum += pow(remainder, digits);
temp /= 10;
}
if(sum == num)
printf("Armstrong number.\n");
else
printf("Not an Armstrong number.\n");
36
return 0;
}
OUTPUT
Enter an integer: 153
Armstrong number.
RESULT
Thus the programs based on number problems are demonstrated
37
EX.NO.8 Array Basics , Static vs Dynamic Array, Two Dimensional Matrix
DATE:
AIM:
Demonstrate Array Basics , Static vs Dynamic Array, Two Dimensional Matrix
EXERCISE- read 'n' numbers into an array and calculate the sum of its elements.
PROGRAM
#include <stdio.h>
int main()
{
float a[100];
int i, n, sum = 0;
printf("Input the number of elements in the array :");
scanf("%d", &n);
printf("Input %d elements in the array :\n", n);
for (i = 0; i < n; i++)
{
printf("element - %d : ", i);
scanf("%f", &a[i]);
}
for (i = 0; i < n; i++)
{
sum += a[i];
}
printf("Sum of all elements stored in the array is : %d\n\n", sum);
return 0;
}
Test case-1
Input the number of elements in the array :4
Input 4 elements in the array :
element - 0 : 76
element - 1 : 54
element - 2 : 32
element - 3 : 10
output-1
Sum of all elements stored in the array is : 172
Test case-2
Input the number of elements in the array :4
Input 4 elements in the array :
element - 0 : 12.3
element - 1 : 56.7
element - 2 : 89.5
element - 3 : 34.2
Expected output-2
Sum of all elements stored in the array is : 191
38
EXERCISE : Write a C program to count even and odd elements in an array.
PROGRAM
#include <stdio.h>
int main()
{
int arr[100];
int i, N, even, odd;
printf("Enter size of the array: ");
scanf("%d", &N);
printf("\nEnter %d elements in array :: ", N);
for(i=0; i<N; i++)
{
printf("\nEnter %d element in array :: ", i+1);
scanf("%d", &arr[i]);
}
even = 0;
odd = 0;
for(i=0; i<N; i++)
{
/* If the current element of array is even then increment even count */
if(arr[i]%2 == 0)
even++;
else
odd++;
}
printf("\nTotal even elements: %d\n", even);
printf("\nTotal odd elements: %d\n", odd);
return 0;
}
Test Case -1
Enter size of the array: 5
Enter 5 elements in array :: 12 34 89 77 66
output-1
Total even elements: 3
Total odd elements: 2
Test Case -2
Enter size of the array: 4
Enter 4 elements in array :: -1 -44 -77 -99
Expected output-2
Total even elements: 1
Total odd elements: 3
39
EXERCISE : Write a C program to print the transpose of a matrix.
PROGRAM
#include <stdio.h>
int main()
{
int m, n, i, j;
// Requesting the dimensions of the matrix from the user
printf("Enter the number of rows and columns of the matrix: ");
scanf("%d%d", &m, &n);
int A[m][n], Transposed[n][m];
// Capturing the matrix elements from the user
printf("Enter the elements of the matrix:\n");
for(i = 0; i < m; i++) {
for(j = 0; j < n; j++) {
printf("A[%d][%d] = ", i+1, j+1);
scanf("%d", &A[i][j]);
}
}
for(i = 0; i < m; i++) {
for(j = 0; j < n; j++) {
Transposed[j][i] = A[i][j];
}
}
// Displaying the transpose
printf("\nTranspose of the matrix is:\n");
for(i = 0; i < n; i++) {
for(j = 0; j < m; j++) {
printf("%d ", Transposed[i][j]);
}
printf("\n");
}
return 0;
}
Testcase-1
Enter the number of rows and columns of the matrix:
2
2
Enter the elements of the matrix:
A[1][1] = 1
A[1][2] = 2
40
A[2][1] = 3
A[2][2] = 4
output-1
Transpose of the matrix is:
1 3
2 4
Testcase-2
Enter the number of rows and columns of the matrix: 2
3
Enter the elements of the matrix:
A[1][1] = 11
A[1][2] = 22
A[1][3] = 33
A[2][1] = 44
A[2][2] = 55
A[2][3] = 66
output-2
Transpose of the matrix is:
11 44
22 55
33 66
41
printf("enter the number of columns in second matrix=");
scanf("%d",&col2);
if (col1!=row2)
{
printf("matrix multiplication impossible\n");
return 0;
}
printf("enter the second matrix element=\n");
for(i=0;i<row2;i++)
{
for(j=0;j<col2;j++)
{
scanf("%d",&b[i][j]);
}
}
printf("multiply of the matrix=\n");
for(i=0;i<row1;i++)
{
for(j=0;j<col2;j++)
{
mul[i][j]=0;
for(k=0;k<row2;k++)
{
mul[i][j]+=a[i][k]*b[k][j];
}
}
}
//for printing result
for(i=0;i<row1;i++)
{
for(j=0;j<col2;j++)
{
printf("%d\t",mul[i][j]);
}
printf("\n");
}
return 0;
}
TESTCASES
Testcase-1 and output-1
enter the number of rows in first matrix=2
enter the number of columns in second matrix=3
enter the first matrix element=
1
2
3
4
42
5
6
enter the number of rows in second matrix=4
enter the number of columns in second matrix=5
matrix multiplication impossible
EXERCISE : Write a C Program to merge two arrays entered by the user at run-time.
PROGRAM
#include <stdio.h>
int main() {
int a[100], b[100], merged[200];
int n1, n2, i, j;
43
// Merge arrays
for (i = 0; i < n1; i++) {
merged[i] = a[i];
}
for (j = 0; j < n2; j++) {
merged[i + j] = b[j];
}
if (n == 0 || n == 1)
return n;
int temp[n];
int j = 0;
int i;
for (i = 0; i< n - 1; i++)
if (arr[i] != arr[i + 1])
temp[j++] = arr[i];
temp[j++] = arr[n - 1];
44
for (i = 0; i< j; i++)
arr[i] = temp[i];
return j;
}
int main()
{
int n, arr[100], i;
printf("enter the size of the elements\n");
scanf("%d", &n);
printf("enter the elements\n");
for (i = 0; i< n; i++)
{
scanf("%d", &arr[i]);
}
printf("\nArray Before Removing Duplicates: ");
for (i = 0; i< n; i++)
printf("%d ", arr[i]);
n = remove_duplicate(arr, n);
printf("\nArray After Removing Duplicates: ");
for (i = 0; i< n; i++)
printf("%d ", arr[i]);
return 0;
}
45
EXERCISE : Demonstrate dynamic arrays
PROGRAM
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr;
int n, i;
// Print elements
printf("You entered:\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
// Free the allocated memory
free(arr);
return 0;
}
OUTPUT
Enter the number of elements: 5
Enter 5 elements:
11
77
66
55
44
You entered:
11 77 66 55 44
RESULT:
Thus programs based on Array Basics , Static vs Dynamic Array, Two Dimensional Matrix were
demonstrated.
46
EX.NO.9 Structure , Union and Storage Classes
DATE:
AIM:
Demonstrate Structure , Union and Storage Classes.
EXERCISE- Write a C program to get details about two students and display their details
using structure members. This program is used to store and access information such as
name, roll number, and marks.
PROGRAM
/* Program to display the values of structure members*/
#include<stdio.h>
#include<string.h>
struct student
{
char name[20];
int rollno;
float marks;
};
int main()
{
struct student stu1, stu2, stu3;
printf("Enter name, rollno and marks for stu1 : ");
scanf("%s %d %f", stu1.name, &stu1.rollno, &stu1.marks);
printf("Enter name, rollno and marks for stu2 : ");
scanf("%s %d %f", stu2.name, &stu2.rollno, &stu2.marks);
printf("stu1 : %s %d %.2f\n", stu1.name, stu1.rollno, stu1.marks);
printf("stu2 : %s %d %.2f\n", stu2.name, stu2.rollno, stu2.marks);
return 0;
}
Test case-1
Enter name, rollno and marks for stu1 : GANESH 101 99
Enter name, rollno and marks for stu2 : SIVA 203 87
Expected output-1
stu1 : GANESH 101 99
stu2 : SIVA 203 87
Test case-2
Enter name, rollno and marks for stu1 : anjali 244 86
Enter name, rollno and marks for stu2 : kumar 203 65
Expected output-2
stu1 : anjali 244 86
stu2 : kumar 203 65
47
EXERCISE - Write a C program to display a structure using the typedef keyword. The
structure should contain fields for name, id, age, and native.
PROGRAM
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct
{
char name[30];
int id;
int age;
char native[50];
} employee;
void main()
{
employee emp;
//assign values to emp
printf("\n Enter empname, id, age and native\n");
scanf("%s %d %d %s", emp.name, emp.id, emp.age, emp.native);
printf("Employee detail:\n");
printf("Name: %s\n",emp.name);
printf("Age: %d\n",emp.age);
printf("id: %d\n",emp.id);
printf("native: %s\n",emp.native);
}
testcase-1
Enter empname, id, age and native
hithesh 101 18 chennai
expected output-1
Employee detail:
Name:hithesh
Age:18
id: 101
native: chennai
testcase-2
Enter empname, id, age and native
srikanth 102 19 vellore
expected output-2
Employee detail:
Name:srikanth
id:19
Age: 102
native: vellore
48
EXERCISE - Write a C program to add two distances in feet and inches using union.
PROGRAM
#include <stdio.h>
union DistancePart {
int feet;
int inches;
};
struct Distance {
union DistancePart f;
union DistancePart i;
};
int main() {
struct Distance d1, d2, sum;
OUTPUT
Enter first distance:
Feet: 12
Inches: 10
Enter second distance:
Feet: 12
Inches: 10
49
EXERCISE : Define a structure called student that contains fields for name, registration
number (regno), marks of subjects, and percentage. Write a C program to read the name,
regno, and marks of 5 subjects for 5 students. Then, sort the students in ascending order
based on their total marks.
PROGRAM
#include <stdio.h>
struct Student
{
char name[50];
int regno;
int marks[5];
float percentage;
int totalMarks;
};
// Function to calculate total marks and percentage
void calculate(struct Student *student)
{
student->totalMarks = 0;
for (int i = 0; i < 5; ++i)
{
student->totalMarks += student->marks[i];
}
student->percentage = (float)student->totalMarks / 5;
}
}}}
}
int main()
{
// Declare an array of 5 students
struct Student students[5];
for(int i = 0; i < 5; ++i)
50
{
printf("Enter details for student %d:\n", i + 1);
printf("Name: ");
scanf("%s", students[i].name);
printf("Registration Number: ");
scanf("%d", &students[i].regno);
printf("Enter marks for 5 subjects:\n");
for(int j = 0; j < 5; ++j)
{
printf("Subject %d: ", j + 1);
scanf("%d", &students[i].marks[j]);
}
calculate(&students[i]);
}
sortStudents(students, 5);
printf("\nSorted list of students in ascending order of total marks:\n");
for(int i = 0; i < 5; ++i)
{
printf("Name: %s, Registration Number: %d, Total Marks: %d,Percentage: %.2f%%\n",
students[i].name, students[i].regno, students[i].totalMarks, students[i].percentage);
}
return 0;
}
51
Subject 4: 88
Subject 5: 77
Enter details for student 4:
Name: RANJITH
Registration Number: 222
Enter marks for 5 subjects:
Subject 1: 55
Subject 2: 56
Subject 3: 57
Subject 4: 54
Subject 5: 50
Enter details for student 5:
Name: KUMAR
Registration Number: 333
Enter marks for 5 subjects:
Subject 1: 35
Subject 2: 56
Subject 3: 67
Subject 4: 33
Subject 5: 52
void demoStatic() {
static int staticVar = 0; // static variable retains its value
staticVar++;
printf("Static variable value: %d\n", staticVar);
}
int main() {
// auto variable (default for local variables)
auto int autoVar = 10;
printf("Auto variable value: %d\n", autoVar);
52
// calling function to see static variable behavior
demoStatic(); // Output: 1
demoStatic(); // Output: 2
demoStatic(); // Output: 3
return 0;
}
OUTPUT
Auto variable value: 10
Register variable value: 20
Static variable value: 1
Static variable value: 2
Static variable value: 3
Extern variable value: 50
RESULT
Thus programs based on Structure , Union ,Storage Classes are demonstrated
53
EX.NO.10 FUNCTIONS AND PARAMETER PASSING
DATE:
AIM:
To demonstrate functions and parameter passing
OUTPUT
Enter a number: 3
Square of 3 is 9
54
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Sorted array:\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
OUTPUT
// Pass by value
void passByValue(int a) {
a = a + 10;
printf("Inside passByValue: a = %d\n", a);
}
// Pass by reference
void passByReference(int *b) {
*b = *b + 10;
printf("Inside passByReference: b = %d\n", *b);
}
int main() {
int x = 5, y = 5;
55
printf("Before passByValue: x = %d\n", x);
passByValue(x);
printf("After passByValue: x = %d\n\n", x);
return 0;
}
OUTPUT
Before passByValue: x = 5
Inside passByValue: a = 15
After passByValue: x = 5
Before passByReference: y = 5
Inside passByReference: b = 15
After passByReference: y = 15
RESULT:
Thus the programs based on functions and passing parameters are demonstrated
56
EX.NO.11 Recursion
DATE:
EXERCISE-Write a C program to print the first n natural numbers in reverse order using
recursion.
PROGRAM
#include<stdio.h>
int numPrint(int);
void main()
{
int n;
printf(" print n value :");
scanf("%d",&n);
numPrint(n);
}
int numPrint(int n)
{ printf("\n");
if (n!=0)
{
printf("%d\n",n);
numPrint(n-1);
}
}
Test case -1
print n value :5
Expected output-1
5 4 3 2 1
Test case -2
print n value :10
Expected output-2
10 9 8 7 6 5 4 3 2 1
Test case -3
print n value :4.5
Expected output-3
4 3 2 1
57
EXERCISE - Write a C program to find the Highest Common Factor (HCF) of given
numbers using recursion.
PROGRAM
#include <stdio.h>
int HCF(int num1, int num2)
{
while (num1 != num2)
{
if (num1 > num2)
return HCF(num1 - num2, num2);
else
return HCF(num1, num2 - num1);
}
return num1;
}
int main()
{
int num1 = 0;
int num2 = 0;
testcase-1
Enter Number 1: 34
Enter Number 2: 68
expected output-1
The Highest Common Factor is: 34
testcase-2
Enter Number 1: 1246
Enter Number 2: 6789
expected output-2
The Highest Common Factor is: 1
58
EXERCISE -Write a C program to find the sum of array elements using recursion.
PROGRAM
#include <stdio.h>
int sum(int arr[], int start, int len);
int main()
{
int arr[100];
int N, i,soa;
Test case-1
Enter size of the array: 5
Enter elements in the array: 1 2 3 4 5
Expected Output-1
Sum of array elements: 15
Test case-2
Enter size of the array: 8
Enter elements in the array: 1 2 3 4 5 6 7 8
Expected Output-2
Sum of array elements: 36
RESULT:
Thus programs based on recursion are demonstrated.
59
EX.NO.12 STRINGS
DATE:
Structure , Union ,Storage Classes
AIM:
To demonstrate programs based on strings
EXERCISE- program to copy the content of one string, S1, into another string, S2, while
removing characters other than alphabets and spaces.
Note
• Maximum size of each string can be 1000
• Read input string in the first line
• Print output string in the second in the second
Constraints
• Input string can contain alphabets, space, digits, and any other special characters
• Output string must contain alphabets and space alone
PROGRAM
#include <stdio.h>
#include<ctype.h>
#nclude<string.h>
int main()
{
char s1[1000],s2[1000];
int i=0,j=0;
printf("enter the string\n");
gets(s1);
while(s1[i]!='\0')
{
if(isalpha(s1[i]) || isspace(s1[i]))
{
s2[j++]=s1[i];
}
i++;
}
s2[j]='\0';
puts(s2);
return 0;
}
Test case- 1
abcd 123 ***
Expected output-1
abcd
60
Test case- 2
123 io 56 nm
Expected output-2
io nm
EXERCISE-Write a C program to read a string from the first line and print the middle
three characters if the length of the string is odd. Otherwise, print the middle two characters
on the next line as output.
Note
Read string in the first line
Print the middle characters in the second line
Constraint on inputs:
The input string can contain space also
PROGRAM
#include <stdio.h>
#include <string.h>
int main()
{
char s[100];
int isOdd,mid,slength;
gets(s);
slength=strlen(s);
if(slength%2==0)
isOdd=0;
else
isOdd=1;
mid=slength/2;
if(isOdd)
printf("%c%c%c",s[mid-1],s[mid],s[mid+1]);
else
printf("%c%c",s[mid-1],s[mid]);
return 0;
}
Test case-1
malayalam
Expected output-1
aya
Test case-2
abcd
Expected output-2
bc
61
EXERCISE-Write a C program to print individual characters of a string in reverse order.
PROGRAM
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char str[100]; /* Declares a string of size 100 */
int l, i; // Declare variables for string length and loop iteration
printf("Input the string : ");
scanf("%s",str);
l = strlen(str); // Calculate the length of the string
printf("The characters of the string in reverse are : \n");
// Loop to print each individual character of the string in reverse order
for (i = l - 1; i >= 0; i--)
{
printf("%c ", str[i]); // Print each character in reverse order
}
}
Test case -1
Input the string : 56778
Expected output
The characters of the string in reverse are :
8 7 7 6 5
Test case -2
Input the string : welcome
Expected output
The characters of the string in reverse are :
e m o c l e w
EXERCISE : Write a C program to swap two strings using the strcpy() function.
PROGRAM
#include<stdio.h>
#include<string.h>
int main()
{
char str1[50], str2[50], temp[50];
printf("Enter the First String: ");
gets(str1);
printf("Enter the Second String: ");
gets(str2);
printf("\nString before Swap:\n");
printf("First String = %s\tSecond String = %s", str1, str2);
strcpy(temp, str1);
strcpy(str1, str2);
strcpy(str2, temp);
62
printf("\n\nString after Swap:\n");
printf("First String = %s\tSecond String = %s", str1, str2);
return 0;
}
testcase-1
Enter the First String: hello
Enter the Second String: welcome
expected output-1
String before Swap:
First String = hello Second String = welcome
String after Swap:
First String = welcome Second String = hello
testcase-2
Enter the First String: I AM IN CHENNAI
Enter the Second String: YOU ARE MY FRIEND
expected output-2
String before Swap:
First String = I AM IN CHENNAI Second String = YOU ARE MY FRIEND
String after Swap:
First String = YOU ARE MY FRIEND Second String = I AM IN CHENNAI
EXERCISE : Write a C program to count the total number of alphabets, digits, and special
characters in a string.
PROGRAM
#include <stdio.h>
#include <ctype.h>
void main()
{
int i=0,alphabets=0,numbers=0,special=0;
char str[100];
printf("Enter any string: ");
gets(str);
while(str[i] != '\0')
{
if(isalpha(str[i]) != 0) alphabets++;
else if(isdigit(str[i]) != 0) numbers++;
else if(isspace(str[i]) != 0) ;
else special++;
i++;
}
printf("Alphabets = %d",alphabets);
printf("\nNumbers = %d",numbers);
printf("\nSpecial Characters = %d",special);
}
testcase-1
Enter any string: i love my country @#$% india 123
63
expected output-1
Alphabets = 19
Numbers = 3
Special Characters = 4
testcase-2
Enter any string: my name is !@#$ kumar 789
expected output-2
Alphabets = 13
Numbers = 3
Special Characters = 4
EXERCISE - program to count the number of vowels and consonants in the given string.
PROGRAM
#include <stdio.h>
void count(char* str)
{
// Declare the variable vowels and consonant
int vowels = 0, consonants = 0;
int i;
char ch;
// Take each character from this string to check
for (i = 0; str[i] != '\0'; i++)
{
ch = str[i];
if (ch == 'a' || ch == 'e'|| ch == 'i' || ch == 'o'|| ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I'|| ch == 'O'
|| ch == 'U')
vowels++;
else if (ch == ' ')
continue;
else
consonants++;
}
// Print the total count of vowels and consonants
printf("\nVowels: %d", vowels);
printf("\nConsonants: %d", consonants);
}
int main()
{
char* str = "india is my country";
printf("String: %s", str);
count(str);
return 0;
}
64
india is my country
String: india is my country
Vowels: 6
Consonants: 10
65
Testcase-1 and output-1
Enter any string: i love india
Enter character to replace: i
Enter character to replace 'i' with: p
RESULT:
Thus the programs based on strings are demonstrated.
66
EX.NO.13 POINTERS
DATE:
AIM
To demonstrate pointers in C
Test case -1 :
Input the first number : 67
Input the second number : 89
Expected output-1
The sum of the entered numbers is : 156
Test case -2
Input the first number : 12345
Input the second number : 765
Expected output-2
The sum of the entered numbers is : 13110
EXERCISE - program to find the maximum of n numbers using pointers, utilizing the
malloc() function.
PROGRAM
#include <stdio.h>
#include <conio.h>
#include<stdlib.h>
int main()
{
int n,*p,i,h=0;
printf("How many numbers u want :: ");
67
scanf("%d",&n);
p=(int *) malloc(sizeof(int));
for(i=0;i<n;i++)
{
printf("Enter Number %d :: ",i+1);
scanf("%d",p+i);
}
h=*p;
for(i=1;i<n;i++)
{
if(*(p+i)>h)
h =*(p+i);
}
printf("\nThe Largest Number is %d \n",h);
return 0;
}
testcase-1
How many numbers u want :: 5
Enter Number 1 :: 11
Enter Number 2 :: 2
Enter Number 3 :: 55
Enter Number 4 :: 77
Enter Number 5 :: 90
expected output-1
The Largest Number is 90
testcase-2
How many numbers u want :: 3
Enter Number 1 :: 778
Enter Number 2 :: 999
Enter Number 3 :: 234
expected output-2
The Largest Number is 999
68
for(i=0;i<n;i++)
{
scanf("%d", &a[i]);
}
p=&a[0];
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(*(p+i)>*(p+j))
{
*(p+i) = *(p+i)+ *(p+j);
*(p+j) = *(p+i)- *(p+j);
*(p+i) = *(p+i)- *(p+j);
}
}
}
printf("\n Sorted Values : ");
for(i=0;i<n;i++)
{
printf("%d ",*(p+i));
}
return 0;
}
69
printf("Error!!! memory not allocated.");
exit(0);
}
// Storing numbers entered by the user.
for (int i = 0; i< n; ++i) {
printf("Enter number%d: ", i + 1);
scanf("%lf", data + i);
}
free(data);
return 0;
}
RESULT
Thus the programs based on pointers are demonstrated.
70
EX.NO.14 Command Line Arguments, Pre-processors
DATE:
AIM:
Demonstrate Command Line Arguments, Pre-processors
EXERCISE - Write a C program to find the sum of N integer numbers using command
line arguments.(Note: store the name of the program as example.c)
PROGRAM
#include <stdio.h>
int main(int argc, char *argv[])
{
int a, b, sum;
int i; //for loop counter
if(argc<2)
{
printf("please use \"program name value1 value2 ... \"\n");
return -1;
}
sum=0;
for(i=1; i<argc; i++)
{
printf("arg[%d]: %d\n",i, atoi(argv[i]));
sum += atoi(argv[i]);
}
printf("Sum of all values: %d\n",sum);
return 0;
}
testcase-1
example 12 20
expected output-1
arg[1] : 12
arg[2] : 22
Sum of all values: 34
testcase-2
example 12.5 22.5
expected output-2
arg[1] : 12
arg[2] :22
Sum of all values: 34
71
EXERCISE : Demonstrate preprocessors
PROGRAM
#include <stdio.h> // Preprocessor directive to include standard I/O library
#define PI 3.14159 // Macro definition
#define AREA(r) (PI * (r) * (r)) // Macro with parameter
#define SHOW // Used for conditional compilation
int main() {
int radius = 5;
#ifdef SHOW
printf("SHOW is defined\n");
#endif
#undef SHOW
#ifdef SHOW
printf("This will not be printed\n");
#else
printf("SHOW is undefined now\n");
#endif
return 0;
}
OUTPUT
Radius = 5
Area of Circle = 78.54
SHOW is defined
SHOW is undefined now
RESULT:
Thus the programs based on command line arguments and preprocessors are demonstrated.
72
EX.NO.15 File Handling & Exception Handling.
DATE:
AIM:
Demonstrate file handling and exception handling methods.
EXERCISE :
Creates a file named example.txt.
Writes two lines into it.
Closes the file.
Reopens it in read mode, reads content line-by-line using fgets(), and prints it.
PROGRAM
#include <stdio.h>
int main() {
FILE *fp;
char str[100];
// Writing to a file
fp = fopen("example.txt", "w"); // Open file in write mode
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
fprintf(fp, "Welcome to File Handling in C!\n");
fputs("This is another line.\n", fp);
fclose(fp); // Close the file after writing
printf("File content:\n");
while (fgets(str, sizeof(str), fp) != NULL) {
printf("%s", str); // Print each line
}
73
return 0;
}
OUTPUT
example.txt file created and contents are
Welcome to File Handling in C!
This is another line.
int main() {
FILE *fp;
char ch;
int wordCount = 0;
int inWord = 0;
fclose(fp);
printf("Total number of words: %d\n", wordCount);
return 0;
}
sample.txt
hello how are you
i am fine
OUTPUT
Total number of words: 7
74
EXERCISE : Write a C program to copy the content of one text file into another text file.
PROGRAM
#include <stdio.h>
#include <stdlib.h> // For exit()
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;
OUTPUT
File2.txt
Welcome to File Handling in C!
This is another line.
jmp_buf buffer;
int main() {
int a = 10, b = 0;
if (setjmp(buffer)) {
75
printf("Error: Division by zero!\n");
} else {
if (b == 0) {
longjmp(buffer, 1); // Jump to error handler
} else {
printf("Result = %d\n", a / b);
}
}
return 0;
}
OUTPUT
Error: Division by zero!
jmp_buf jump_buffer;
int main() {
int arr[5] = {10, 20, 30, 40, 50};
int index = 7;
if (setjmp(jump_buffer))
{
printf("Error: Array index out of bounds!\n");
}
else {
if (index < 0 || index >= 5) {
longjmp(jump_buffer, 1); // Go to error handler
} else {
printf("Value = %d\n", arr[index]);
}
}
return 0;
}
OUTPUT
Error: Array index out of bounds!
RESULT:
Thus programs based on file handling and exception handling are demonstrated.
76
23ES1212 -TECHNICAL SKILL PRACTICES I
(ADDITIONAL PROGRAMS)
#include <stdio.h>
void main()
{
int i;
for (i = 10; i>= 1; i--)
{
printf("%d\t", i);
}
}
OUTPUT
10 9 8 7 6 5 4 3 2 1
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
char str[15]="panimalar";
for (i=0;i<8;i++)
{
printf("%c", str[i]);
}
getch();
}
OUTPUT
panimala
#include <stdio.h>
#define PI 3.14f /* Define the value of pie */
void main()
{
/* Variable Declaration. */
float radius, perimeter, area;
77
scanf("%f", & radius);
OUTPUT
Enter radius of the Circle:
6
Perimeter of the circle: 37.6800
Area of circle: 113.0400
// Calculate factorial
for (i = 1; i<= num; i++)
{
fact =fact* i;
}
printf("Factorial of %d is %d\n", num, fact);
}
OUTPUT
Enter a number: 5
Factorial of 5 is 120
#include <stdio.h>
void main()
{
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
78
for (i = 2; i <= n / 2; ++i)
{
if (n % i == 0)
{
flag = 1;
break;
}
}
// flag is 0 for prime numbers
if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);
}
OUTPUT
Enter a positive integer: 5
5 is a prime number.
6. PROGRAM TO CONVERT THE TEMPERATURE GIVEN IN FAHRENHEIT TO
CELSIUS AND VICE VERSA USING THE FOLLOWING FORMULA:
PROGRAM
#include <stdio.h>
void main()
{
int choice;
float temperature, converted;
printf("Temperature Conversion:\n");
printf("1. Celsius to Fahrenheit\n");
printf("2. Fahrenheit to Celsius\n");
printf("Enter your choice (1 or 2): ");
scanf("%d", &choice);
if (choice == 1)
{
printf("Enter temperature in Celsius: ");
scanf("%f", &temperature);
converted = (temperature * 9.0 / 5.0) + 32;
printf("Temperature in Fahrenheit: %.2f\n", converted);
}
else if (choice == 2)
{
printf("Enter temperature in Fahrenheit: ");
scanf("%f", &temperature);
79
converted = (temperature - 32) * 5.0 / 9.0;
printf("Temperature in Celsius: %.2f\n", converted);
}
else
printf("Invalid choice.\n");
}
OUTPUT
Temperature Conversion:
1. Celsius to Fahrenheit
2. Fahrenheit to Celsius
Enter your choice (1 or 2): 1
Enter temperature in Celsius: 37
Temperature in Fahrenheit: 98.60
#include <stdio.h>
void main()
{
int n,i,s[10],d[10];
// Input the size of the array
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("Enter the elements of the source array:\n");
for (i = 0; i< n; i++)
{
scanf("%d",&s[i]);
}
for (i = 0; i< n; i++)
{
d[i] = s[i];
}
OUTPUT
Enter the number of elements: 5
Enter the elements of the source array:
8
66
77
33
44
80
Elements of the destination array:
8 66 77 33 44
#include <stdio.h>
// Function to perform Selection Sort
void selectionSort(int arr[], int n)
{
int i, j, minIndex, temp;
// Traverse through all array elements
for (i = 0; i< n - 1; i++)
{
// Find the minimum element in unsorted part
minIndex = i;
for (j = i + 1; j < n; j++)
{
if (arr[j] <arr[minIndex])
minIndex = j;
}
// Swap the found minimum element with the first element
if (minIndex != i)
{
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
} //close outer for loop
} //close selectionsort()
void main()
{
int n,i,arr[20];
printf("Enter the number of elements: ");
scanf("%d", &n);
81
printf("%d ", arr[i]);
}
printf("\n");
}
OUTPUT
OUTPUT
Enter the number of elements: 7
Enter the elements:
6
7
4
99
80
87
82
56
Sum: 339.00
Mean: 48.43
#include <stdio.h>
struct Student
{
int rollNo;
char name[50];
int mark1;
int mark2;
int mark3;
int totalMarks;
float average;
};
int main()
{
struct Student student;
// Input student details
printf("Enter Roll Number: ");
scanf("%d", &student.rollNo);
printf("Enter Name: ");
scanf(" %s", student.name);
// Input marks for 3 subjects
printf("Enter marks for Subject 1: ");
scanf("%d", &student.mark1);
printf("Enter marks for Subject 2: ");
scanf("%d", &student.mark2);
printf("Enter marks for Subject 3: ");
scanf("%d", &student.mark3);
// Calculate total and average
student.totalMarks = student.mark1 + student.mark2 + student.mark3;
student.average = student.totalMarks / 3.0;
// Display mark statement
printf("\n--- Mark Statement ---\n");
printf("Roll Number: %d\n", student.rollNo);
printf("Name: %s\n", student.name);
printf("Marks:\n");
printf(" Subject 1: %d\n", student.mark1);
printf(" Subject 2: %d\n", student.mark2);
printf(" Subject 3: %d\n", student.mark3);
printf("Total Marks: %d\n", student.totalMarks);
printf("Average Marks: %.2f\n", student.average);
}
83
OUTPUT
Enter Roll Number: 878
Enter Name: HARISH
Enter marks for Subject 1: 90
Enter for Subject 2: 77
Enter marks for Subject 3: 89
// Input marks
printf("Enter Marks: ");
scanf("%f", &student.marks);
printf("Marks: %.2f\n", student.marks);
// Input grade
printf("Enter Grade: ");
scanf(" %c", &student.grade);
printf("Grade: %c\n", student.grade);
return 0;
}
OUTPUT
Enter Roll Number:101
Roll Number: 101
Enter Marks: 89
Marks: 89.00
Enter Grade: O
Grade: O
84
C PROGRAM TO FIND AVERAGE OF NUMBERS STORED IN SEQUENTIAL
12. MANNER.
Step 1: open turboc editor, type the following program and name it as seq.c
#include <stdio.h>
void main()
{
FILE *file;
float num, sum = 0.0;
int count = 0;
// Open the file in read mode
file = fopen("numbers.txt", "r");
if (file == NULL) {
printf("Could not open file.\n");
return 1;
}
// Read numbers from the file and calculate sum and count
while (fscanf(file, "%f", &num) != EOF)
{
sum += num;
count++;
}
// Check if any numbers were read
if (count == 0) {
printf("No numbers to calculate average.\n");
}
else {
float average = sum / count;
printf("Average of numbers: %.2f\n", average);
}
fclose(file);
}
Step 2 : open a turboc editor, type the followingnumbers and save the file as numbers.txt:
10.5
20.8
30.2
15.0
25.7
Step 3: now run the file seq.c you will get following output
Average of numbers:20.4
Step 1 : open a new file in turboc editor, type the following contents and save the file as
example.txt
85
Welcome to Panimalar engineering college
#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *file;
char ch;
int i,size;
// Open the file in read mode
file = fopen("example.txt", "r");
if (file == NULL)
{
printf("Could not open the file.\n");
}
// Move to the end of the file
fseek(file, 0, SEEK_END);
// Get the size of the file
size = ftell(file);
// Read and display the contents in reverse order
for (i = size - 1; i>= 0; i--)
{
fseek(file, i, SEEK_SET);
ch = fgetc(file);
putchar(ch);
}
fclose(file);
}
Step 3: now run above file and you can see output
#include <stdio.h>
struct Employee {
int id;
char name[30];
float basicSalary;
float hra;
float da;
float grossSalary;
};
86
int main() {
struct Employee emp;
// Input
printf("Enter Employee ID: ");
scanf("%d", &emp.id);
// Calculations
emp.hra = 0.20 * emp.basicSalary; // 20% HRA
emp.da = 0.10 * emp.basicSalary; // 10% DA
emp.grossSalary = emp.basicSalary + emp.hra + emp.da;
// Output
printf("\n--- Employee Payroll ---\n");
printf("ID: %d\n", emp.id);
printf("Name: %s\n", emp.name);
printf("Basic Salary: %.2f\n", emp.basicSalary);
printf("HRA: %.2f\n", emp.hra);
printf("DA: %.2f\n", emp.da);
printf("Gross Salary: %.2f\n", emp.grossSalary);
return 0;
}
OUTPUT
15 C program to check whether a given number is Armstrong number or not using command
line argument.
Step 1: open turboc editor, create a new file and save it as commandline.c
87
//commandline.c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void main(int argc, char *argv[])
{
int num = atoi(argv[1]), originalNum = num, sum = 0, digit, n = 0;
if (argc != 2)
{
printf("Enter a number as a command line argument\n");
return 1;
}
// Find the number of digits in the number
while (num != 0) {
num /= 10;
n++;
}
num = originalNum;
// Calculate the sum of digits raised to the power of the number of digits
while (num != 0)
{
digit = num % 10;
sum += pow(digit, n);
num /= 10;
}
if (sum == originalNum)
printf("%d is an Armstrong number.\n", originalNum);
else
printf("%d is not an Armstrong number.\n", originalNum);
}
Step 2 : open the DOS shell in File menu of the turboc editor, and type c:\tc\bin\ commandline
153
Output - 153 is an Armstrong number
Step 3: open the DOS shell in File menu of the turboc editor, and type
type c:\tc\bin\ commandline 11
output - 11 is not an Armstrong number
int main() {
int choice;
float balance = 10000.0, deposit, withdraw;
int pin, enteredPin;
88
printf("Welcome to ATM Machine Simulation!\n");
printf("Enter your PIN: ");
scanf("%d", &enteredPin);
if(enteredPin != pin) {
printf("Incorrect PIN. Access Denied!\n");
return 0;
}
do {
printf("\n===== ATM Menu =====\n");
printf("1. Check Balance\n");
printf("2. Deposit Money\n");
printf("3. Withdraw Money\n");
printf("4. Exit\n");
printf("Enter your choice (1-4): ");
scanf("%d", &choice);
switch(choice) {
case 1:
printf("Your current balance is: Rs. %.2f\n", balance);
break;
case 2:
printf("Enter amount to deposit: Rs. ");
scanf("%f", &deposit);
if(deposit > 0) {
balance += deposit;
printf("Deposit successful! New balance: Rs. %.2f\n", balance);
} else {
printf("Invalid deposit amount!\n");
}
break;
case 3:
printf("Enter amount to withdraw: Rs. ");
scanf("%f", &withdraw);
if(withdraw > 0 && withdraw <= balance) {
balance -= withdraw;
printf("Withdrawal successful! New balance: Rs. %.2f\n", balance);
} else {
printf("Invalid withdrawal amount or Insufficient balance!\n");
}
break;
case 4:
printf("Thank you for using ATM. Goodbye!\n");
break;
89
default:
printf("Invalid choice! Please select 1-4.\n");
}
} while(choice != 4);
return 0;
}
OUTPUT
Welcome to ATM Machine Simulation!
Enter your PIN: 1234
90
3. Withdraw Money
4. Exit
Enter your choice (1-4):
17. Student Marks Management System
Store roll number, name, and marks for 3 subjects.
Calculate total and average.
Find the student with the highest average.
Allow the user to input multiple students.
program
#include <stdio.h>
struct Student {
int roll;
char name[50];
int marks[3];
int total;
float average;
};
int main() {
struct Student s[100];
int n, i, j;
s[i].total = 0;
for(j = 0; j < 3; j++) {
printf("Enter marks for subject %d: ", j+1);
scanf("%d", &s[i].marks[j]);
s[i].total += s[i].marks[j];
}
s[i].average = s[i].total / 3.0;
}
printf("\nStudent Details:\n");
printf("Roll\tName\tTotal\tAverage\n");
for(i = 0; i < n; i++) {
printf("%d\t%s\t%d\t%.2f\n", s[i].roll, s[i].name, s[i].total, s[i].average);
}
91
for(i = 1; i < n; i++) {
if(s[i].average > s[maxIndex].average) {
maxIndex = i;
}
}
printf("\nTopper: %s with Average = %.2f\n", s[maxIndex].name, s[maxIndex].average);
return 0;
}
Output
Enter number of students: 4
Student Details:
Roll Name Total Average
101 priya 268 89.33
102 hari 231 77.00
405 krish 234 78.00
444 kannan 287 95.67
92