0% found this document useful (0 votes)
14 views92 pages

TSP Lab Record

The document is a lab record for the Technical Skill Practices-I course at Panimalar Engineering College, detailing the vision and mission of the institution and department, program specific outcomes, knowledge and attitude profiles, and program outcomes. It includes exercises and example programs in C programming covering data types, operators, expressions, conditional statements, and more. The document serves as a practical guide for students to demonstrate their technical skills in programming.

Uploaded by

pmadhavsanjay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views92 pages

TSP Lab Record

The document is a lab record for the Technical Skill Practices-I course at Panimalar Engineering College, detailing the vision and mission of the institution and department, program specific outcomes, knowledge and attitude profiles, and program outcomes. It includes exercises and example programs in C programming covering data types, operators, expressions, conditional statements, and more. The document serves as a practical guide for students to demonstrate their technical skills in programming.

Uploaded by

pmadhavsanjay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 92

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 – 600123

DEPARTMENT OF
INFORMATION TECHNOLOGY

I YEAR–II SEMESTER

LAB RECORD

23ES1212 -TECHNICAL SKILL PRACTICES- I

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 …………

Batch:2024-2028, submitted for Anna University Practical Examination held on


Date: in 23ES1212-Technical Skill Practices-I during Feb 2025- May2 025.

STAFF-IN-CHARGE

INTERNAL EXAMINER EXTERNAL EXAMINER

2
VISION AND MISSION OF THE INSTITUTION

VISION

To transform the budding Engineers into academically excellent, highly


intellectual, and self-disciplined engineering graduates to mould them as
good citizens with the spirit of integrity and morality that would cater to
the needs of our Nation.

MISSION

• To impart quality education with high standards of excellence in


engineering and technology.

• To provide an excellent infrastructure in a serene and conducive


atmosphere that would motivate the students in their pursuit of knowledge
in the field of engineering and technology.

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.

PROGRAM SPECIFIC OUTCOMES (PSOs)

PSO 1 (Professional Skills): To inculcate technical skills to analyze, design and


implement software‘s related to algorithms, networking, web services, multimedia,
big data analytics and recent topics of varying complexity.

PSO 2 (Problem-Solving Skills): To develop the capability to comprehend and


solve the interdisciplinary problems through appropriate technology with the
understanding of contemporary business environment

PSO 3 (Successful Career and Entrepreneurship): To develop an ability to utilize


the latest technology and platforms to become a triumphant professional, successful
entrepreneur and an urge for pursuing higher studies.

4
KNOWLEDGE AND ATTITUDE PROFILE (WK)

WK1: A systematic, theory-based understanding of the natural sciences applicable


to the discipline and awareness of relevant social sciences.

WK2: Conceptually-based mathematics, numerical analysis, data analysis, statistics


and formal aspects of computer and information science to support
detailed analysis and modelling applicable to the discipline.

WK3: A systematic, theory-based formulation of engineering fundamentals


required in the engineering discipline.

WK4: Engineering specialist knowledge that provides theoretical frameworks and


bodies of knowledge for the accepted practice areas in the engineering discipline;
much is at the forefront of the discipline.

WK5: Knowledge, including efficient resource use, environmental impacts, whole-


life cost, re- use of resources, net zero carbon, and similar concepts, that supports
engineering design and operations in a practice area.

WK6: Knowledge of engineering practice (technology) in the practice areas in the


engineering discipline.

WK7: Knowledge of the role of engineering in society and identified issues in


engineering practice in the discipline, such as the professional responsibility
of an engineer to public safety and sustainable development.

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.

WK9: Ethics, inclusive behaviour and conduct. Knowledge of professional ethics,


responsibilities, and norms of engineering practice. Awareness of the need for
diversity by reason of ethnicity, gender, age, physical ability etc. with
mutual understanding and respect, and of inclusive attitudes.

5
PROGRAM OUTCOMES (POs)

PO1: Engineering Knowledge: Apply knowledge of mathematics, natural science, computing,


engineering fundamentals and an engineering specialization as specified in WK1 to WK4
respectively to develop to the solution of complex engineering problems.

PO2: Problem Analysis: Identify, formulate, review research literature and analyze complex
engineering problems reaching substantiated conclusions with consideration for sustainable
development. (WK1 to WK4)

PO3: Design/Development of Solutions: Design creative solutions for complex


engineering problems and design/develop systems/components/processes to meet identified needs
with consideration for the public health and safety, whole-life cost, net zero carbon, culture,
society and environment as required. (WK5)

