0% found this document useful (0 votes)
96 views

PPC18 Lab Manual

Uploaded by

raj8789881500
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)
96 views

PPC18 Lab Manual

Uploaded by

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

Department of Information Science and Engineering

Laboratory Schedule:

Session No Topics: Programming Assignments No. of


hours
1. Creating and Running Simple C Programs: 2hr
• C-Program to calculate the sum of three numbers / C-Program to demonstrate
a Simple Calculator.
• C-Program to calculate the area and circumference of a circle using PI as a
defined constant.
• C-Program to convert temperature given in Celsius to Fahrenheit and
Fahrenheit to Celsius
• C-Program to compute the roots of a quadratic equation by accepting the
coefficients.
2. Creating and Running C Programs on Expressions : 2hr
• C-Program to calculate quotient and reminder of two numbers.)
• C-Program to evaluate two complex expressions.
• C-Program to demonstrate automatic and type casting of numeric types
• C-Program to calculate the total sales given the unit price, quantity, discount
and tax rate
• C-Program to calculate a student’s average score for a course with 4 quizzes, 2
midterms and a final. The quizzes are weighted 30%, the midterms 40% and the
final 30%.

3. Creating and Running C Programs on Making Decision: 2hr


• C-Program to determine the use of the character classification functions found
in c-type library.
• C-Program to read a test score, calculate the grade for the score and print the
grade.
• C-Program to uses a menu to allow the user to add, multiply, subtract and
divide two numbers using switch case.
• C-Program to read the name of the user, number of units consumed and print
out the charges. An electricity board charges the following rates for the use of
electricity:
 For the first 200 units 80 paise per unit
 For the next 100 units 90 paise per unit
 Beyond 300 units Rs 1 per unit.

All users are charged a minimum of Rs. 100 as meter charge. If the total amount
is more than Rs 400, then an additional surcharge of 15% of total amount is
charged
4. Creating and Running C Programs on Repetition or Loops: 2hr
• C-Program to print a number series from 1 to a user-specified limit in the form
of a angle
• C-Program to print the number and sum of digits in an integer.
• C-Program to calculate the factorial of a number using for loop/ Recursion
• C-Program to calculate nth Fibonacci number.
• C-Program to convert binary to a decimal number
5. Creating and Running C Programs on One Dimensional Arrays: 2hr
• C-Program to print square of index and print it.
• C-Program to calculate average of the number in an array.
• C-Program to sort the list using bubble sort.
• C-Program to search an ordered list using binary search.
6. Creating and Running C Programs on Two Dimensional Arrays: 2hr
• C-Program to perform addition of two matrices.
• C-Program to perform multiplication of two matrices.
• C-Program to find transpose of the given matrices.
• C-Program to find row sum and column sum and sum of all elements in a
matrix.
• C-Program initialize/fill all the diagonal elements of a matrix with zero and
print
7. Creating and Running C Programs on User Defined Functions: 2hr
• C-program to read a number, Find its factorial using function with argument
and with return type.
• C-Program to read two number, Find its GCD and LCM using function with
arguments and without return type.
• C-Program to read a number, Find whether it is a palindrome or not using
function without argument and with return type.
• C-Program to read a number, Find whether it is prime number or not using
function without arguments and without return type.
8. Creating and Running C Programs on Strings: 2hr
• C-program read two strings, Combine them without using string built-in
functions.
• C-program read two strings, Compare them without using string built-in
functions.
• C-program read two strings, concatenate them without using string built-in
functions.
• C Program to Check if the Substring is Present in the Given String.
• C-program to demonstrate built-in sting functions like strlen(), strcpy(),
strcmp(), strcat()
Revision as per format MSRIT. F702 Rev. No. 2

. 9 Creating and Running C Programs on Storage Classes and Pointers: 2hr


• C-program to show the use of auto and static variable.
• C-program to add two numbers using pointers. / C-program to swap two
numbers using pointers.
• C-program to show how the same pointer can point to different data variable.
/ C-program to show the use of different pointers point to the same variable
• C-Program to read an array of elements, Compute its sum using pointers.

10 Creating and Running C Programs on Derived Types and Unions:


• C-Program to print selected TV stations for our cable TV systems.
• C-Program to demonstrate union of short int and two char

11 Creating and Running C Programs on Structures:


• C Program to read employee details (name, salary, address) and print the
same
using structure.
• C-Program to read marks of three students in 3 subjects. Calculate the total
marks
scored, student wise and subject wise using structure.

12 Creating and Running C Programs on Files:


• C-Program to demonstrate function fread()/fscanf()
• C-Program to demonstrate function fwrite()/fprintf()

Continuous Internal Evaluation (CIE): 50 Marks


Assessment tool Marks Course outcomes attained
Internal Test-I 30 CO1, CO2, CO3
Internal Test-II 30 CO3, CO4, CO5
Average of the two internal test shall be taken for 30 marks
Other components
Lab Component Evaluation 20 CO1, CO2, CO3, CO4, CO5
Semester-End Examination(SEE) 100 CO1, CO2, CO3, CO4, CO5
Revision as per format MSRIT. F702 Rev. No. 2

Programs
1.Creating and Running Simple C Programs:
• C-Program to calculate the sum of three numbers / C-Program to demonstrate a Simple
Calculator.
• C-Program to calculate the area and circumference of a circle using PI as a defined constant.
• C-Program to convert temperature given in Celsius to Fahrenheit and Fahrenheit to Celsius
• C-Program to compute the roots of a quadratic equation by accepting the coefficients.

Sum of three numbers


#include <stdio.h>
int main(){
int a, b, c, sum;
float avg;

// Asking for input


printf("Enter 3 numbers: \n");
scanf("%d %d %d", &a, &b, &c);

// Calculating sum
sum = a + b + c;

// Displaying output
printf("Sum = %d \n", sum);
return 0;
}

Output:

Enter 3 numbers:
567
Sum = 18
Average = 6.00
Revision as per format MSRIT. F702 Rev. No. 2

C program to demonstrate a simple Calculator


#include<stdio.h>

int main() {
char operator;
double num1, num2, result;

printf("Enter an operator (+, -, *, /): ");


scanf("%c", &operator);

printf("Enter two operands: ");


scanf("%lf %lf", &num1, &num2);

switch (operator) {
case '+':
result = num1 + num2;
printf("Result: %.2lf\n", result);
break;
case '-':
result = num1 - num2;
printf("Result: %.2lf\n", result);
break;
case '*':
result = num1 * num2;
printf("Result: %.2lf\n", result);
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
printf("Result: %.2lf\n", result);
} else {
printf("Error! Division by zero.\n");
}
break;
default:
printf("Error! Invalid operator.\n");
}

return 0;
}
Revision as per format MSRIT. F702 Rev. No. 2

