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

C Practical Assignment in Word (2)

Uploaded by

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

C Practical Assignment in Word (2)

Uploaded by

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

NAVGUJARAT COLLEGE OF COMPUTER APPLICATION ,

USMANPURA

NAME:-VANSH J SAVADIYA
ROLL NO:-1196
BATCH:-B2
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: ");

scanf("%f", &time);

// Calculate Simple Interest

interest = (principal * rate * time) / 100;

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

VANSH SAVADIYA
int main() {

int num1, num2, num3;

// Prompt user for input

printf("Enter three 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;

VANSH SAVADIYA
// Prompt the user for choice

printf("Temperature Conversion Menu\n");

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

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

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;

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

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

VANSH SAVADIYA
}

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;

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

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

VANSH SAVADIYA
#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();

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;

VANSH SAVADIYA
// 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.


.

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

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

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

VANSH SAVADIYA
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]
*

**

***

****

LEFT ALIGNED :-
#include <stdio.h>

#include<conio.h>

int main() {

int rows = 5, i, j;

VANSH SAVADIYA
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();

CENTER ALIGNED :-
#include <stdio.h>

#include<conio.h>

int main()

VANSH SAVADIYA
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.

#include <stdio.h>

#include<conio.h>

int main() {

int n, i, j;

// Prompt user for input

printf("Enter an integer N: ");

scanf("%d", &n);

VANSH SAVADIYA
// 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()

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

VANSH SAVADIYA
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)

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

VANSH SAVADIYA
// 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]);

printf("\n");

getch();

VANSH SAVADIYA
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)

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

VANSH SAVADIYA
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)

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

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

VANSH SAVADIYA
}

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

// Display the result

printf("Product of the two matrices:\n");

VANSH SAVADIYA
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

VANSH SAVADIYA
// 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 1

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

VANSH SAVADIYA
getch();

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

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

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

VANSH SAVADIYA
char str[100];

// Prompt user for input

printf("Enter a lowercase string: ");

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

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

VANSH SAVADIYA
printf("Enter the number N: ");

scanf("%d", &n);

printf("Enter the position k: ");

scanf("%d", &k);

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

VANSH SAVADIYA
}

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

int main()

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>

VANSH SAVADIYA
// Define structure for state

struct State {

char name[50];

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

VANSH SAVADIYA
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
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++) {

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

printf("Code: ");

scanf("%d", &items[i].code);

printf("Name: ");

scanf("%s", 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 {

VANSH SAVADIYA
int month;

int day;

};

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

VANSH SAVADIYA
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>

#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() {

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

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

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

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

VANSH SAVADIYA
// 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.
.

#include <stdio.h>

#include<conio.h>

// Define the structure for time

struct Time {

int hours;

int minutes;

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

// Calculate the difference

difference = calculateDifference(startTime, endTime);

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

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

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

VANSH SAVADIYA
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].literacyRate) {

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

8 Define a structure employee with member variables having


employee name, basic pay, dearness allowance, house rent,

VANSH SAVADIYA
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++) {

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

temp = employees[i];

VANSH SAVADIYA
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", &employees[i].dearnessAllowance);

printf("House Rent: ");

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

VANSH SAVADIYA
}

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

VANSH SAVADIYA
// 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;

VANSH SAVADIYA
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();

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;

VANSH SAVADIYA
*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 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);

VANSH SAVADIYA
*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).
.

#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') {

VANSH SAVADIYA
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;

VANSH SAVADIYA
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: ");

VANSH SAVADIYA
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 source array

VANSH SAVADIYA
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

VANSH SAVADIYA
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