PO4: Conduct Investigations of Complex Problems: Conduct investigations of complex


engineering problems using research-based knowledge including design of experiments,
modelling, analysis & interpretation of data to provide valid conclusions. (WK8).

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.

PO9: Communication: Communicate effectively and inclusively within the engineering


community and society at large, such as being able to comprehend and write effective reports and
design documentation, make effective presentations considering cultural, language, and learning
differences

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

EX.NO DATE NAME OF THE EXERCISE PAGE Marks Faculty


NO. Signature
1 Data Types, Variables, Operators 9

2 Expressions, Precedence , Operators 11


3 Conditional Statements , Switch 13
Statements
4 Looping, Nested Loops 20
5 Problems on Bit Manipulation 29
6 Patterns 31
7 Number Problems 35
8 Array Basics , Static vs Dynamic Array, 38
Two Dimensional Matrix
9 Structure , Union ,Storage Classes 47
10 Function , Parameters passing 54

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.

PROGRAM // demonstrate datatypes and variables


#include <stdio.h>
int main()
{
int a = 10; // integer
float b = 5.5; // float
char c = 'A'; // character
double d = 3.14159; // double

printf("Integer: %d\n", a);


printf("Float: %.2f\n", b);
printf("Character: %c\n", c);
printf("Double: %lf\n", d);

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

printf("Sum = %d\n", sum);


printf("Product = %d\n", product);
printf("Result = %d\n", result);
return 0;
}

OUTPUT
Sum = 15
Product = 50
Result = 32

PROGRAM #operator precedence


#include <stdio.h>
int main()
{
// Declare and initialize variables
int a = 4, b = 2, c = 8, d = 3;
int result;

// Expression 1: Without parentheses


result = a + b * c / d;
// According to precedence:
// b * c = 2 * 8 = 16
// 16 / d = 16 / 3 = 5 (integer division)
// a + 5 = 4 + 5 = 9
printf("Result 1 (a + b * c / d) = %d\n", result);

// Expression 2: With parentheses to change precedence


result = (a + b) * (c / d);
// a + b = 6
// c / d = 8 / 3 = 2 (integer division)
// 6 * 2 = 12

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

PROGRAM #different types of operators


#include <stdio.h>
int main() {
int x = 6, y = 3;

// 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

Thus the programs based on expressions, precedence , operators are demonstrated.

12
EX.NO.3 CONDITIONAL STATEMENTS , SWITCH STATEMENTS

DATE:

AIM

Demonstrate Conditional Statements and Switch Statements

EXERCISE- Write a C program to check whether a given character is a vowel or a


consonant.

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.

if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u' || ch=='A' || ch=='E' || ch=='I' || ch=='O' ||


ch=='U')
{
printf("The alphabet is a vowel.\n"); // Print message for vowel.
}
else if((ch>='a' && ch<='z') || (ch>='A' && ch<='Z'))
{
printf("The alphabet is a consonant.\n"); // Print message for consonant.
}
else
{
printf("The character is not an alphabet.\n");
}
}
OUTPUT
Test case- 1
Input any alphabet : 5
output-1
The character is not an alphabet.

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.

EXERCISE-Write a C program to determine whether a given number is a power of two or


not. If the number is a power of two, print 'Yes'; otherwise, print 'No', using a break
statement.

Note
• Read N in the first line
• Print output in the second

Constraint on inputs and output:


• N is non negative

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

EXERCISE-Write a C program to implement banking operations using a switch-case


statement. Assume a fixed interest rate of 4% of the balance.

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!");
}
}
}

Testcase-1 and output-1


Banking System
................
D ->Deposit
W ->Withdraw

16
B ->Balance
I ->Interest
Q ->Quit
Enter operation: D

Enter deposit amount: 10000

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

Enter withdraw amount: 3000

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

EXERCISE : Develop a program to implement a calculator in C.