Output:
Enter an operator (+, -, *, /): +
Enter two operands: 5 6
Result: 11.00

C-Program to calculate the area and circumference of a circle using PI as a defined


constant

#include <stdio.h>

#define PI 3.14159

int main() {
double radius, area, circumference;

printf("Enter the radius of the circle: ");


scanf("%lf", &radius);

// Calculate the area of the circle


area = PI * radius * radius;

// Calculate the circumference of the circle


circumference = 2 * PI * radius;

printf("Area of the circle: %.2lf\n", area);


printf("Circumference of the circle: %.2lf\n", circumference);

return 0;
}

Output:
Enter the radius of the circle: 6
Area of the circle: 113.10
Circumference of the circle: 37.70
Revision as per format MSRIT. F702 Rev. No. 2

C-Program to convert temperature given in Celsius to Fahrenheit and Fahrenheit to


Celsius

#include <stdio.h>

double celsiusToFahrenheit(double celsius) {


return (celsius * 9.0/5.0) + 32.0;
}

double fahrenheitToCelsius(double fahrenheit) {


return (fahrenheit - 32.0) * 5.0/9.0;
}

int main() {
char choice;
double temperature;

printf("Enter temperature: ");


scanf("%lf", &temperature);

printf("Choose conversion:\n");
printf("a. Celsius to Fahrenheit\n");
printf("b. Fahrenheit to Celsius\n");
printf("Enter your choice (a/b): ");
scanf(" %c", &choice);

switch (choice) {
case 'a':
case 'A':
printf("%.2lf Celsius is equal to %.2lf Fahrenheit.\n", temperature,
celsiusToFahrenheit(temperature));
break;
case 'b':
case 'B':
printf("%.2lf Fahrenheit is equal to %.2lf Celsius.\n", temperature,
fahrenheitToCelsius(temperature));
break;
default:
printf("Invalid choice.\n");
}

return 0;
}
Revision as per format MSRIT. F702 Rev. No. 2

Output:
Enter temperature: 34
Choose conversion:
a. Celsius to Fahrenheit
b. Fahrenheit to Celsius
Enter your choice (a/b): a
34.00 Celsius is equal to 93.20 Fahrenheit.

2. Creating and Running C Programs on Expressions :


• C-Program to calculate quotient and reminder of two numbers.)
• C-Program to evaluate two complex expressions.
• C-Program to demonstrate automatic and type casting of numeric types
• C-Program to calculate the total sales given the unit price, quantity, discount and tax rate
• C-Program to calculate a student’s average score for a course with 4 quizzes, 2 midterms and a
final. The quizzes are weighted 30%, the midterms 40% and the final 30%.

C-Program to calculate quotient and reminder of two numbers.)

#include <stdio.h>

int main() {
int dividend, divisor, quotient, remainder;

printf("Enter dividend: ");


scanf("%d", &dividend);

printf("Enter divisor: ");


scanf("%d", &divisor);

// Calculate quotient
quotient = dividend / divisor;

// Calculate remainder
remainder = dividend % divisor;

printf("Quotient: %d\n", quotient);


printf("Remainder: %d\n", remainder);

return 0;
}
Revision as per format MSRIT. F702 Rev. No. 2

Output:
Enter dividend: 7
Enter divisor: 3
Quotient: 2
Remainder: 1

C-Program to evaluate two complex expressions.


#include <stdio.h>

typedef struct {
double real;
double imag;
} Complex;

Complex add(Complex num1, Complex num2) {


Complex result;
result.real = num1.real + num2.real;
result.imag = num1.imag + num2.imag;
return result;
}

Complex multiply(Complex num1, Complex num2) {


Complex result;
result.real = (num1.real * num2.real) - (num1.imag * num2.imag);
result.imag = (num1.real * num2.imag) + (num1.imag * num2.real);
return result;
}

int main() {
Complex num1, num2, sum, product;

// Input for the first complex number


printf("Enter real and imaginary parts of first complex number: ");
scanf("%lf %lf", &num1.real, &num1.imag);

// Input for the second complex number


printf("Enter real and imaginary parts of second complex number: ");
scanf("%lf %lf", &num2.real, &num2.imag);

// Calculate sum of complex numbers


sum = add(num1, num2);

// Calculate product of complex numbers


product = multiply(num1, num2);
Revision as per format MSRIT. F702 Rev. No. 2

// Display the sum and product


printf("Sum: %.2lf + %.2lf i\n", sum.real, sum.imag);
printf("Product: %.2lf + %.2lf i\n", product.real, product.imag);

return 0;
}

Output:
Enter real and imaginary parts of first complex number: 2
+ 3j
Enter real and imaginary parts of second complex number: Sum: 5.00 + 0.00 i
Product: 6.00 + 0.00 i

C-Program to demonstrate automatic and type casting of numeric types


#include <stdio.h>

int main() {
// Automatic type conversion (promotion)
int a = 10;
double b = 3.5;

double result_auto = a + b; // int is automatically promoted to double

printf("Automatic Type Conversion:\n");


printf("a + b = %.2lf\n", result_auto);

// Type casting (explicit conversion)


double x = 20.7;
int y = (int)x; // double is explicitly casted to int

printf("\nType Casting:\n");
printf("x (double) = %.2lf\n", x);
printf("y (int) = %d\n", y);

return 0;
}

Output:
Automatic Type Conversion:
a + b = 13.50

Type Casting:
x (double) = 20.70
y (int) = 20
Revision as per format MSRIT. F702 Rev. No. 2

C-Program to calculate the total sales given the unit price, quantity, discount and tax rate

#include <stdio.h>

int main() {
double unitPrice, quantity, discount, taxRate;
double totalSales;

// Input the unit price, quantity, discount, and tax rate


printf("Enter unit price: ");
scanf("%lf", &unitPrice);

printf("Enter quantity: ");


scanf("%lf", &quantity);

printf("Enter discount (as a percentage): ");


scanf("%lf", &discount);

printf("Enter tax rate (as a percentage): ");


scanf("%lf", &taxRate);

// Calculate total sales


double discountAmount = (discount / 100) * (unitPrice * quantity);
double taxableAmount = (unitPrice * quantity) - discountAmount;
double taxAmount = (taxRate / 100) * taxableAmount;

totalSales = taxableAmount + taxAmount;

// Display the total sales


printf("Total Sales: $%.2lf\n", totalSales);

return 0;
}

Output:
Enter unit price: 25
Enter quantity: 2
Enter discount (as a percentage): 10
Enter tax rate (as a percentage): 2
Total Sales: $45.90
Revision as per format MSRIT. F702 Rev. No. 2

C-Program to calculate a student’s average score for a course with 4 quizzes, 2 midterms
and a final. The quizzes are weighted 30%, the midterms 40% and the final 30%.