VANSH SAVADIYA
while (start < end) {

temp = *start;

*start = *end;

*end = temp;

start++;

end--;

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

VANSH SAVADIYA
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");

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

VANSH SAVADIYA
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';

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

VANSH SAVADIYA
Extra Practice List:

1 Demonstrate printing Tables for the range given by user. E.g. start
no : 1,
ending no: 10 Program should print table(s) of 1 to 10 numbers.
ANS
#include<stdio.h>

#include<conio.h>

void printTable(int num) {

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

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

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

printf("\n");

int main() {

int start, end;

// Prompt user for the range

printf("Enter the starting number: ");

scanf("%d", &start);

printf("Enter the ending number: ");

scanf("%d", &end);

// Print multiplication tables for the range

for (int i = start; i <= end; i++) {

printTable(i);

getch();

VANSH SAVADIYA
2. Demonstrate to find sum of N numbers.
ANS
#include <stdio.h>

#include<conio.h>

int main() {

int N, i, sum = 0, num;

// Prompt user for the number of elements

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

scanf("%d", &N);

// Loop to read N numbers and calculate the sum

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

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

scanf("%d", &num);

sum += num;

// Display the result

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

getch();

3. Demonstrate to find sum of the digits entered by the user.


ANS
#include<stdio.h>

#include<conio.h>

int main() {

int num, sum = 0, digit;

// Prompt user for input

printf("Enter an integer: ");

scanf("%d", &num);

// Calculate the sum of the digits

VANSH SAVADIYA
while (num != 0) {

digit = num % 10; // Get the last digit

sum += digit; // Add the digit to the sum

num /= 10; // Remove the last digit from the number

// Display the result

printf("The sum of the digits is: %d\n", sum);

getch();

4. Demonstrate to find the sum of first 100 odd nos. and even nos.
ANS
#include<stdio.h>

#include<conio.h>

int main() {

int sumOdd = 0;

int sumEven = 0;

int i;

// Calculate the sum of the first 100 odd numbers

for (i = 1; i <= 200; i += 2) {

sumOdd += i;

// Calculate the sum of the first 100 even numbers

for (i = 2; i <= 200; i += 2) {

sumEven += i;

// Display the results

printf("Sum of the first 100 odd numbers: %d\n", sumOdd);

printf("Sum of the first 100 even numbers: %d\n", sumEven);

getch();

VANSH SAVADIYA
}

5. Demonstrate to check whether the given number is Armstrong


or not.
ANS
#include<stdio.h>

#include<math.h>

#include<conio.h>

// Function to check if a number is Armstrong

int isArmstrong(int num) {

int originalNum, remainder, n = 0, result = 0;

originalNum = num;

// Count the number of digits

while (originalNum != 0) {

originalNum /= 10;

++n;

originalNum = num;

// Calculate the sum of the nth power of its digits

while (originalNum != 0) {

remainder = originalNum % 10;

result += pow(remainder, n);

originalNum /= 10;

// Check if the result equals the original number

return (result == num);

int main() {

int num;

// Prompt user for input

VANSH SAVADIYA
printf("Enter an integer: ");

scanf("%d", &num);

// Check if the number is an Armstrong number

if (isArmstrong(num)) {

printf("%d is an Armstrong number.\n", num);

} else {

printf("%d is not an Armstrong number.\n", num);

getch();

6. Demonstrate to print all the prime numbers ranging from 50 to


100.
ANS
#include<stdio.h>

#include<conio.h>

// Function to check if a number is prime

int isPrime(int num) {

if (num <= 1) {

return 0;

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

if (num % i == 0) {

return 0;

return 1;

int main() {

printf("Prime numbers between 50 and 100 are:\n");

VANSH SAVADIYA
for (int i = 50; i <= 100; i++) {

if (isPrime(i)) {

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

getch();

7. Demonstrate to find x1+x2+x3+x4+ ….+ xn.


ANS
#include<stdio.h>

#include<conio.h>

int main() {

int n, i;

float sum = 0.0, number;

// Prompt user for the number of elements

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

scanf("%d", &n);

// Loop to read n numbers and calculate the sum

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

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

printf("x%d: ", i);

scanf("%f", &number);

sum += number;

// Display the result

printf("The sum of the numbers is: %.2f\n", sum);

getch();

VANSH SAVADIYA
8. Demonstrate to find 1+1/2+1/3+1/4+ …+1/n.
ANS
#include<stdio.h>

#include<conio.h>

int main() {

int n, i;

float sum = 0.0;

// Prompt user for input

printf("Enter the value of n: ");

scanf("%d", &n);

// Calculate the sum of the series

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

sum += 1.0 / i;

// Display the result

printf("The sum of the series 1 + 1/2 + 1/3 + ... + 1/%d is: %.2f\n", n, sum);

getch();

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


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

VANSH SAVADIYA
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();

10. Print the following Pattern:


A
BC
DEF
G H I J.
ANS
#include<stdio.h>

#include<conio.h>

int main() {

char ch = 'A';

int n = 4; // Number of rows

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

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

printf("%c", ch);

ch++;

printf("\n");

VANSH SAVADIYA
}

getch();

11. Print the following pattern:


A
ABA
ABCBA
ABCDCBA.
ANS
#include<stdio.h>

#include<conio.h>

int main() {

int n = 4; // Number of rows

int i, j;

char ch;

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

ch = 'A';

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

printf("%c", ch);

ch++;

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

ch--;

printf("%c", ch);

printf("\n");

getch();

VANSH SAVADIYA
}

12. Print the following pattern:


1
01
010
1 0 1 0.
ANS
#include<stdio.h>

#include<conio.h>

int main() {

int n = 4; // Number of rows

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

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

if ((i + j) % 2 == 0) {

printf("1 ");

} else {

printf("0 ");

printf("\n");

getch();

VANSH SAVADIYA
13. Display this kind of output on screen.
C
CP
CPR
..
CPROGRAMING
.
.
CPR
CP
C.
ANS
#include<stdio.h>

#include<conio.h>

int main() {

// Print the required pattern

printf("CCPCPR\n");

printf(". .CPROGRAMING..\n");

printf("CPRCPC\n");

getch();

14. Demonstrate to search an element from the array.


ANS
#include<stdio.h>

#include<conio.h>

// Function to search for an element in the array

VANSH SAVADIYA
int searchElement(int *arr, int size, int element) {

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

if (*(arr + i) == element) {

return i; // Element found, return its index

return -1; // Element not found, return -1

int main() {

int arr[10], size = 10, element, index;

// Prompt user to input array elements

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

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

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

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

// Prompt user to enter the element to search for

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

scanf("%d", &element);

// Search for the element in the array

index = searchElement(arr, size, element);

// Display the result

if (index != -1) {

printf("Element %d found at index %d.\n", element, index);

} else {

printf("Element %d not found in the array.\n", element);

getch();

VANSH SAVADIYA
15. Demonstrate to find sum, average of two numbers passed to
user defined
functions called sum and average.
ANS
#include<stdio.h>

#include<conio.h>

// Function to calculate the sum of two numbers

int sum(int a, int b) {

return a + b;

// Function to calculate the average of two numbers

float average(int a, int b) {

return (a + b) / 2.0;

int main() {

int num1, num2;

int total;

float avg;

// Prompt user for input

printf("Enter the first number: ");

scanf("%d", &num1);

printf("Enter the second number: ");

scanf("%d", &num2);

// Calculate sum and average

total = sum(num1, num2);

= avg = average(num1, num2);

// Display the results

printf("Sum: %d\n", total);

printf("Average: %.2f\n", avg);

getch();

VANSH SAVADIYA
}

16. Demonstrate to print Fibonacci series using recursive UDF.


ANS
#include<stdio.h>

#include<conio.h>

// Function to calculate Fibonacci number using recursion

int fibonacci(int n) {

if (n <= 1) {

return n;

} else {

return fibonacci(n - 1) + fibonacci(n - 2);

int main() {

int n, i;

// Prompt user for input

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

scanf("%d", &n);

printf("Fibonacci series up to %d terms:\n", n);

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

printf("%d ", fibonacci(i));

printf("\n");

getch();

17. Demonstrate to find length of the given string (without


including string.h).
ANS

VANSH SAVADIYA
#include <stdio.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();

18. Accept two strings from the user and print the message that
the strings are same
or not.
ANS
#include<stdio.h>

#include<string.h>

#include<conio.h>

// Function to compare two strings

int compareStrings(char *str1, char *str2) {

VANSH SAVADIYA
while (*str1 && *str2) {

if (*str1 != *str2) {

return 0; // Strings are not the same

str1++;

str2++;

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

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 the same.\n");

} else {

printf("The strings are not the same.\n");

getch();

VANSH SAVADIYA

You might also like