PROGRAM
#include <stdio.h>
#include <stdlib.h>
// Driver code
int main()
{
char ch;
double a, b;
while (1)
{
printf("Enter an operator (+, -, *, /), "
"if want to exit press x: ");
scanf(" %c", &ch);

// to exit
if (ch == 'x')
exit(0);
printf("Enter two first and second operand: ");
scanf("%lf %lf", &a, &b);

// Using switch case we will differentiate


// operations based on different operator
switch (ch) {

// 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");
}
}

Testcase-1 and output-1


Enter an operator (+, -, *, / ) if want to exit press x: !
Enter two first and second operand: 12
23
Error! please write a valid operator

Enter an operator (+, -, *, / ) if want to exit press x:

Testcase-2 and output-2


Enter an operator (+, -, *, / ) if want to exit press x: +
Enter two first and second operand: 12
23
12.0 + 23.0 = 35.0

Enter an operator (+, -, *, / ) if want to exit press x: -


Enter two first and second operand: 45
67
45.0 - 67.0 = -22.0

Enter an operator (+, -, *, / ) if want to exit press x: *


Enter two first and second operand: 12
23
12.0 * 23.0 = 276.0

Enter an operator (+, -, *, / ) if want to exit press x: /


Enter two first and second operand: 12
12
12.0 / 12.0 = 1.0

Enter an operator (+, -, *, / ) if want to exit press x: x

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

EXERCISE : Write a C program to find the sum of the series 1+11+111+1111+... up to n


terms using a for loop, where 1 <= n <= 10.

Input and Output:


● Read value of number of terms n the first line.
● print the series .
● Print the sum of the series in the second line.
PROGRAM

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

Example of other perfect numbers are:


Perfect Number Sum of Divisors
6 1+2+3
28 1 + 2 + 4 + 7 + 14
496 1 + 2 + 4 + 8 + 16 + 31 + 62 + 124 + 248
8128 1 + 2 + 4 + 8 + 16 + 32 + 64 + 127 + 254 + 508 + 1016 + 2032 + 4064
PROGRAM
#include <stdio.h>
int main()
{
int num,x;
int sum=0;
printf("\nenter the number : ");
scanf("%d",&num);
for(x=1; x<num;x++)
{
if(num%x==0)
sum+=x;
}
if(sum==num)
printf("\n%d is a perfect number",num);
else
printf("\n%d is not a perfect number.\n",num);
return 0;
}

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

// Calculate the sum of the series


for(i=1;i<=num;i++)
sum = sum + i;

// Display the last term of the series


printf(" 1/%d",num);

// Calculate and display the sum


printf("\nSum = 1/%d", sum +1/num);
return0;
}

Testcase-1 and output-1


Input any number: 7
1 + 1/2 + 1/3 + 1/4 + 1/5 + 1/6 + 1/7
Sum = 1/28
Testcase-2 and output-2
Input the number of terms: 5
1 + 1/2 + 1/3 + 1/4 + 1/5
Sum = 1/15
Testcase-3 and output-3
Input the number of terms: 8
1 + 1/2 + 1/3 + 1/4 + 1/5 + 1/6 + 1/7 + 1/8
Sum = 1/36

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;
}

Testcase-1 and output-1


Enter start and end value
2
50
Prime Numbers from 2 to 50 are:
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47

Testcase-2 and output-2


Enter start and end value
34
78
SPrime Numbers from 34 to 78 are:
37, 41, 43, 47, 53, 59, 61, 67, 71, 73

Testcase-3 and output-3


Enter start and end value
1
1000

Prime Numbers from 1 to 100 are:


1, 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

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;
}

Testcase-1 and output-1


enter the marks of 10 students :
marks[0]= 98
marks[1]= 80
marks[2]= 99
marks[3]= 78
marks[4]= 92
marks[5]= 93
marks[6]= 45
marks[7]= 88
marks[8]= 80
marks[9]= 76

*************
FREQUENCY HISTOGRAM
GROUP 0 |
GROUP 1 |
GROUP 2 |
GROUP 3 |
GROUP 4 | *
GROUP 5 |
GROUP 6 |
GROUP 7 | * *
GROUP 8 | * * *
GROUP 9 | * * * *

Testcase-2 and output-2

enter the marks of 10 students :


marks[0]= 76
marks[1]= 6
marks[2]= 78
marks[3]= 79
marks[4]= 75

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 |

Testcase-3 and output-3


enter the marks of 10 students :
marks[0]= 11
marks[1]= 23
marks[2]= 34
marks[3]= 45
marks[4]= 56
marks[5]= 67
marks[6]= 78
marks[7]= 89
marks[8]= 90
marks[9]= 100

*************

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;

// Outer loop for rows


for(i = 1; i <= 5; i++) {
// Inner loop for columns
for(j = 1; j <= i; j++) {
printf("* ");
}
printf("\n"); // New line after each row
}
return 0;
}

OUTPUT
*
**
***
****
*****

RESULT
Thus programs based on loops and nested loops are demonstrated.

28
EX.NO.5 PROBLEMS ON BIT MANIPULATION

DATE:

AIM

To demonstrate bit manipulation

EXERCISE - Check if a number is even or odd using bitwise operator

// 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

