c Programming Practical Assignment

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 49

NAVGUJARAT COLLEGE OF COMPUTER APPLICATION ,

USMANPURA

NAME:-KHAMBHALIYA MEET RAJESHBHAI


ROLL NO:-1126
BATCH:-B1
COURSE NAME:-C PROGRAMMING PRACTICAL
COURSE CODE:-DSC-C-BCA-112 P

1. Loops and decision


making controls

1. Write a program to calculate simple interest. Accept Principle


amount, rate of interest and duration in years from the user.
.

#include <stdio.h>

#include <conio.h>

int main()

float principal, rate, time, interest;

// Prompt user for input printf("Enter

Principal amount: "); scanf("%f",

&principal); printf("Enter Rate of

interest: "); scanf("%f", &rate);

printf("Enter Time in years: ");

MEET PATEL
scanf("%f", &time); // Calculate Simple

Interest interest = (principal * rate *

time) / 100; // Display the result

printf("Simple Interest = %.2f\n", interest);

getch();

2. Write a program to swap two variables by taking third


variable and without taking third variable.
.

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

int main()

{ int a = 5;

int b = 10;

int temp;

// Using a third variable to

swap temp = a; a = b;

b = temp; printf("After swapping using third

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

printf("b = %d\n", b); getch();

3. Write a program to find greatest number from given 3


numbers from the user using nested if and using conditional
operator.
.

#include <stdio.h>

#include <conio.h>

int main() { int num1, num2, num3; //

Prompt user for input printf("Enter three

MEET PATEL
numbers: "); scanf("%d %d %d", &num1,

&num2, &num3);

// Using nested if statements if (num1 >= num2)

{ if (num1 >= num3) { printf("The greatest

number is: %d\n", num1);

} else {

printf("The greatest number is: %d\n", num3);

} else {

if (num2 >= num3) { printf("The greatest

number is: %d\n", num2);

} else {

printf("The greatest number is: %d\n", num3);

getch();

4. Write a program to convert temperature from Fahrenheit to


Celsius and from Celsius to Fahrenheit.
.

#include <stdio.h>

#include <conio.h> int

main() { float fahrenheit,

celsius; int choice;

// Prompt the user for choice

printf("Temperature Conversion Menu\n");

printf("1. Convert Fahrenheit to Celsius\n");

printf("2. Convert Celsius to Fahrenheit\n");

MEET PATEL
printf("Enter your choice (1 or 2): "); scanf("%d",

&choice);

if (choice == 1) {

// Fahrenheit to Celsius printf("Enter temperature in Fahrenheit: ");

scanf("%f", &fahrenheit); celsius = (fahrenheit - 32) * 5 / 9;

printf("%.2f Fahrenheit is equal to %.2f Celsius\n", fahrenheit, celsius);

} else if (choice == 2) { // Celsius to Fahrenheit printf("Enter

temperature in Celsius: "); scanf("%f", &celsius); fahrenheit =

(celsius * 9 / 5) + 32; printf("%.2f Celsius is equal to %.2f Fahrenheit\n",

celsius, fahrenheit);

} else {

printf("Invalid choice! Please enter 1 or 2.\n");

getch();

5. Demonstrate printing Table of given number using loop.


.

#include <stdio.h>

#include <conio.h>

int main()

int num, i;

// Prompt user for input printf("Enter a number to print its

multiplication table: "); scanf("%d", &num);

printf("Multiplication Table of %d:\n", num); // Using a

loop to print the table for (i = 1; i <= 10; ++i)

printf("%d x %d = %d\n", num, i, num * i);


MEET PATEL
}

getch();
}

6. Demonstrate to find factorial of given number.


.

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

int main() { int num, i; unsigned long long

factorial = 1; // Prompt user for input

printf("Enter a number to find its factorial: ");

scanf("%d", &num);

// Error handling for negative numbers

if (num < 0) { printf("Factorial of negative numbers

doesn't exist.\n");

} else {

// Loop to calculate factorial

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

{ factorial *= i;

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

getch();

7. Demonstrate to find maximum from given N inputs by user.


.

#include <stdio.h>

#include <conio.h>

int main() { int n, i,

num, max;

MEET PATEL
// Prompt user for the number of inputs

printf("Enter the number of inputs: "); scanf("%d",

&n);

// Check if the number of inputs is valid

if (n <= 0) { printf("Please enter a positive number of

inputs.\n");

return 1;

// Prompt user for the first input and assume it's the maximum

printf("Enter number 1: "); scanf("%d", &num); max = num;

// Loop through the remaining inputs

for (i = 2; i <= n; i++)

{ printf("Enter number %d: ", i);

scanf("%d", &num);

// Update max if the current input is greater than max

if (num > max) { max = num;

// Display the maximum number printf("The

maximum number is: %d\n", max);

getch();

8. Demonstrate to find reverse of a given number.


.

#include <stdio.h>

#include <conio.h>

int main() { int num, reversed = 0,

remainder; // Prompt user for

MEET PATEL
input printf("Enter an integer: ");

scanf("%d", &num);

// Process of reversing the number while (num != 0) { remainder

= num % 10; // Get the last digit reversed = reversed * 10 +

remainder; // Build the reversed number num /= 10; // Remove the

last digit

// Display the reversed number

printf("Reversed number: %d\n", reversed);

getch();

9. Demonstrate to generate Fibonacci series up to N numbers.


.

#include <stdio.h>

#include <conio.h> int

main() {

int n, i;

unsigned long long t1 = 0, t2 = 1, nextTerm;

// Prompt user for input printf("Enter the

number of terms: "); scanf("%d", &n);

printf("Fibonacci Series: %llu, %llu", t1, t2);

for (i = 3; i <= n; ++i) { nextTerm = t1 + t2;

printf(", %llu", nextTerm);

t1 = t2; t2

= nextTerm;

printf("\n");

getch();

MEET PATEL
10. Demonstrate to find GCD and LCM of given 2 numbers.
.

#include <stdio.h>

#include<conio.h>

// Function to find GCD using Euclidean algorithm

int findGCD(int a, int b) { while (b != 0) { int

temp = b; b = a % b; a = temp;

return a;

// Function to find LCM int

findLCM(int a, int b, int gcd)

{ return (a * b) / gcd;

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

lcm; // Prompt user for input

printf("Enter two integers: ");

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

// Calculate GCD gcd =

findGCD(num1, num2);

// Calculate LCM lcm =

findLCM(num1, num2, gcd);

// Display the results printf("GCD of %d and %d = %d\

n", num1, num2, gcd); printf("LCM of %d and %d = %d\

n", num1, num2, lcm);

getch();

11. Demonstrate to check whether given is Palindrome or not.

MEET PATEL
#include <stdio.h> #include<conio.h> int main() {

int num, originalNum, reversed = 0, remainder;

// Prompt user for input printf("Enter an integer:

"); scanf("%d", &num); originalNum = num; //

Store the original number

// Process of reversing the number

while (num != 0) {

remainder = num % 10; reversed

= reversed * 10 + remainder; num /=

10;

// Check if the original number and the reversed number are the same

if (originalNum == reversed) { printf("%d is a palindrome.\n",

originalNum);

} else {

printf("%d is not a palindrome.\n", originalNum);

getch();

12. Demonstrate to check whether the given number is Prime or


not.

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

int main() { int num, i, isPrime = 1;

// Prompt user for input

printf("Enter a positive integer: ");

scanf("%d", &num);

MEET PATEL
// Check if number is less than 2

if (num <= 1) { isPrime = 0;

} else {

// Loop to check if the number is divisible by any number other than 1 and itself

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

if (num % i == 0) {

isPrime = 0; break;

// Check the result if (isPrime)

{ printf("%d is a prime number.\n",

num);

} else {

printf("%d is not a prime number.\n", num);

return 0;

2. Pattern, Array String and


Functions

1. Print the following pyramid. [Left aligned, Right Aligned,


Center Aligned]
*

**

MEET PATEL
***

****

LEFT ALIGNED :-
#include <stdio.h>

#include<conio.h>

int main() { int

rows = 5, i, j; for

(i = 1; i <= rows; +

+i) { for (j = 1;

j <= i; ++j)

{ printf("*

");

printf("\n");

getch();

RIGHT ALIGNED:-
#include <stdio.h> #include<conio.h> int main()

{ int rows = 5, i, j, space; for (i = 1; i <=

rows; ++i) { for (space = 1; space <= rows -

i; ++space) { printf(" "); // Print space

for (j = 1; j <= i; ++j)

{ printf("* ");

printf("\n");

getch();

MEET PATEL
CENTER ALIGNED :-
#include <stdio.h>

#include<conio.h> int

main()

int rows = 5, i, j, space; for

(i = 1; i <= rows; ++i)

for (space = 1; space <= rows - i; ++space)

{ printf(" "); // Print

space

for (j = 1; j <= 2*i - 1; ++j)

{ printf("*

");

printf("\n");

getch();

2. To accept an integer N, if the integer N = 4, then print the


pyramid :
1

121

12321 1234321.

MEET PATEL
#include <stdio.h>

#include<conio.h> int

main() {

int n, i, j;

// Prompt user for input

printf("Enter an integer N: ");

scanf("%d", &n);

// Generate the pyramid pattern

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

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

printf("%d", j);

} for (j = i - 1; j >=

1; j--) { printf("%d",

j);

printf("\n");

getch();

3. A program which will take 10 numbers from user and stored


it in the array. It will print all the numbers, their sum and
average of it.
.

#include <stdio.h>

#include<conio.h> int

main()

MEET PATEL
int numbers[10];

int sum = 0; float

average;

// Prompt user for 10 numbers

printf("Enter 10 numbers:\n");

for (int i = 0; i < 10; ++i)

printf("Number %d: ", i + 1);

scanf("%d", &numbers[i]); sum +=

numbers[i]; // Adding the number to sum

// Calculate average average =

sum / 10.0; // Print all numbers

printf("The numbers entered are: ");

for (int i = 0; i < 10; ++i)

printf("%d ", numbers[i]);

printf("\n");

// Print sum and average printf("Sum of the

numbers: %d\n", sum); printf("Average of the

numbers: %.2f\n", average); getch();

4. Demonstrate to sort an array.


.

#include <stdio.h>

#include<conio.h> void

bubbleSort(int arr[], int n)

MEET PATEL
{ 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 arr[j] and arr[j+1]

temp = arr[j]; arr[j] = arr[j+1];

arr[j+1] = temp;

int main() {

int n, i;

// Prompt user for number of elements

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

scanf("%d", &n); int arr[n];

// Prompt user to input array elements

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

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

{ printf("Element %d: ", i + 1);

scanf("%d", &arr[i]);

// Sort the array

bubbleSort(arr, n); //

Print the sorted array

printf("Sorted array: ");

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

{ printf("%d ", arr[i]);

MEET PATEL
}

printf("\n");

getch();

5. Demonstrate to find addition of two matrices of 3*3.


.

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

int main()

int matrix1[3][3], matrix2[3][3], sum[3][3];

int i, j;

// Prompt user to input elements for first matrix

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

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

{ for (j = 0; j < 3; +

+j)

printf("Element [%d][%d]: ", i + 1, j + 1);

scanf("%d", &matrix1[i][j]);

// Prompt user to input elements for second matrix

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

for (i = 0; i < 3; ++i) { for (j = 0; j < 3; ++j)

{ printf("Element [%d][%d]: ", i + 1, j +

1); scanf("%d", &matrix2[i][j]);

// Adding the two matrices

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

MEET PATEL
{ for (j = 0; j < 3; +

+j)

sum[i][j] = matrix1[i][j] + matrix2[i][j];

// Display the result printf("Sum of

the two matrices:\n");

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

(j = 0; j < 3; ++j)

{ printf("%d ", sum[i]

[j]); if (j == 2) printf("\

n");

getch();

6. Demonstrate to find multiplication of two matrices of 3*3.


.

#include <stdio.h> #include<conio.h> int main() {

int matrix1[3][3], matrix2[3][3], product[3][3];

int i, j, k;

// Prompt user to input elements for the first matrix

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

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

{ for (j = 0; j < 3; +

+j)

MEET PATEL
printf("Element [%d][%d]: ", i + 1, j + 1);

scanf("%d", &matrix1[i][j]);

// Prompt user to input elements for the second matrix

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

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

{ for (j = 0; j < 3; +

+j)

printf("Element [%d][%d]: ", i + 1, j + 1);

scanf("%d", &matrix2[i][j]);

// Initialize the product matrix to zero

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

{ for (j = 0; j < 3; +

+j)

product[i][j] = 0;

} // Multiply the two matrices

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

{ for (j = 0; j < 3; +

+j)

for (k = 0; k < 3; ++k)

product[i][j] += matrix1[i][k] * matrix2[i][j];

MEET PATEL
}

// Display the result printf("Product of

the two matrices:\n"); for (i = 0; i < 3; ++i)

{ for (j = 0; j < 3; +

+j)

printf("%d ", product[i][j]);

if (j == 2) printf("\n");

getch();

7. Input a string from the user and check whether the string is
palindrome or not.
.

#include <stdio.h>

#include<conio.h> #include

<string.h> int main() { char

str[100], reversedStr[100];

int i, len;

// Prompt user for input printf("Enter a string: "); gets(str); //

Note: gets() is risky, prefer fgets() in production code

// Calculate length of the string

len = strlen(str); // Reverse the

string

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

{ reversedStr[i] = str[len - 1 - i];

reversedStr[len] = '\0'; // Null-terminate the reversed string

MEET PATEL
// Check if the original string is equal to the reversed string

if (strcmp(str, reversedStr) == 0) { printf("%s is a

palindrome.\n", str);

} else { printf("%s is not a

palindrome.\n", str);

getch();

8. Demonstrate to print factorial of a given number by recursive


user defined function fact(int).

#include <stdio.h>

#include<conio.h>

// Recursive function to find factorial

int fact(int n) { if (n == 0)

{ return 1; // Base case: 0! is

} else { return n * fact(n - 1); //

Recursive case

int main()

{ int num;

// Prompt user for input printf("Enter an

integer: "); scanf("%d", &num); // Calculate and

print factorial printf("Factorial of %d is %d\n",

num, fact(num)); getch();

MEET PATEL
9. Demonstrate to convert lowercase string to uppercase string
(without including string.h).
.

#include <stdio.h>

#include<conio.h> void

toUppercase(char* str)

{ for (int i = 0; str[i] != '\0'; i+

+)

if (str[i] >= 'a' && str[i] <= 'z')

{ str[i] = str[i] - 'a' +

'A';

int main()

{ char

str[100];

// Prompt user for input printf("Enter a lowercase string: ");

gets(str); // Note: gets() is risky, prefer fgets() in production code

// Convert to uppercase

toUppercase(str); // Print the result

printf("Uppercase string: %s\n", str);

getch();

10. Take a lowercase string from the user and print its length
and uppercase string.

MEET PATEL
.

#include <stdio.h>

#include<conio.h>

// Function to calculate the length of a string int

stringLength(char* str)

int length = 0; while

(str[length] != '\0')

length++;

return length;

// Function to convert lowercase string to uppercase void

toUppercase(char* str)

{ for (int i = 0; str[i] != '\0'; i+

+)

{ if (str[i] >= 'a' && str[i] <=

'z')

{ str[i] = str[i] - 'a' +

'A';

int main()

char str[100];

// Prompt user for input printf("Enter a lowercase string: ");

gets(str); // Note: gets() is risky, prefer fgets() in production code

MEET PATEL
// Calculate length and convert to uppercase

int length = stringLength(str);

toUppercase(str); // Print the results

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

printf("Uppercase string: %s\n", str); getch();

11. A program that uses function digit(n, k) that return the


value of the kth digit the right of the number N. For e.g. The
function call digit (254693, 2) should return 9.
.

#include <stdio.h>

#include<conio.h>

// Function to find the k-th digit from the right of number n

int digit(int n, int k)

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

{ n /= 10;

return n % 10;

int main() {

int n, k, result;

// Prompt user for input

printf("Enter the number N: ");

scanf("%d", &n); printf("Enter

the position k: "); scanf("%d",

&k);

MEET PATEL
// Call the function and get the result result = digit(n, k); //

Display the result printf("The %d-th digit from the right of %d is

%d\n", k, n, result); getch();

12. Demonstrate to find if the given no. is prime or not. The


function should accept the number as an argument and
return if the no. is prime or not.

#include <stdio.h>

#include<conio.h>

// Function to check if a number is prime int

isPrime(int num)

if (num <= 1)

return 0; // 0 and 1 are not prime numbers

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

{ if (num % i ==

0)

return 0; // If divisible by any number other than 1 and itself, it's not prime

return 1; // If not divisible by any number other than 1 and itself, it's prime

int main()

MEET PATEL
int num;

// Prompt user for input

printf("Enter a number: ");

scanf("%d", &num);

// Check if the number is prime

if (isPrime(num))

printf("%d is a prime number.\n", num);

} else {

printf("%d is not a prime number.\n", num);

getch();

3. Structures and
Union

1. Define structure called state having member variables as


state name, number of districts and total population. Input
and display 5 State data.
.

#include <stdio.h>

#include<conio.h>

// Define structure for state

struct State { char

name[50]; int

MEET PATEL
numberOfDistricts; long

totalPopulation;

};

int main() { struct

State states[5];

int i;

// Input data for 5 states printf("Enter data

for 5 states:\n"); for (i = 0; i < 5; i++)

{ printf("State %d:\n", i + 1);

printf("Name: "); scanf("%s",

states[i].name); printf("Number of

Districts: "); scanf("%d",

&states[i].numberOfDistricts); printf("Total

Population: "); scanf("%ld",

&states[i].totalPopulation);

// Display data for 5 states printf("\

nDisplaying data for 5 states:\n");

for (i = 0; i < 5; i++) { printf("State %d: \n", i + 1);

printf("Name: %s\n", states[i].name); printf("Number of Districts:

%d\n", states[i].numberOfDistricts); printf("Total Population:

%ld\n", states[i].totalPopulation);

getch();

2. Define a structure called Item having member variables:


Item code, Item name, item price. Create an array of structure
to store five Items. Create a function which accepts the Item

MEET PATEL
array and modifies each element with an increase of 10% in
the price.
.

#include <stdio.h>

#include<conio.h>

// Define the structure for Item struct

Item

int code;

char name[50];

float price;

};

// Function to increase the price of each item by 10% void

increasePrice(struct Item items[], int size)

{ for (int i = 0; i < size; i+

+)

items[i].price *= 1.10;

int main() { struct

Item items[5];

int i;

// Input data for 5 items

printf("Enter data for 5 items:\n");

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

printf("Item %d:\n", i + 1);

printf("Code: "); scanf("%d",

&items[i].code);

printf("Name: "); scanf("%s",

MEET PATEL
items[i].name); printf("Price:

"); scanf("%f",

&items[i].price);

// Increase the price of each item by 10%

increasePrice(items, 5);

// Display the modified data for 5 items printf("\nModified

data for 5 items with increased prices:\n");

for (i = 0; i < 5; i++) { printf("Item

%d:\n", i + 1); printf("Code: %d\n",

items[i].code); printf("Name: %s\n",

items[i].name); printf("Price: %.2f\n",

items[i].price);

getch();

3. Define a structure to represent a date. Use your structures


that accept two different dates in the format mm dd of the
same year. Write a C program to display the month names of
both dates.
.

#include <stdio.h>

#include<conio.h>

// Define the structure to represent a date struct

Date {

int month;

int day;

};

MEET PATEL
// Function to get the month name const

char* getMonthName(int month)

{ const char* monthNames[] = {

"January", "February", "March", "April", "May", "June",

"July", "August", "September", "October", "November", "December"

};

if (month >= 1 && month <= 12)

{ return monthNames[month - 1];

} else { return "Invalid

month";

int main() { struct Date

date1, date2;

// Prompt user to input the first date printf("Enter the first

date (mm dd): "); scanf("%d %d", &date1.month, &date1.day);

// Prompt user to input the second date printf("Enter the second

date (mm dd): "); scanf("%d %d", &date2.month, &date2.day);

// Display the month names of both dates printf("First date is in

%s\n", getMonthName(date1.month)); printf("Second date is in

%s\n", getMonthName(date2.month));

getch();

4. Define a structure that can describe a Hotel. It should have


members that include name, address, grade, room charges, grade
and no of rooms. Write a function to print out all hotel details with
room charges less than a given value.
.

#include <stdio.h>

MEET PATEL
#include<conio.h>

#include <string.h>

// Define the structure for a hotel

struct Hotel { char name[50];

char address[100]; int grade;

float roomCharges; int

numberOfRooms;

};

// Function to print hotel details with room charges less than a given value

void printHotels(struct Hotel hotels[], int size, float maxCharges)

{ printf("Hotels with room charges less than %.2f:\n", maxCharges);

for (int i = 0; i < size; i++) { if (hotels[i].roomCharges <

maxCharges) { printf("Name: %s\n", hotels[i].name);

printf("Address: %s\n", hotels[i].address); printf("Grade: %d\

n", hotels[i].grade); printf("Room Charges: %.2f\n",

hotels[i].roomCharges); printf("Number of Rooms: %d\n",

hotels[i].numberOfRooms);

printf("\n");

int main() {

struct Hotel hotels[5];

int i;

// Input data for 5 hotels printf("Enter data for 5 hotels:\n"); for (i

= 0; i < 5; i++) { printf("Hotel %d:\n", i + 1); printf("Name: ");

scanf("%s", hotels[i].name); printf("Address: "); scanf(" %[^\n]

%*c", hotels[i].address); // To read string with spaces printf("Grade:

"); scanf("%d", &hotels[i].grade); printf("Room Charges: ");

scanf("%f", &hotels[i].roomCharges); printf("Number of Rooms: ");

scanf("%d", &hotels[i].numberOfRooms);

MEET PATEL
}

float maxCharges; printf("Enter the maximum room

charges to filter hotels: "); scanf("%f", &maxCharges);

// Print hotels with room charges less than the given value

printHotels(hotels, 5, maxCharges); getch();

5. Accept records of different states using array of structures.


The structure should contain state and number of
engineering colleges, medical colleges, management colleges
and universities. Calculate total colleges and display the
state, which is having highest number of colleges.
.

#include <stdio.h>

#include<conio.h>

#include <string.h>

// Define the structure for state

struct State { char name[50];

int engineeringColleges; int

medicalColleges; int

managementColleges;

int universities;

int totalColleges;

};

int main() { struct State states[5]; int i,

maxCollegesIndex = 0; // Input data for 5 states

printf("Enter data for 5 states:\n"); for (i = 0; i <

5; i++) { printf("State %d:\n", i + 1);

printf("Name: "); scanf("%s", states[i].name);

MEET PATEL
printf("Number of Engineering Colleges: ");

scanf("%d", &states[i].engineeringColleges);

printf("Number of Medical Colleges: ");

scanf("%d", &states[i].medicalColleges);

printf("Number of Management Colleges: ");

scanf("%d", &states[i].managementColleges);

printf("Number of Universities: "); scanf("%d",

&states[i].universities);

// Calculate total number of colleges

states[i].totalColleges = states[i].engineeringColleges +

states[i].medicalColleges +

states[i].managementColleges +

states[i].universities;

// Find the state with the highest number of colleges

for (i = 1; i < 5; i++) { if (states[i].totalColleges >

states[maxCollegesIndex].totalColleges) { maxCollegesIndex = i;

// Display the details of the state with the highest number of colleges

printf("\nState with the highest number of colleges:\n"); printf("Name:

%s\n", states[maxCollegesIndex].name); printf("Total Colleges: %d\n",

states[maxCollegesIndex].totalColleges); getch();

6. Define a structure by name time with members seconds,


minutes and hours. If time1 and time2 are two variables of
the structure type, write a program to find the difference in
time using a function.

MEET PATEL
.

#include <stdio.h>

#include<conio.h>

// Define the structure for time

struct Time { int hours; int

minutes;

int seconds;

};

// Function to calculate the difference between two times struct

Time calculateDifference(struct Time start, struct Time end)

{ struct Time diff; // Calculate seconds if (end.seconds <

start.seconds) { end.seconds += 60; end.minutes -= 1;

diff.seconds = end.seconds - start.seconds;

// Calculate minutes if

(end.minutes < start.minutes) {

end.minutes += 60; end.hours -

= 1;

diff.minutes = end.minutes - start.minutes;

// Calculate hours diff.hours =

end.hours - start.hours; return diff;

int main() { struct Time startTime, endTime,

difference;

// Input start time printf("Enter start time (hh mm ss): "); scanf("%d %d %d",

&startTime.hours, &startTime.minutes, &startTime.seconds);

// Input end time printf("Enter end time (hh mm ss): "); scanf("%d %d %d",

&endTime.hours, &endTime.minutes, &endTime.seconds);

MEET PATEL
// Calculate the difference difference =

calculateDifference(startTime, endTime); // Display

the difference

printf("Time difference: %02d:%02d:%02d\n", difference.hours, difference.minutes,


difference.seconds); getch();

7. Declare structure having state name, population, literacy


rate and per capita income. Input 5 records. Display the state
whose literacy rate is highest and whose per capita income is
highest.
.

#include <stdio.h>

#include<conio.h>

#include <string.h>

// Define the structure for a state

struct State { char name[50];

long population; float

literacyRate; long

perCapitaIncome;

};

int main() { struct

State states[5];

int i;

int highestLiteracyIndex = 0; int

highestIncomeIndex = 0; // Input

data for 5 states printf("Enter data

for 5 states:\n");

MEET PATEL
for (i = 0; i < 5; i++)

{ printf("State %d:\n", i + 1);

printf("Name: "); scanf("%s",

states[i].name);

printf("Population: ");

scanf("%ld", &states[i].population);

printf("Literacy Rate: ");

scanf("%f", &states[i].literacyRate);

printf("Per Capita Income: ");

scanf("%ld",

&states[i].perCapitaIncome); //

Check for the highest literacy rate

if (states[i].literacyRate >

states[highestLiteracyIndex].literac

yRate) { highestLiteracyIndex

= i;

// Check for the highest per capita income if (states[i].perCapitaIncome >

states[highestIncomeIndex].perCapitaIncome) { highestIncomeIndex = i;

// Display the state with the highest literacy rate printf("\nState with the

highest literacy rate:\n"); printf("Name: %s\n",

states[highestLiteracyIndex].name); printf("Literacy Rate: %.2f%%\n",

states[highestLiteracyIndex].literacyRate);

// Display the state with the highest per capita income printf("\nState with the

highest per capita income:\n"); printf("Name: %s\n",

states[highestIncomeIndex].name); printf("Per Capita Income: %ld\n",

states[highestIncomeIndex].perCapitaIncome); getch();

MEET PATEL
8. Define a structure employee with member variables having
employee name, basic pay, dearness allowance, house rent,
and net salary. Store data of 5 employees. Write a function
which calculates the net salary of employees and prints all
employee details in descending order of their net salary.
.

#include <stdio.h>

#include<conio.h>

#include <string.h>

// Define the structure for an employee

struct Employee { char name[50];

float basicPay; float

dearnessAllowance; float houseRent;

float netSalary;

};

// Function to calculate net salary void calculateNetSalary(struct

Employee employees[], int size) {

for (int i = 0; i < size; i++)

{ employees[i].netSalary = employees[i].basicPay

+ employees[i].dearnessAllowance

+ employees[i].houseRent;

// Function to sort employees in descending order of net salary void

sortEmployeesByNetSalary(struct Employee employees[], int size)

{ struct Employee temp;

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

for (int j = i + 1; j < size; j++) {

MEET PATEL
if (employees[i].netSalary < employees[j].netSalary) {

temp = employees[i];

employees[i] = employees[j];

employees[j] = temp;

// Function to print employee details void

printEmployeeDetails(struct Employee employees[], int size) {

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

printf("Name: %s\n", employees[i].name); printf("Basic Pay: %.2f\n",

employees[i].basicPay); printf("Dearness Allowance: %.2f\n",

employees[i].dearnessAllowance); printf("House Rent: %.2f\n",

employees[i].houseRent); printf("Net Salary: %.2f\n\n",

employees[i].netSalary);

int main() { struct Employee

employees[5];

int i;

// Input data for 5 employees

printf("Enter data for 5 employees:\n");

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

{ printf("Employee %d:\n", i + 1);

printf("Name: "); scanf("%s",

employees[i].name);

printf("Basic Pay: ");

scanf("%f", &employees[i].basicPay);

printf("Dearness Allowance: "); scanf("%f",

MEET PATEL
&employees[i].dearnessAllowance);

printf("House Rent: "); scanf("%f",

&employees[i].houseRent);

// Calculate net salary for each employee

calculateNetSalary(employees, 5); // Sort

employees by net salary

sortEmployeesByNetSalary(employees, 5);

// Print employee details printf("\nEmployee details sorted by net salary

in descending order:\n"); printEmployeeDetails(employees, 5); getch();

9. Define a structure with tag population with fields Men and


Women. Create structure with in structure using state and
population structure. Read and display the data.
.

#include <stdio.h>

#include<conio.h>

// Define the structure for Population

struct Population { int men; int

women;

};

// Define the structure for State that includes Population structure

struct State { char name[50]; struct Population population;

};

int main() { struct

State states[5];

int i;

MEET PATEL
// Input data for 5 states

printf("Enter data for 5 states:\n");

for (i = 0; i < 5; i++) { printf("State %d:\n",

i + 1); printf("Name: "); scanf("%s",

states[i].name); printf("Number of Men: ");

scanf("%d", &states[i].population.men);

printf("Number of Women: "); scanf("%d",

&states[i].population.women);

// Display the data for the 5 states printf("\

nDisplaying data for 5 states:\n");

for (i = 0; i < 5; i++) { printf("State %d:\n", i + 1);

printf("Name: %s\n", states[i].name); printf("Men:

%d\n", states[i].population.men); printf("Women:

%d\n", states[i].population.women);

printf("\n");

getch();

10. Demonstrate the use of Union.


.

#include <stdio.h>
#include<conio.h> // Define a union union Data {
int i; float f; char str[20];
};
int main() { union Data data; // Store an integer data.i = 10; printf("data.i: %d\n", data.i);
// Store a float data.f = 220.5; printf("data.f: %.1f\n", data.f);
// Store a string strcpy(data.str,

"Hello"); printf("data.str: %s\n",

data.str); getch();

MEET PATEL
4. Pointers

1. Demonstrate a user-defined function which will swap the


values of two variables using pointer (Call by reference).
.

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

// Function to swap the values of two variables using pointers

void swap(int *a, int *b) { int temp; temp = *a; *a = *b;

*b = temp;

} int main()

int x, y;

// Prompt user for input

printf("Enter value of x: ");

scanf("%d", &x); printf("Enter

value of y: "); scanf("%d", &y);

// Display values before swap

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

// Call the swap function

swap(&x, &y);

// Display values after swap printf("After

swap: x = %d, y = %d\n", x, y); getch();

2. Demonstrate a user defined function calc(), which will


return the sum, subtraction, multiplication, and division values
MEET PATEL
of two variable locally declared in the main function use of
pointer.
.

#include <stdio.h>

#include<conio.h>

// Function to perform arithmetic operations void calc(int *a, int

*b, int *sum, int *sub, int *mul, float *div) {

*sum = *a + *b;

*sub = *a - *b;

*mul = (*a) * (*b);

*div = (float)(*a) / (*b); // Typecasting to float for division

} int main()

int x, y; int sum,

sub, mul; float

div;

// Prompt user for input printf("Enter

value of x: "); scanf("%d", &x);

printf("Enter value of y: "); scanf("%d",

&y); // Call calc() function calc(&x,

&y, &sum, &sub, &mul, &div);

// Display results printf("Sum:

%d\n", sum); printf("Subtraction:

%d\n", sub); printf("Multiplication:

%d\n", mul); printf("Division: %.2f\

n", div); getch();

3. Demonstrate UDF which will return the length of the string


declared locally in the main (use pointer).
MEET PATEL
.

#include <stdio.h>

#include<conio.h>

// Function to calculate the length of a string

int stringLength(char *str) { int length = 0;

while (*(str + length) != '\0') {

length++;

return length;

int main()

{ char

str[100];

// Prompt user for input printf("Enter a string: "); gets(str); //

Note: gets() is risky, prefer fgets() in production code // Calculate

the length of the string using the stringLength function int length =

stringLength(str); // Print the length of the string printf("Length of

the string: %d\n", length); getch();

4. Write a program in C to find the maximum number between


two numbers using a pointer.
.

#include <stdio.h>

#include<conio.h>

// Function to find the maximum number between two numbers using pointers

int findMax(int *a, int *b) {

if (*a > *b) { return *a;

} else { return *b;

MEET PATEL
}

int main() { int

num1, num2;

// Prompt user for input

printf("Enter the first number: ");

scanf("%d", &num1); printf("Enter

the second number: "); scanf("%d",

&num2);

// Find the maximum using the findMax function int max = findMax(&num1,

&num2); // Print the maximum number printf("The maximum number between

%d and %d is %d\n", num1, num2, max); getch();

5. Write a C program to input and print array elements using


pointer.
.

#include <stdio.h>

#include<conio.h>

// Function to input array elements using pointers

void inputArray(int *arr, int size) { for (int i = 0; i

< size; i++) { printf("Enter element %d: ", i + 1);

scanf("%d", (arr + i));

// Function to print array elements using pointers

void printArray(int *arr, int size) { printf("Array

elements are: ");

MEET PATEL
for (int i = 0; i < size; i++)

{ printf("%d ", *(arr + i));

printf("\n");

int main() {

int arr[10]; int size = sizeof(arr) /

sizeof(arr[0]);

// Input array elements

inputArray(arr, size); //

Print array elements

printArray(arr, size);

getch();

6. Write a C program to copy one array to another using


pointers.
.

#include <stdio.h>

#include<conio.h>

// Function to copy one array to another using pointers void

copyArray(int *source, int *destination, int size) {

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

*(destination + i) = *(source + i);

int main() { int source[10], destination[10];

int size = sizeof(source) /

sizeof(source[0]); // Input elements for the

MEET PATEL
source array printf("Enter 10 elements for

the source array:\n");

for (int i = 0; i < size; i++)

{ printf("Element %d: ", i + 1);

scanf("%d", &source[i]);

// Copy source array to destination array

copyArray(source, destination, size); // Print the

destination array printf("Elements in the

destination array are:\n");

for (int i = 0; i < size; i++)

{ printf("%d ", destination[i]);

printf("\n"); getch();

7. Write a C program to compare two strings using pointers.


.

#include <stdio.h>

#include<conio.h>

// Function to compare two strings using pointers

int compareStrings(char *str1, char *str2)

{ while (*str1 && *str2) { if (*str1 != *str2) {

return 0; // Strings are not equal

str1++;

str2++;

return (*str1 == '\0' && *str2 == '\0'); // True if both strings end simultaneously

MEET PATEL
int main() { char str1[100], str2[100]; // Prompt user for input

printf("Enter the first string: "); gets(str1); // Note: gets() is risky,

prefer fgets() in production code printf("Enter the second string: ");

gets(str2);

// Compare the strings using compareStrings function

if (compareStrings(str1, str2)) { printf("The strings

are equal.\n");

} else { printf("The strings are not

equal.\n");

getch();

8. Write a C program to find reverse of a string using pointers.


.

#include <stdio.h>

#include<conio.h>

// Function to reverse a string using pointers

void reverseString(char *str) { char *start =

str; char *end = str; char temp;

// Move the end pointer to the last character of the string

while (*end != '\0') { end++;

end--; // Move back to the last character (non-null)

// Swap the characters from start and end until the pointers meet in the middle

while (start < end) {

temp = *start;

*start = *end;

*end = temp;

start++; end--;

MEET PATEL
}

int main() { char str[100]; // Prompt user for input

printf("Enter a string: "); gets(str); // Note: gets() is risky, prefer

fgets() in production code

// Reverse the string

reverseString(str); // Print the

reversed string printf("Reversed

string: %s\n", str); getch();

9. Write a C program to sort array using pointers.


.

#include <stdio.h>

#include<conio.h>

// Function to sort the array using pointers

void sortArray(int *arr, int size) { int i, j,

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

(j = i + 1; j < size; j++) { if (*(arr + i) >

*(arr + j)) { // Swap the elements

temp = *(arr + i);

*(arr + i) = *(arr + j);

*(arr + j) = temp;

int main() { int arr[10], i; int size =

sizeof(arr) / sizeof(arr[0]);

// Prompt user to input array elements

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

MEET PATEL
for (i = 0; i < size; i++)

{ printf("Element %d: ", i + 1);

scanf("%d", (arr + i));

// Sort the array

sortArray(arr, size); //

Print the sorted array

printf("Sorted array:\n");

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

{ printf("%d ", *(arr + i));

printf("\n"); getch();

10. Write a C program to concatenate two strings using


pointers.
.

#include <stdio.h>

#include<conio.h>

// Function to concatenate two strings using pointers

void concatenate(char *str1, char *str2) { // Move

to the end of the first string while (*str1 != '\0') {

str1++;

// Copy the second string to the end of the first string

while (*str2 != '\0') { *str1 = *str2; str1++;

str2++;

// Add null terminator at the end

*str1 = '\0';

MEET PATEL
int main() { char str1[100], str2[100]; // Prompt user for input

printf("Enter the first string: "); gets(str1); // Note: gets() is risky,

prefer fgets() in production code printf("Enter the second string:

"); gets(str2);

// Concatenate the strings

concatenate(str1, str2); // Print the

concatenated string printf("Concatenated

string: %s\n", str1); getch();

Extra Practice List:

MEET PATEL

You might also like