#include <stdio.h>

int main() {
double quiz1, quiz2, quiz3, quiz4, midterm1, midterm2, finalExam;
double quizWeight = 0.3, midtermWeight = 0.4, finalWeight = 0.3;
double totalScore;

// Input scores for quizzes, midterms, and final exam


printf("Enter scores for the 4 quizzes:\n");
printf("Quiz 1: ");
scanf("%lf", &quiz1);

printf("Quiz 2: ");
scanf("%lf", &quiz2);

printf("Quiz 3: ");
scanf("%lf", &quiz3);

printf("Quiz 4: ");
scanf("%lf", &quiz4);

printf("\nEnter scores for the 2 midterms:\n");


printf("Midterm 1: ");
scanf("%lf", &midterm1);

printf("Midterm 2: ");
scanf("%lf", &midterm2);

printf("\nEnter score for the final exam: ");


scanf("%lf", &finalExam);

// Calculate the weighted scores for each component


double weightedQuizScore = (quiz1 + quiz2 + quiz3 + quiz4) / 4 * quizWeight;
double weightedMidtermScore = ((midterm1 + midterm2) / 2) * midtermWeight;
double weightedFinalScore = finalExam * finalWeight;

// Calculate the total score


totalScore = weightedQuizScore + weightedMidtermScore + weightedFinalScore;

// Display the total score


printf("\nTotal Score: %.2lf\n", totalScore);

return 0;
Revision as per format MSRIT. F702 Rev. No. 2

Output:

Enter scores for the 4 quizzes:


Quiz 1: 56
Quiz 2: 78
Quiz 3: 67
Quiz 4: 89
Enter scores for the 2 midterms:
Midterm 1: 56
Midterm 2: 78
Enter score for the final exam: 89
Total Score: 75.25

3.Creating and Running C Programs on Making Decision:


• C-Program to determine the use of the character classification functions found in c-type library.
• C-Program to read a test score, calculate the grade for the score and print the grade.
• C-Program to uses a menu to allow the user to add, multiply, subtract and divide two numbers
using switch case.
• C-Program to read the name of the user, number of units consumed and print out the charges.
An electricity board charges the following rates for the use of electricity:
 For the first 200 units 80 paise per unit
 For the next 100 units 90 paise per unit
 Beyond 300 units Rs 1 per unit.

All users are charged a minimum of Rs. 100 as meter charge. If the total amount is more than Rs
400, then an additional surcharge of 15% of total amount is charged

C-Program to determine the use of the character classification functions found in c-type
library.

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

int main() {
char ch;

printf("Enter a character: ");


scanf(" %c", &ch); // Note the space before %c to skip whitespace characters

// Check if the character is a digit


if (isdigit(ch))
printf("%c is a digit.\n", ch);
Revision as per format MSRIT. F702 Rev. No. 2

else
printf("%c is not a digit.\n", ch);

// Check if the character is an alphabetic character


if (isalpha(ch))
printf("%c is an alphabetic character.\n", ch);
else
printf("%c is not an alphabetic character.\n", ch);

// Check if the character is a whitespace character


if (isspace(ch))
printf("%c is a whitespace character.\n", ch);
else
printf("%c is not a whitespace character.\n", ch);

// Check if the character is an uppercase letter


if (isupper(ch))
printf("%c is an uppercase letter.\n", ch);
else
printf("%c is not an uppercase letter.\n", ch);

// Check if the character is a lowercase letter


if (islower(ch))
printf("%c is a lowercase letter.\n", ch);
else
printf("%c is not a lowercase letter.\n", ch);

return 0;
}

Output:
Enter a character: t
t is not a digit.
t is an alphabetic character.
t is not a whitespace character.
t is not an uppercase letter.
t is a lowercase letter.
Revision as per format MSRIT. F702 Rev. No. 2

C-Program to read a test score, calculate the grade for the score and print the grade.

#include <stdio.h>

int main() {
int score;

printf("Enter the test score (out of 100): ");


scanf("%d", &score);

// Determine the grade based on the score


char grade;
if (score >= 90) {
grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else if (score >= 70) {
grade = 'C';
} else if (score >= 60) {
grade = 'D';
} else {
grade = 'F';
}

printf("Grade for the test score %d is: %c\n", score, grade);

return 0;
}

Output:
Enter the test score (out of 100): 98
Grade for the test score 98 is: A
Revision as per format MSRIT. F702 Rev. No. 2

C-Program to uses a menu to allow the user to add, multiply, subtracts and divides two
numbers using switch case
#include <stdio.h>

int main() {
int choice;
double num1, num2, result;

printf("Enter first number: ");


scanf("%lf", &num1);

printf("Enter second number: ");


scanf("%lf", &num2);

printf("Menu:\n");
printf("1. Add\n");
printf("2. Subtract\n");
printf("3. Multiply\n");
printf("4. Divide\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
result = num1 + num2;
printf("Result of addition: %.2lf\n", result);
break;
case 2:
result = num1 - num2;
printf("Result of subtraction: %.2lf\n", result);
break;
case 3:
result = num1 * num2;
printf("Result of multiplication: %.2lf\n", result);
break;
case 4:
if (num2 != 0) {
result = num1 / num2;
printf("Result of division: %.2lf\n", result);
} else {
printf("Error! Division by zero.\n");
}
break;
default:
printf("Invalid choice!\n");
}
Revision as per format MSRIT. F702 Rev. No. 2

return 0;
}

Output:
Enter first number: 4
Enter second number: 6
Menu:
1. Add
2. Subtract
3. Multiply
4. Divide
Enter your choice: 1
Result of addition: 10.00

C-Program to read the name of the user, number of units consumed and print out the
charges. An electricity board charges the following rates for the use of electricity:
 For the first 200 units 80 paise per unit
 For the next 100 units 90 paise per unit
 Beyond 300 units Rs 1 per unit.

#include <stdio.h>

int main() {
char name[100];
int units;
double totalCharge;

// Input user's name and units consumed


printf("Enter your name: ");
scanf("%s", name);

printf("Enter the number of units consumed: ");


scanf("%d", &units);

// Calculate charges based on rates


if (units <= 200) {
totalCharge = units * 0.80; // 80 paise per unit
} else if (units <= 300) {
totalCharge = 200 * 0.80 + (units - 200) * 0.90; // 80 paise for first 200 units, 90 paise for
next 100 units
} else {
totalCharge = 200 * 0.80 + 100 * 0.90 + (units - 300) * 1.0; // Rs 1 per unit beyond 300
units
Revision as per format MSRIT. F702 Rev. No. 2

// Display the charges


printf("Hello, %s!\n", name);
printf("Total charges for %d units: Rs %.2lf\n", units, totalCharge);

return 0;
}

Output:
Enter your name: nithin
Enter the number of units consumed: 45
Hello, nithin!
Total charges for 45 units: Rs 36.00

4.Creating and Running C Programs on Repetition or Loops:


• C-Program to print a number series from 1 to a user-specified limit in the form of a angle
• C-Program to print the number and sum of digits in an integer.
• C-Program to calculate the factorial of a number using for loop/ Recursion
• C-Program to calculate nth Fibonacci number.
• C-Program to convert binary to a decimal number

C-Program to print a number series from 1 to a user-specified limit in the form of a angle

#include <stdio.h>

int main() {
int limit;

printf("Enter the limit: ");


scanf("%d", &limit);

for (int i = 1; i <= limit; i++) {


printf("%d degrees\n", i);
}

return 0;
}
Output:
Enter the limit: 6
1 degrees
2 degrees
3 degrees
4 degrees
5 degrees
6 degrees
Revision as per format MSRIT. F702 Rev. No. 2

C-Program to print the number and sum of digits in an integer

#include <stdio.h>

int main() {
int num, originalNum, sum = 0, remainder;

printf("Enter an integer: ");


scanf("%d", &num);

originalNum = num;

while (num != 0) {
remainder = num % 10;
sum += remainder;
num /= 10;
}

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

return 0;
}

Output:
Enter an integer: 345
Sum of digits of 345 = 12

C-Program to calculate the factorial of a number using for loop/ Recursion

#include <stdio.h>

int main() {
int num;
unsigned long long factorial = 1;

printf("Enter a non-negative integer: ");


scanf("%d", &num);

for (int i = 1; i <= num; ++i) {


factorial *= i;
}
printf("Factorial of %d = %llu\n", num, factorial);

return 0;
}
Revision as per format MSRIT. F702 Rev. No. 2

Output:
Enter a non-negative integer: 5
Factorial of 5 = 120

C-Program to calculate nth Fibonacci number.


#include <stdio.h>

int main() {
int n, i, a = 0, b = 1, next;

printf("Enter the number of terms: ");


scanf("%d", &n);

printf("Fibonacci Series: ");

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


printf("%d, ", a);
next = a + b;
a = b;
b = next;
}

return 0;
}

Output:
Enter the number of terms: 4
Fibonacci Series: 0, 1, 1, 2,
Revision as per format MSRIT. F702 Rev. No. 2

C-Program to convert binary to a decimal number


#include <stdio.h>

int binaryToDecimal(int binary) {


int decimal = 0, base = 1, remainder;

while (binary > 0) {


remainder = binary % 10;
decimal += remainder * base;
binary /= 10;
base *= 2;
}

return decimal;
}

int main() {
int binary;

printf("Enter a binary number: ");


scanf("%d", &binary);

printf("Decimal equivalent: %d\n", binaryToDecimal(binary));

return 0;
}

Output:
Enter a binary number: 1001
Decimal equivalent: 9
Revision as per format MSRIT. F702 Rev. No. 2

5. Creating and Running C Programs on One Dimensional Arrays:


• C-Program to print square of index and print it.
• C-Program to calculate average of the number in an array.
• C-Program to sort the list using bubble sort.
• C-Program to search an ordered list using binary search.

-Program to print square of index and print it.


#include <stdio.h>

int main() {
int n;

printf("Enter the number of elements: ");


scanf("%d", &n);

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


printf("Square of index %d: %d\n", i, i * i);
}

return 0;
}
Output:
Enter the number of elements: 4
Square of index 0: 0
Square of index 1: 1
Square of index 2: 4
Square of index 3: 9

C-Program to calculate average of the number in an array.

#include <stdio.h>

int main() {
int n;
double sum = 0.0;

printf("Enter the number of elements: ");


scanf("%d", &n);

int arr[n];

printf("Enter the elements:\n");


for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
sum += arr[i];
Revision as per format MSRIT. F702 Rev. No. 2

double average = sum / n;


printf("Average: %.2lf\n", average);

return 0;
}

Output:
Enter the number of elements: 5
Enter the elements:
34567
Average: 5.00

C-Program to sort the list using bubble sort.


#include <stdio.h>

void bubbleSort(int arr[], int n)


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

printf("Enter the number of elements: ");


scanf("%d", &n);

int arr[n];

printf("Enter the elements:\n");


for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
Revision as per format MSRIT. F702 Rev. No. 2

// Sort the array


bubbleSort(arr, n);

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

return 0;
}