EXERCISE: Swap two numbers without using a third variable

PROGRAM // XOR swapping technique using bit manipulation.

#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

EXERCISE - Check if a number is a power of 2


//Only powers of 2 have exactly one bit set.
PROGRAM
#include <stdio.h>
int main() {
int num = 16;
if (num != 0 && (num & (num - 1)) == 0)
printf("%d is a power of 2\n", num);
else
printf("%d is NOT a power of 2\n", num);
return 0;
}
OUTPUT
16 is a power of 2

EXERCISE. Get the ith bit of a number


PROGRAM
#include <stdio.h>
int main()
{
int num = 13; // Binary: 1101
int i = 2;
int bit = (num >> i) & 1;
printf("The %dth bit is: %d\n", i, bit);
return 0;
}
OUTPUT
The 2th bit is: 1

RESULT
Thus the programs based on bit manipulation are demonstrated.

30
EX.NO.6 PATTERNS

DATE:

AIM:
Demonstrate patterns in C

EXERCISE- Write a C Program to print numbers in a Pyramid using a for Loop.

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

EXERCISE- Produce right angle triangle pattern


*
**
***
****
*****

PROGRAM
#include <stdio.h>
int main() {
int i, j, n;
printf("Enter number of rows: ");
scanf("%d", &n);

for(i = 1; i <= n; i++) {


for(j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}

EXERCISE : Produce the following pattern


1
12
123
1234
12345

33
PROGRAM
#include <stdio.h>
int main() {
int i, j, n;
printf("Enter number of rows: ");
scanf("%d", &n);

for(i = 1; i <= n; i++) {


for(j = 1; j <= i; j++) {
printf("%d ", j);
}
printf("\n");
}
return 0;
}

EXERCISE: Produce Inverted Triangle Pattern


*****
****
***
**
*

PROGRAM
#include <stdio.h>
int main() {
int i, j, n;
printf("Enter number of rows: ");
scanf("%d", &n);

for(i = n; i >= 1; i--) {


for(j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}

RESULT:
Thus the programs based on patterns are demonstrated

34
EX.NO.7 Number problems

DATE:

AIM

Demonstrate number problems

EXERCISE : Check number is prime


PROGRAM

#include <stdio.h>

int main() {
int num, i, isPrime = 1;
printf("Enter a number: ");
scanf("%d", &num);

if (num <= 1) isPrime = 0;

for(i = 2; i <= num / 2; i++) {


if(num % i == 0) {
isPrime = 0;
break;
}
}

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

EXERCISE : Check if a Number is Palindrome


PROGRAM
#include <stdio.h>

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.

EXERCISE: Check if a Number is an Armstrong Number


PROGRAM
#include <stdio.h>
#include <math.h>

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

EXERCISE : Write a C program to perform matrix multiplication.


PROGRAM
#include<stdio.h>
#include<stdlib.h>
int main()
{
int a[10][10],b[10][10],mul[10][10],row1, col1, row2, col2,i,j,k;
printf("enter the number of rows in first matrix=");
scanf("%d",&row1);
printf("enter the number of columns in second matrix=");
scanf("%d",&col1);
printf("enter the first matrix element=\n");
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("enter the number of rows in second matrix=");
scanf("%d",&row2);

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

Testcase-2 and output-2


enter the number of rows in first matrix=2
enter the number of columns in second matrix=2
enter the first matrix element=
12
12
12
12
enter the number of rows in second matrix=2
enter the number of columns in second matrix=2
enter the second matrix element=
12
12
12
12
multiply of the matrix=
288 288
288 288

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;

// Input size of first array


printf("Enter number of elements in first array: ");
scanf("%d", &n1);

printf("Enter elements of first array:\n");


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

// Input size of second array


printf("Enter number of elements in second array: ");
scanf("%d", &n2);

printf("Enter elements of second array:\n");


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

43
// Merge arrays
for (i = 0; i < n1; i++) {
merged[i] = a[i];
}
for (j = 0; j < n2; j++) {
merged[i + j] = b[j];
}

// Display merged array


printf("Merged array:\n");
for (i = 0; i < n1 + n2; i++) {
printf("%d ", merged[i]);
}
return 0;
}

Testcase-1 and output-1


Enter the size of first array: 5
Enter the array elements: 66
44
88
98
12
Enter the size of second array: 4
Enter the array elements: 87
65
43
21
The merged array: 66 44 88 98 12 87 65 43 21
Final array after sorting: 12 21 43 44 65 66 87 88 98

EXERCISE - Write a C program to remove duplicates from a sorted array.


PROGRAM
#include <stdio.h>
int remove_duplicate(int arr[], int n)
{

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;
}

Testcase-1 and output-1


enter the size of the elements
6
enter the elements
11
11
11
11
11
111
Array Before Removing Duplicates: 11 11 11 11 11 111
Array After Removing Duplicates: 11 111
Testcase-2 and output-2
enter the size of the elements
5
enter the elements
67
67
56
45
3
Array Before Removing Duplicates: 67 67 56 45 3
Array After Removing Duplicates: 67 56 45 3

45
EXERCISE : Demonstrate dynamic arrays
PROGRAM
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr;
int n, i;

// Ask user for size


printf("Enter the number of elements: ");
scanf("%d", &n);

// Dynamically allocate memory


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

// Check if memory is allocated successfully


if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
// Input elements
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[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;

printf("Enter first distance:\n");


printf("Feet: ");
scanf("%d", &d1.f.feet);
printf("Inches: ");
scanf("%d", &d1.i.inches);

printf("Enter second distance:\n");


printf("Feet: ");
scanf("%d", &d2.f.feet);
printf("Inches: ");
scanf("%d", &d2.i.inches);

// Add feet and inches


sum.f.feet = d1.f.feet + d2.f.feet;
sum.i.inches = d1.i.inches + d2.i.inches;
// Convert inches to feet if >= 12
if (sum.i.inches >= 12) {
sum.f.feet += sum.i.inches / 12;
sum.i.inches = sum.i.inches % 12;
}
printf("\nTotal Distance = %d feet %d inches\n", sum.f.feet, sum.i.inches);
return 0;}

OUTPUT
Enter first distance:
Feet: 12
Inches: 10
Enter second distance:
Feet: 12
Inches: 10

Total Distance = 25 feet 8 inches

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;
}

// Function to swap two students


void swap(struct Student *a, struct Student *b)
{
struct Student temp;
temp= *a;
*a = *b;
*b = temp;
}
void sortStudents(struct Student students[], int n)
{
for (int i = 0; i< n - 1; ++i) {
for (int j = 0; j < n - i - 1; ++j) {
if (students[j].totalMarks> students[j + 1].totalMarks)
{
swap(&students[j], &students[j + 1]);

}}}
}

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;
}

Testcase-1 and output-1


Enter details for student 1:
Name: SELVAN
Registration Number: 101
Enter marks for 5 subjects:
Subject 1: 90
Subject 2: 98
Subject 3: 98
Subject 4: 87
Subject 5: 86
Enter details for student 2:
Name: KRISH
Registration Number: 302
Enter marks for 5 subjects:
Subject 1: 98
Subject 2: 88
Subject 3: 87
Subject 4: 86
Subject 5: 85
Enter details for student 3:
Name: VINAYKUMAR
Registration Number: 102
Enter marks for 5 subjects:
Subject 1: 76
Subject 2: 68
Subject 3: 66

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

Sorted list of students in ascending order of total marks:


Name: KUMAR, Registration Number: 333, Total Marks: 243,Percentage: 48.60%
Name: RANJITH, Registration Number: 222, Total Marks: 272,Percentage: 54.40%
Name: VINAYKUMAR, Registration Number: 102, Total Marks: 375,Percentage: 75.00%
Name: KRISH, Registration Number: 302, Total Marks: 444,Percentage: 88.80%
Name: SELVAN, Registration Number: 101, Total Marks: 459,Percentage: 91.80%

EXERCISE : Demonstrate storage classes in C


PROGRAM
#include <stdio.h>
// extern variable declaration
int externVar = 50; // This acts as a global variable

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

// register variable (suggests to keep in CPU register)


register int regVar = 20;
printf("Register variable value: %d\n", regVar);

52
// calling function to see static variable behavior
demoStatic(); // Output: 1
demoStatic(); // Output: 2
demoStatic(); // Output: 3

// accessing extern variable


printf("Extern variable value: %d\n", externVar);

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

EXERCISE-Write a C program to find the square of a number using a function.


PROGRAM
#include <stdio.h>
// Function to calculate square
int square(int num) {
return num * num;
}
int main() {
int number, result;
printf("Enter a number: ");
scanf("%d", &number);
result = square(number); // Function call
printf("Square of %d is %d\n", number, result);
return 0;
}

OUTPUT
Enter a number: 3
Square of 3 is 9

EXERCISE - Program to Sort N Numbers Using a Function


PROGRAM
#include <stdio.h>
// Function to sort array in ascending order
void sortArray(int arr[], int n) {
int i, j, temp;

for (i = 0; i < n - 1; i++) {


for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int arr[50], n, i;

54
printf("Enter number of elements: ");
scanf("%d", &n);

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


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

sortArray(arr, n); // Function call

printf("Sorted array:\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}

return 0;
}

OUTPUT

Enter number of elements: 5


Enter 5 numbers:
88
77
55
33
90
Sorted array:
33 55 77 88 90

EXERCISE – Program to demonstrate pass by value and pass by reference


PROGRAM
#include <stdio.h>

// 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);

printf("Before passByReference: y = %d\n", y);


passByReference(&y);
printf("After passByReference: y = %d\n", y);

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:

AIM: Demonstrate recursion in C

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;

printf("Enter Number1: ");


scanf("%d", &num1);

printf("Enter Number2: ");


scanf("%d", &num2);

printf("The Highest Common Factor is: %d\n", HCF(num1, num2));


}

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;

printf("Enter size of the array: ");


scanf("%d",&N);
printf("Enter elements in the array: ");

for(i=0; i<N; i++)


{
scanf("%d",&arr[i]);
}
soa = sum(arr,0,N);
printf("Sum of array elements: %d", soa);
}

int sum(int arr[],int start,int len)


{
if(start >= len) return 0;
return (arr[start]+sum(arr,start+1,len));
}

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;
}

Testcase-1 and output-1


enter the string

64
india is my country
String: india is my country
Vowels: 6
Consonants: 10

Testcase-2 and output-2


enter the string
String: PANIMALAR ENGINEERING COLLEGE, CHENNAI
Vowels: 15
Consonants: 20

EXERCISE - Write a C program to replace all occurrences of a character in a string.


PROGRAM
#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size
/* Function declaration */
void replaceAll(char * str, char oldChar, char newChar);
int main()
{
char str[MAX_SIZE], oldChar, newChar;
printf("Enter any string: ");
gets(str);
printf("Enter character to replace: ");
oldChar = getchar();
// Dummy getchar() to eliminate extra ENTER character
getchar();
printf("Enter character to replace '%c' with: ", oldChar);
newChar = getchar();
printf("\nString before replacing: \n%s", str);
replaceAll(str, oldChar, newChar);
printf("\n\nString after replacing '%c' with '%c' : \n%s", oldChar, newChar, str);
return 0;
}
void replaceAll(char * str, char oldChar, char newChar)
{
int i = 0;
/* Run till end of string */
while(str[i] != '\0')
{
/* If occurrence of character is found */
if(str[i] == oldChar)
{
str[i] = newChar;
}
i++;
} }

65
Testcase-1 and output-1
Enter any string: i love india
Enter character to replace: i
Enter character to replace 'i' with: p

String before replacing:


i love india

String after replacing 'i' with 'p' :


p love pndpa

Testcase-2 and output-2


Enter any string: WHERE ARE YOU, I AM FINE HERE
Enter character to replace: E
Enter character to replace 'E' with: )

String before replacing:


WHERE ARE YOU, I AM FINE HERE

String after replacing 'E' with ')' :


WH)R) AR) YOU, I AM FIN) H)R)

RESULT:
Thus the programs based on strings are demonstrated.

66
EX.NO.13 POINTERS

DATE:

AIM
To demonstrate pointers in C

EXERCISE-Write a C program to add two numbers using pointers.


PROGRAM
#include <stdio.h>
int main()
{
int fno, sno, *ptr, *qtr, sum;
printf(" Input the first number : ");
scanf("%d", &fno);
printf(" Input the second number : ");
scanf("%d", &sno);
ptr = &fno;
qtr = &sno;
sum = *ptr + *qtr;
printf(" The sum of the entered numbers is : %d\n\n", sum);
}

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

EXERCISE -Write a program in C to sort an array of integers using pointers.


PROGRAM
#include <stdio.h>
int main(void)
{
int a[10];
int *p,i=0,j=0, n;
printf("\n enter the number of elements\n");
scanf("%d",&n);
printf("enter the elements one by one \n");

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;
}

Testcase-1 and output-1


enter the number of elements
4
enter the elements one by one
76
54
88
99
Sorted Values : 54 76 88 99

EXERCISE - find largest number using dynamic memory allocation.


PROGRAM
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;
double *data;
printf("Enter the total number of elements: ");
scanf("%d", &n);
// Allocating memory for n elements
data = (double *)calloc(n, sizeof(double));
if (data == NULL) {

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);
}