Output:
Enter the number of elements: 5
Enter the elements:
31256
Sorted array:
12356

C-Program to search an ordered list using binary search.


#include <stdio.h>
int binarySearch(int arr[], int n, int key) {
int left = 0;
int right = n - 1;

while (left <= right) {


int mid = left + (right - left) / 2;

if (arr[mid] == key)
return mid;

if (arr[mid] < key)


left = mid + 1;
else
right = mid - 1;
}

return -1;
}

int main() {
int n, key;

printf("Enter the number of elements: ");


scanf("%d", &n);
Revision as per format MSRIT. F702 Rev. No. 2

int arr[n];

printf("Enter the elements in sorted order:\n");


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

printf("Enter the element to search: ");


scanf("%d", &key);

int result = binarySearch(arr, n, key);

if (result == -1)
printf("Element not found.\n");
else
printf("Element found at index %d.\n", result);

return 0;
}

Output:

Enter the number of elements: 4


Enter the elements in sorted order:
4
5
6
7
Enter the element to search: 7
Element found at index 3.
Revision as per format MSRIT. F702 Rev. No. 2

6.Creating and Running C Programs on Two Dimensional Arrays:


• C-Program to perform addition of two matrices.
• C-Program to perform multiplication of two matrices.
• C-Program to find transpose of the given matrices.
• C-Program to find row sum and column sum and sum of all elements in a matrix.
• C-Program initialize/fill all the diagonal elements of a matrix with zero and print

C-Program to perform addition of two matrices.


#include <stdio.h>

void addMatrices(int mat1[10][10], int mat2[10][10], int result[10][10], int rows, int cols)
{
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = mat1[i][j] + mat2[i][j];
}
}
}

void displayMatrix(int mat[10][10], int rows, int cols) {


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", mat[i][j]);
}
printf("\n");
}
}

int main() {
int mat1[10][10], mat2[10][10], result[10][10];
int rows, cols;

printf("Enter the number of rows: ");


scanf("%d", &rows);

printf("Enter the number of columns: ");


scanf("%d", &cols);

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


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &mat1[i][j]);
}
}
Revision as per format MSRIT. F702 Rev. No. 2

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


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &mat2[i][j]);
}
}

// Perform matrix addition


addMatrices(mat1, mat2, result, rows, cols);

// Display the result


printf("Sum of the matrices:\n");
displayMatrix(result, rows, cols);

return 0;
}

Output:
Enter the number of rows: 2
Enter the number of columns: 2
Enter elements of the first matrix:
2222
Enter elements of the second matrix:
2222
Sum of the matrices:
44
44
Revision as per format MSRIT. F702 Rev. No. 2

C-Program to perform multiplication of two matrix


#include <stdio.h>

void multiplyMatrices(int mat1[10][10], int mat2[10][10], int result[10][10], int rows1, int cols1,
int rows2, int cols2) {
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
result[i][j] = 0;
for (int k = 0; k < cols1; k++) {
result[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
}

void displayMatrix(int mat[10][10], int rows, int cols) {


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", mat[i][j]);
}
printf("\n");
}
}

int main() {
int mat1[10][10], mat2[10][10], result[10][10];
int rows1, cols1, rows2, cols2;

printf("Enter the number of rows for matrix 1: ");


scanf("%d", &rows1);

printf("Enter the number of columns for matrix 1: ");


scanf("%d", &cols1);

printf("Enter elements of matrix 1:\n");


for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
scanf("%d", &mat1[i][j]);
}
}

printf("Enter the number of rows for matrix 2: ");


scanf("%d", &rows2);

printf("Enter the number of columns for matrix 2: ");


scanf("%d", &cols2);
Revision as per format MSRIT. F702 Rev. No. 2

printf("Enter elements of matrix 2:\n");


for (int i = 0; i < rows2; i++) {
for (int j = 0; j < cols2; j++) {
scanf("%d", &mat2[i][j]);
}
}

// Check if matrices can be multiplied


if (cols1 != rows2) {
printf("Matrices cannot be multiplied.\n");
return 0;
}

// Perform matrix multiplication


multiplyMatrices(mat1, mat2, result, rows1, cols1, rows2, cols2);

// Display the result


printf("Result of matrix multiplication:\n");
displayMatrix(result, rows1, cols2);

return 0;
}

Output:
Enter the number of rows for matrix 1: 2
Enter the number of columns for matrix 1: 2
Enter elements of matrix 1:
2222
Enter the number of rows for matrix 2: 2
Enter the number of columns for matrix 2: 2
Enter elements of matrix 2:
2222
Result of matrix multiplication:
88
88
Revision as per format MSRIT. F702 Rev. No. 2

C-Program to find transpose of the given matrices.

#include <stdio.h>

void transposeMatrix(int mat[10][10], int transpose[10][10], int rows, int cols) {


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
transpose[j][i] = mat[i][j];
}
}
}

void displayMatrix(int mat[10][10], int rows, int cols) {


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", mat[i][j]);
}
printf("\n");
}
}

int main() {
int mat[10][10], transpose[10][10];
int rows, cols;

printf("Enter the number of rows: ");


scanf("%d", &rows);

printf("Enter the number of columns: ");


scanf("%d", &cols);

printf("Enter elements of the matrix:\n");


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &mat[i][j]);
}
}

// Calculate the transpose of the matrix


transposeMatrix(mat, transpose, rows, cols);

// Display the original matrix


printf("Original Matrix:\n");
displayMatrix(mat, rows, cols);
Revision as per format MSRIT. F702 Rev. No. 2

// Display the transpose


printf("\nTranspose of the Matrix:\n");
displayMatrix(transpose, cols, rows);

return 0;
}

Output:
Enter the number of rows: 2
Enter the number of columns: 2
Enter elements of the matrix:
2345
Original Matrix:
23
45

Transpose of the Matrix:


24
35

C-Program to find row sum and column sum and sum of all elements in a matrix

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

void calculateSums(int mat[10][10], int rows, int cols) {


int rowSum[10] = {0};
int colSum[10] = {0};
int totalSum = 0;

// Calculate row sums and total sum


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
rowSum[i] += mat[i][j];
totalSum += mat[i][j];
}
}

// Calculate column sums


for (int j = 0; j < cols; j++) {
for (int i = 0; i < rows; i++) {
colSum[j] += mat[i][j];
}
}
Revision as per format MSRIT. F702 Rev. No. 2

// Display row sums


printf("Row sums:\n");
for (int i = 0; i < rows; i++) {
printf("Row %d: %d\n", i + 1, rowSum[i]);
}

// Display column sums


printf("\nColumn sums:\n");
for (int j = 0; j < cols; j++) {
printf("Column %d: %d\n", j + 1, colSum[j]);
}

// Display total sum


printf("\nTotal sum of all elements: %d\n", totalSum);
}

void displayMatrix(int mat[10][10], int rows, int cols) {


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", mat[i][j]);
}
printf("\n");
}
}

int main() {
int mat[10][10];
int rows, cols;

printf("Enter the number of rows: ");


scanf("%d", &rows);

printf("Enter the number of columns: ");


scanf("%d", &cols);

printf("Enter elements of the matrix:\n");


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &mat[i][j]);
}
}

// Display the original matrix


printf("\nOriginal Matrix:\n");
displayMatrix(mat, rows, cols);
Revision as per format MSRIT. F702 Rev. No. 2

// Calculate and display row sum, column sum, and total sum
printf("\n\nCalculating Sums...\n");
calculateSums(mat, rows, cols);

return 0;
}

Output:
Enter the number of rows: 2
Enter the number of columns: 2
Enter elements of the matrix:
2 2 22
Original Matrix:
22
22

Calculating Sums...
Row sums:
Row 1: 4
Row 2: 4

Column sums:
Column 1: 4
Column 2: 4

Total sum of all elements: 8


Revision as per format MSRIT. F702 Rev. No. 2

C-Program initialize/fill all the diagonal elements of a matrix with zero and print
#include <stdio.h>
void fillDiagonalWithZero(int mat[10][10], int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (i == j) {
mat[i][j] = 0;
}
}
}
}

void displayMatrix(int mat[10][10], int rows, int cols) {


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", mat[i][j]);
}
printf("\n");
}
}

int main() {
int mat[10][10];
int rows, cols;

printf("Enter the number of rows: ");


scanf("%d", &rows);

printf("Enter the number of columns: ");


scanf("%d", &cols);

printf("Enter elements of the matrix:\n");


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &mat[i][j]);
}
}
// Fill diagonal with zero
fillDiagonalWithZero(mat, rows, cols);

// Display the modified matrix


printf("\nMatrix with diagonal elements as zero:\n");
displayMatrix(mat, rows, cols);

return 0;
Revision as per format MSRIT. F702 Rev. No. 2

Output:
Enter the number of rows: 2
Enter the number of columns: 2
Enter elements of the matrix:
2222
Matrix with diagonal elements as zero:
02
20

7.Creating and Running C Programs on User Defined Functions:


• C-program to read a number, Find its factorial using function with argument and with
return type.
• C-Program to read two number, Find its GCD and LCM using function with
arguments and without return type.
• C-Program to read a number, Find whether it is a palindrome or not using function
without argument and with return type.
• C-Program to read a number, Find whether it is prime number or not using function
without arguments and without return type.

C-program to read a number, Find its factorial using function with argument and with
return type.

#include <stdio.h>
unsigned long long factorial(int num) {
if (num == 0 || num == 1)
return 1;
else
return num * factorial(num - 1);
}

int main() {
int num;

printf("Enter a non-negative integer: ");


scanf("%d", &num);

if (num < 0) {
printf("Factorial is not defined for negative numbers.\n");
} else {
unsigned long long result = factorial(num);
printf("Factorial of %d = %llu\n", num, result);
}
return 0;
}
Revision as per format MSRIT. F702 Rev. No. 2

Output:
Enter a non-negative integer: 6
Factorial of 6 = 720

C-Program to read two number, Find its GCD and LCM using function with
arguments and without return type.

#include <stdio.h>

void calculateGCDandLCM(int num1, int num2, int *gcd, int *lcm) {


int i, max;

// Find maximum between the two numbers


max = (num1 > num2) ? num1 : num2;

// Find GCD
for (i = 1; i <= max; i++) {
if (num1 % i == 0 && num2 % i == 0)
*gcd = i;
}

// Find LCM
*lcm = (num1 * num2) / *gcd;
}

int main() {
int num1, num2, gcd, lcm;

printf("Enter first number: ");


scanf("%d", &num1);

printf("Enter second number: ");


scanf("%d", &num2);

// Calculate GCD and LCM


calculateGCDandLCM(num1, num2, &gcd, &lcm);

printf("GCD of %d and %d is: %d\n", num1, num2, gcd);


printf("LCM of %d and %d is: %d\n", num1, num2, lcm);

return 0;
}
Revision as per format MSRIT. F702 Rev. No. 2

Output:
Enter first number: 4
Enter second number: 6
GCD of 4 and 6 is: 2
LCM of 4 and 6 is: 12

C-Program to read a number, Find whether it is a palindrome or not using function


without argument and with return type

#include <stdio.h>

int isPalindrome() {
int num, reversedNum = 0, originalNum;

printf("Enter a number: ");


scanf("%d", &num);

originalNum = num;

// Reverse the number


while (num != 0) {
int remainder = num % 10;
reversedNum = reversedNum * 10 + remainder;
num /= 10;
}

// Check if the original number and the reversed number are the same
if (originalNum == reversedNum)
return 1; // The number is a palindrome
else
return 0; // The number is not a palindrome
}

int main() {
int result;

result = isPalindrome();

if (result)
printf("The number is a palindrome.\n");
else
printf("The number is not a palindrome.\n");

return 0;
}
Revision as per format MSRIT. F702 Rev. No. 2

Output:
Enter a number: 121
The number is a palindrome.

Enter a number: 132


The number is not a palindrome.

C-Program to read a number, Find whether it is prime number or not using function
without arguments and without return type.

#include <stdio.h>

void checkPrime() {
int num, i, flag = 0;

printf("Enter a number: ");


scanf("%d", &num);

// 0 and 1 are not prime numbers


if (num == 0 || num == 1) {
printf("%d is not a prime number.\n", num);
return;
}

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


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

if (flag == 0)
printf("%d is a prime number.\n", num);
else
printf("%d is not a prime number.\n", num);
}

int main() {
checkPrime();
return 0;
}
Revision as per format MSRIT. F702 Rev. No. 2

Output:
Enter a number: 4
4 is not a prime number.

Enter a number: 5
5 is a prime number.

8.Creating and Running C Programs on Strings:


• C-program read two strings, Combine them without using string built-in functions.
• C-program read two strings, Compare them without using string built-in functions.
• C-program read two strings, concatenate them without using string built-in
functions.
• C Program to Check if the Substring is Present in the Given String.
• C-program to demonstrate built-in sting functions like strlen(), strcpy(), strcmp(), strcat()

C-program read two strings, Combine them without using string built-in functions.

#include <stdio.h>

void combineStrings(char str1[], char str2[], char combined[]) {


int i, j;

// Copy the first string to the combined string


for (i = 0; str1[i] != '\0'; ++i) {
combined[i] = str1[i];
}

// Concatenate the second string to the combined string


for (j = 0; str2[j] != '\0'; ++j) {
combined[i + j] = str2[j];
}

// Null-terminate the combined string


combined[i + j] = '\0';
}

int main() {
char str1[100], str2[100], combined[200];

printf("Enter the first string: ");


scanf("%s", str1);

printf("Enter the second string: ");


Revision as per format MSRIT. F702 Rev. No. 2

scanf("%s", str2);

combineStrings(str1, str2, combined);

printf("Combined string: %s\n", combined);

return 0;
}

Output:
Enter the first string: hello
Enter the second string: good
Combined string: hellogood

C-program read two strings, Compare them without using string built-in functions

#include <stdio.h>

int compareStrings(char str1[], char str2[]) {


int i = 0;

while (str1[i] != '\0' && str2[i] != '\0') {


if (str1[i] != str2[i]) {
return str1[i] - str2[i];
}
i++;
}

return str1[i] - str2[i];


}

int main() {
char str1[100], str2[100];

printf("Enter the first string: ");


scanf("%s", str1);

printf("Enter the second string: ");


scanf("%s", str2);

int result = compareStrings(str1, str2);

if (result == 0) {
printf("Strings are equal.\n");
} else if (result < 0) {
Revision as per format MSRIT. F702 Rev. No. 2

printf("First string is less than the second string.\n");


} else {
printf("First string is greater than the second string.\n");
}

return 0;
}

Output:
Enter the first string: hello
Enter the second string: good
First string is greater than the second string.

C Program to Check if the Substring is Present in the Given String


#include<stdio.h>

int main()
{
char str[80], search[10];
int count1 = 0, count2 = 0, i, j, flag;

printf("Enter a string:");
gets(str);
printf("Enter search substring:");
gets(search);
while (str[count1] != '\0')
count1++;
while (search[count2] != '\0')
count2++;
for (i = 0; i <= count1 - count2; i++)
{
for (j = i; j < i + count2; j++)
{
flag = 1;
if (str[j] != search[j - i])
{
flag = 0;
break;
}
}
if (flag == 1)
break;
}
if (flag == 1)
printf("SEARCH SUCCESSFUL!");
else
Revision as per format MSRIT. F702 Rev. No. 2

printf("SEARCH UNSUCCESSFUL!");

return 0;
}

Output
Enter a string:HELLO HI
Enter search substring:HI
SEARCH SUCCESSFUL!