// Finding the largest number


for (int i = 1; i < n; ++i) {
if (*data < *(data + i)) {
*data = *(data + i);
}
}
printf("Largest number = %.2lf", *data);

free(data);

return 0;
}

Testcase-1 and output-1


Enter the total number of elements: 5
Enter number1: 3.4
Enter number2: 2.4
Enter number3: -5
Enter number4: 24.2
Enter number5: 6.7
Largest number = 24.20

Testcase-2 and output-2


Enter the total number of elements: 3
Enter number1: 45
Enter number2: 67
Enter number3: 29.5
Largest number = 67.00

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;

printf("Radius = %d\n", radius);


printf("Area of Circle = %.2f\n", AREA(radius));

#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

// Reading from the file


fp = fopen("example.txt", "r"); // Open file in read mode
if (fp == NULL) {
printf("File not found!\n");
return 1;
}

printf("File content:\n");
while (fgets(str, sizeof(str), fp) != NULL) {
printf("%s", str); // Print each line
}

fclose(fp); // Close the file after reading

73
return 0;
}

OUTPUT
example.txt file created and contents are
Welcome to File Handling in C!
This is another line.

EXERCISE : To count the number of words in a file


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

int main() {
FILE *fp;
char ch;
int wordCount = 0;
int inWord = 0;

// Open the file in read mode


fp = fopen("sample.txt", "r");
if (fp == NULL) {
printf("File could not be opened.\n");
return 1;
}

while ((ch = fgetc(fp)) != EOF) {


if (isspace(ch)) {
inWord = 0; // We're outside a word
} else if (inWord == 0) {
inWord = 1; // Entering a word
wordCount++;
}
}

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;

- // Open one file for reading


fptr1 = fopen("file1.txt", "r");
if (fptr1 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
// Open another file for writing
fptr2 = fopen("file2.txt", "w");
if (fptr2 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
// Read contents from file
c = fgetc(fptr1);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(fptr1);
}
printf("\nContents copied to %s", filename);
}

OUTPUT
File2.txt
Welcome to File Handling in C!
This is another line.

EXERCISE- Demonstrate division by zero


PROGRAM
#include <stdio.h>
#include <setjmp.h>

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!

EXERCISE: Exception for Invalid Array Access


PROGRAM
#include <stdio.h>
#include <setjmp.h>

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)

1. WRITE A FOR LOOP TO PRINT FROM 10 TO 1.

#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

2. C PROGRAM TO PRINT FIRST 8 CHARACTERS IN THE WORD PANIMALAR .

#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

3. WRITE A C PROGRAM TO FIND AREA AND PERIMETER OF A CIRCLE

#include <stdio.h>
#define PI 3.14f /* Define the value of pie */
void main()
{
/* Variable Declaration. */
float radius, perimeter, area;

/* Taking input of the radious of the circle from the user */


printf("Enter radius of the Circle:\n");

77
scanf("%f", & radius);

/* Calculating perimeter of the circle */


perimeter = 2 * PI * radius;
printf("Perimeter of the circle: %0.4f\n", perimeter);

/* Calculating area of the circle */


area = PI * radius * radius;
printf("Area of circle: %0.4f\n", area);
}

OUTPUT
Enter radius of the Circle:
6
Perimeter of the circle: 37.6800
Area of circle: 113.0400

C PROGRAM TO FIND FACTORIAL OF A NUMBER


4.
#include <stdio.h>
void main()
{
int num, i,fact = 1;
printf("Enter a number: ");
scanf("%d", &num);

// 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

5. C PROGRAM TO CHECK WHETHER A NUMBER IS PRIME OR NOT.

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

celsius = (fahrenheit - 32) * 5 / 9;


fahrenheit = (celsius * 9 / 5) + 32;

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

7 C PROGRAM TO COPY ALL ELEMENTS OF AN ARRAY INTO ANOTHER ARRAY.

#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];
}

printf("Elements of the destination array:\n");


for (i = 0; i< n; i++)
{
printf("%d ", d[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

8. PROGRAM TO SORT GIVEN N NUMBERS USING FUNCTIONS.

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

// Input the elements of the array


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

// Perform Selection Sort


selectionSort(arr, n);
printf("Sorted array: ");
for (i = 0; i< n; i++)
{

81
printf("%d ", arr[i]);
}
printf("\n");
}
OUTPUT

Enter the number of elements: 5


Enter the elements: 99
8
88
5
3
Sorted array: 3 5 8 88 99

9. WRITE A C PROGRAM USING POINTERS TO COMPUTE THE SUM AND MEAN OF


ALL ELEMENTS STORED IN AN ARRAY OF “N‟ REAL NUMBERS.
#include <stdio.h>
#include <math.h>
void main()
{
int n,i;
float arr[20], sum = 0.0, mean, sd = 0.0, *ptr;
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("Enter the elements: \n");
for ( i = 0; i< n; i++)
{
scanf("%f", &arr[i]);
}
// Pointer to traverse the array
ptr = arr;
// Calculate the sum
for (i = 0; i< n; i++)
{
sum += *(ptr + i);
}
mean = sum / n;
printf("Sum: %.2f\n", sum);
printf("Mean: %.2f\n", mean);
}

OUTPUT
Enter the number of elements: 7
Enter the elements:
6
7
4
99
80
87

82
56
Sum: 339.00
Mean: 48.43

10. C PROGRAM USING STRUCTURES TO PREPARE STUDENTS MARK STATEMENT.

#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

--- Mark Statement ---


Roll Number: 878
Name: HARISH
Marks:
Subject 1: 90
Subject 2: 77
Subject 3: 89
Total Marks: 256
Average Marks: 85.33

11 Write an example program for union in C


#include <stdio.h>
// Define a union to hold different types of student data
union Student {
int rollNo;
float marks;
char grade;
};
int main() {
union Student student;
// Input roll number
printf("Enter Roll Number: ");
scanf("%d", &student.rollNo);
printf("Roll Number: %d\n", student.rollNo);

// 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

13. C PROGRAM TO DISPLAY THE CONTENTS OF THE FILE IN REVERSE ORDER

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

Step 2: open a new file in turboc editor, create a C file

#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

egelloc gnireenigne ralaminaP ot emocleW

14 C PROGRAM USING STRUCTURES TO PREPARE THE EMPLOYEE PAY ROLL OF A


COMPANY.

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

printf("Enter Employee Name: ");


scanf("%s", emp.name);

printf("Enter Basic Salary: ");


scanf("%f", &emp.basicSalary);

// 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

Enter Employee ID: 101


Enter Employee Name: harish
Enter Basic Salary: 100000

--- Employee Payroll ---


ID: 101
Name: harish
Basic Salary: 100000.00
HRA: 20000.00
DA: 10000.00
Gross Salary: 130000.00

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

16. Simulate ATM Machine operations


include <stdio.h>

int main() {
int choice;
float balance = 10000.0, deposit, withdraw;
int pin, enteredPin;

pin = 1234; // predefined PIN

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

===== ATM Menu =====


1. Check Balance
2. Deposit Money
3. Withdraw Money
4. Exit
Enter your choice (1-4): 2
Enter amount to deposit: Rs. 10000
Deposit successful! New balance: Rs. 20000.00

===== ATM Menu =====


1. Check Balance
2. Deposit Money
3. Withdraw Money
4. Exit
Enter your choice (1-4): 1
Your current balance is: Rs. 20000.00

===== ATM Menu =====


1. Check Balance
2. Deposit Money
3. Withdraw Money
4. Exit
Enter your choice (1-4): 3
Enter amount to withdraw: Rs. 2000
Withdrawal successful! New balance: Rs. 18000.00

===== ATM Menu =====


1. Check Balance
2. Deposit Money
3. Withdraw Money
4. Exit
Enter your choice (1-4): 1
Your current balance is: Rs. 18000.00

===== ATM Menu =====


1. Check Balance
2. Deposit Money

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;

printf("Enter number of students: ");


scanf("%d", &n);

for(i = 0; i < n; i++) {


printf("\nEnter details for student %d\n", i+1);
printf("Roll Number: ");
scanf("%d", &s[i].roll);
printf("Name: ");
scanf("%s", s[i].name);

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);
}

// Finding highest average


int maxIndex = 0;

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

Enter details for student 1


Roll Number: 101
Name: priya
Enter marks for subject 1: 89
Enter marks for subject 2: 90
Enter marks for subject 3: 89

Enter details for student 2


Roll Number: 102
Name: hari
Enter marks for subject 1: 66
Enter marks for subject 2: 77
Enter marks for subject 3: 88

Enter details for student 3


Roll Number: 405
Name: krish
Enter marks for subject 1: 67
Enter marks for subject 2: 78
Enter marks for subject 3: 89

Enter details for student 4


Roll Number: 444
Name: kannan
Enter marks for subject 1: 90
Enter marks for subject 2: 98
Enter marks for subject 3: 99

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

Topper: kannan with Average = 95.67

92

You might also like