C-program to demonstrate built-in sting functions like strlen(), strcpy(), strcmp(), strcat()
#include <stdio.h>
#include <string.h>

int main() {
char str1[100], str2[100];

// Demonstrate strlen()
printf("Enter a string: ");
scanf("%s", str1);
printf("Length of the string: %lu\n", strlen(str1));

// Demonstrate strcpy()
strcpy(str2, str1);
printf("Copied string using strcpy(): %s\n", str2);

// Demonstrate strcmp()
printf("Enter another string: ");
scanf("%s", str2);
int cmpResult = strcmp(str1, str2);
if (cmpResult == 0)
printf("Strings are equal.\n");
else if (cmpResult < 0)
printf("First string is less than the second string.\n");
else
printf("First string is greater than the second string.\n");

// Demonstrate strcat()
strcat(str1, str2);
printf("Concatenated string using strcat(): %s\n", str1);

return 0;
}
Revision as per format MSRIT. F702 Rev. No. 2

Output:
/tmp/iEaAHSxUVB.o
Enter a string: hello
Length of the string: 5
Copied string using strcpy(): hello
Enter another string: good
First string is greater than the second string.
Concatenated string using strcat(): hellogood

9.Creating and Running C Programs on Storage Classes and Pointers:


• C-program to show the use of auto and static variable.
• C-program to add two numbers using pointers. / C-program to swap two numbers using
pointers.
• C-program to show how the same pointer can point to different data variable.
/ C-program to show the use of different pointers point to the same variable
• C-Program to read an array of elements, Compute its sum using pointers.

C-program to show the use of auto and static variable.

#include <stdio.h>

void autoExample() {
auto int x = 10; // auto variable

printf("Auto variable: %d\n", x);

x++; // Modify the auto variable

printf("Modified auto variable: %d\n", x);


}

void staticExample() {
static int y = 20; // static variable

printf("Static variable: %d\n", y);

y++; // Modify the static variable

printf("Modified static variable: %d\n", y);


}

int main() {
printf("Inside main function:\n");

autoExample();
Revision as per format MSRIT. F702 Rev. No. 2

staticExample();

printf("Again inside main function:\n");

autoExample();
staticExample();

return 0;
}

Output:
Inside main function:
Auto variable: 10
Modified auto variable: 11
Static variable: 20
Modified static variable: 21
Again inside main function:
Auto variable: 10
Modified auto variable: 11
Static variable: 21
Modified static variable: 22

C-program to add two numbers using pointers. / C-program to swap two numbers using
pointers

C-program to add two numbers using pointers

#include <stdio.h>

void addNumbers(int *a, int *b, int *sum) {


*sum = *a + *b;
}

int main() {
int num1, num2, sum;

printf("Enter first number: ");


scanf("%d", &num1);

printf("Enter second number: ");


scanf("%d", &num2);

// Passing addresses of num1 and num2 to addNumbers function


addNumbers(&num1, &num2, &sum);

printf("Sum: %d + %d = %d\n", num1, num2, sum);


Revision as per format MSRIT. F702 Rev. No. 2

return 0;
}

Output
Enter first number: 5
Enter second number: 6
Sum: 5 + 6 = 11

C-program to swap two numbers using pointers

#include <stdio.h>

void swapNumbers(int *a, int *b) {


int temp = *a;
*a = *b;
*b = temp;
}

int main() {
int num1, num2;

printf("Enter first number: ");


scanf("%d", &num1);

printf("Enter second number: ");


scanf("%d", &num2);

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

// Passing addresses of num1 and num2 to swapNumbers function


swapNumbers(&num1, &num2);

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

return 0;
}

Output:

Enter first number: 4


Enter second number: 6
Before swapping: num1 = 4, num2 = 6
After swapping: num1 = 6, num2 = 4
Revision as per format MSRIT. F702 Rev. No. 2

C-program to show how the same pointer can point to different data variable
#include <stdio.h>

int main() {
int a = 10, b = 20;
int *ptr;

ptr = &a; // ptr points to variable a


printf("Value at ptr: %d\n", *ptr); // prints 10

ptr = &b; // ptr now points to variable b


printf("Value at ptr: %d\n", *ptr); // prints 20

return 0;
}
Output:
Value at ptr: 10
Value at ptr: 20

C-program to show the use of different pointers point to the same variable
#include <stdio.h>
int main() {
int x = 10;
int *ptr1, *ptr2;
ptr1 = &x; // ptr1 points to variable x
ptr2 = &x; // ptr2 also points to variable x

printf("Value at ptr1: %d\n", *ptr1); // prints 10


printf("Value at ptr2: %d\n", *ptr2); // prints 10

return 0;
}

Output:
Value at ptr1: 10
Value at ptr2: 10
Revision as per format MSRIT. F702 Rev. No. 2

C-Program to read an array of elements, Compute its sum using pointers.

#include <stdio.h>

int main() {
int arr[100], n, sum = 0;

printf("Enter the number of elements (max 100): ");


scanf("%d", &n);

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


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

// Compute sum using pointers


int *ptr = arr;
for (int i = 0; i < n; i++) {
sum += *ptr;
ptr++;
}

printf("Sum of the array elements: %d\n", sum);

return 0;
}

Output:
Enter the number of elements (max 100): 7
Enter elements of the array:
Enter element 1: 4
Enter element 2: 6
Enter element 3: 7
Enter element 4: 8
Enter element 5: 9
Enter element 6: 2
Enter element 7: 1
Sum of the array elements: 37
Revision as per format MSRIT. F702 Rev. No. 2

10.Creating and Running C Programs on Derived Types and Unions:


• C-Program to print selected TV stations for our cable TV systems.
• C-Program to demonstrate union of short int and two char

C-Program to print selected TV stations for our cable TV systems.

#include <stdio.h>

int main() {
char tvStations[10][30] = {
"CNN",
"BBC News",
"ESPN",
"Discovery Channel",
"National Geographic",
"Cartoon Network",
"HBO",
"FOX News",
"CNBC",
"MTV"
};

printf("TV Stations for Cable TV Systems:\n");


for (int i = 0; i < 10; i++) {
printf("%d. %s\n", i + 1, tvStations[i]);
}

return 0;
}

Output:
TV Stations for Cable TV Systems:
1. CNN
2. BBC News
3. ESPN
4. Discovery Channel
5. National Geographic
6. Cartoon Network
7. HBO
8. FOX News
9. CNBC
10. MTV
Revision as per format MSRIT. F702 Rev. No. 2

C-Program to demonstrate union of short int and two char


#include <stdio.h>

union SampleUnion {
short int s;
char c[2];
};

int main() {
union SampleUnion u;

printf("Enter a short integer: ");


scanf("%hi", &u.s);

printf("Short int: %hi\n", u.s);


printf("Characters (as bytes):\n");
printf("First char: %c\n", u.c[0]);
printf("Second char: %c\n", u.c[1]);

return 0;
}

Output:
Enter a short integer: 345
Short int: 345
Characters (as bytes):
First char: Y
Second char:

11.Creating and Running C Programs on Structures:


• C Program to read employee details (name, salary, address) and print the same
using structure.
• C-Program to read marks of three students in 3 subjects. Calculate the total marks
scored, student wise and subject wise using structure.

C Program to read employee details (name, salary, address) and print the same
using structure

#include <stdio.h>

// Define a structure for employee details


struct Employee {
char name[50];
float salary;
char address[100];
Revision as per format MSRIT. F702 Rev. No. 2

};

int main() {
struct Employee emp;

printf("Enter employee details:\n");

printf("Enter name: ");


scanf(" %[^\n]", emp.name); // Read the name with spaces

printf("Enter salary: ");


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

printf("Enter address: ");


scanf(" %[^\n]", emp.address); // Read the address with spaces

// Print employee details


printf("\nEmployee Details:\n");
printf("Name: %s\n", emp.name);
printf("Salary: %.2f\n", emp.salary);
printf("Address: %s\n", emp.address);

return 0;
}

Output:
Enter employee details:
Enter name: nithin
Enter salary: 456789
Enter address: mathikere
Employee Details:
Name: nithin
Salary: 456789.00
Address: mathikere
Revision as per format MSRIT. F702 Rev. No. 2

C-Program to read marks of three students in 3 subjects. Calculate the total marks
scored, student wise and subject wise using structure.

#include <stdio.h>
#define NUM_STUDENTS 3
#define NUM_SUBJECTS 3

// Define a structure for student details


struct Student {
int marks[NUM_SUBJECTS];
int totalMarks;
};

int main() {
struct Student students[NUM_STUDENTS] = {{0}, {0}, {0}};

// Read marks for each student and subject


for (int i = 0; i < NUM_STUDENTS; i++) {
printf("Enter marks for Student %d:\n", i + 1);
for (int j = 0; j < NUM_SUBJECTS; j++) {
printf("Enter marks for Subject %d: ", j + 1);
scanf("%d", &students[i].marks[j]);
students[i].totalMarks += students[i].marks[j];
}
}
// Print total marks scored by each student
printf("\nTotal marks scored by each student:\n");
for (int i = 0; i < NUM_STUDENTS; i++) {
printf("Student %d Total Marks: %d\n", i + 1, students[i].totalMarks);
}

// Calculate subject-wise total marks


int subjectTotal[NUM_SUBJECTS] = {0};
for (int i = 0; i < NUM_STUDENTS; i++) {
for (int j = 0; j < NUM_SUBJECTS; j++) {
subjectTotal[j] += students[i].marks[j];
}
}
// Print total marks scored in each subject
printf("\nTotal marks scored in each subject:\n");
for (int j = 0; j < NUM_SUBJECTS; j++) {
printf("Subject %d Total Marks: %d\n", j + 1, subjectTotal[j]);
}

return 0;
}
Revision as per format MSRIT. F702 Rev. No. 2

Output:
Enter marks for Student 1:
Enter marks for Subject 1: 56
Enter marks for Subject 2: 78
Enter marks for Subject 3: 89
Enter marks for Student 2:
Enter marks for Subject 1: 87
Enter marks for Subject 2: 98
Enter marks for Subject 3: 79
Enter marks for Student 3:
Enter marks for Subject 1: 89
Enter marks for Subject 2: 67
Enter marks for Subject 3: 87
Total marks scored by each student:
Student 1 Total Marks: 223
Student 2 Total Marks: 264
Student 3 Total Marks: 243

Total marks scored in each subject:


Subject 1 Total Marks: 232
Subject 2 Total Marks: 243
Subject 3 Total Marks: 255

12.Creating and Running C Programs on Files:


• C-Program to demonstrate function fread()/fscanf()
• C-Program to demonstrate function fwrite()/fprintf()

C-Program to demonstrate function fread()/fscanf()

#include <stdio.h>

typedef struct {
char name[50];
int age;
} Person;

int main() {
FILE *file;
Person person;

// Open a file in binary write mode


file = fopen("data.bin", "wb");

if (file == NULL) {
Revision as per format MSRIT. F702 Rev. No. 2

printf("Could not open the file for writing.\n");


return 1;
}

// Write data using fwrite()


Person persons[] = {{"Alice", 30}, {"Bob", 25}, {"Charlie", 35}};
fwrite(persons, sizeof(Person), 3, file);

// Close the file


fclose(file);

// Open the file in binary read mode


file = fopen("data.bin", "rb");

if (file == NULL) {
printf("Could not open the file for reading.\n");
return 1;
}

// Read data using fread()


printf("Reading data using fread():\n");
fread(&person, sizeof(Person), 1, file);
printf("Name: %s, Age: %d\n", person.name, person.age);

// Close the file


fclose(file);

// Open the file in text read mode


file = fopen("data.txt", "r");

if (file == NULL) {
printf("Could not open the file for reading.\n");
return 1;
}

// Read data using fscanf()


printf("\nReading data using fscanf():\n");
while (fscanf(file, "%s %d", person.name, &person.age) != EOF) {
printf("Name: %s, Age: %d\n", person.name, person.age);
}

// Close the file


fclose(file);

return 0;
}
Revision as per format MSRIT. F702 Rev. No. 2

Output:
Reading data using fread():
Name: Alice, Age: 30
Could not open the file for reading.

C-Program to demonstrate function fwrite()/fprintf()

#include <stdio.h>

typedef struct {
char name[50];
int age;
} Person;

int main() {
FILE *binaryFile, *textFile;
Person persons[] = {{"Alice", 30}, {"Bob", 25}, {"Charlie", 35}};

// Open a binary file for writing


binaryFile = fopen("data.bin", "wb");

if (binaryFile == NULL) {
printf("Could not open the binary file for writing.\n");
return 1;
}

// Write data to the binary file using fwrite()


fwrite(persons, sizeof(Person), 3, binaryFile);

// Close the binary file


fclose(binaryFile);

// Open a text file for writing


textFile = fopen("data.txt", "w");

if (textFile == NULL) {
printf("Could not open the text file for writing.\n");
return 1;
}

// Write data to the text file using fprintf()


for (int i = 0; i < 3; i++) {
fprintf(textFile, "Name: %s, Age: %d\n", persons[i].name, persons[i].age);
}
Revision as per format MSRIT. F702 Rev. No. 2

// Close the text file


fclose(textFile);

printf("Data written to files successfully.\n");

return 0;
}
Output:
Data written to files successfully.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy