Problem Statement 1:
You are tasked with creating a simple program in C that takes two numbers as input from the user and allows them to perform basic arithmetic operations such as addition, subtraction, multiplication, and division on these numbers. The program should use if-else statements and arithmetic operators to carry out the chosen operation. It should also handle the case of division by zero and provide appropriate error messages for invalid operations.
Code:
#include <stdio.h>
int main()
{
double num1, num2;
char operation;
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
printf("Enter an operation (+, -, *, /): ");
scanf(" %c", &operation);
if (operation == '+')
{
printf("%.2lf + %.2lf = %.2lf\n", num1, num2, num1 + num2);
}
else if (operation == '-')
{
printf("%.2lf - %.2lf = %.2lf\n", num1, num2, num1 - num2);
}
else if (operation == '*')
{
printf("%.2lf * %.2lf = %.2lf\n", num1, num2, num1 * num2);
}
else if (operation == '/')
{
if (num2 != 0.0)
{
printf("%.2lf / %.2lf = %.2lf\n", num1, num2, num1 / num2);
}
else
{
printf("Cannot divide by zero.\n");
}
}
else
{
printf("Invalid operation.\n");
}
return 0;
}
Explanation:
The code starts by including the standard input/output library (<stdio.h>).
In the main() function, we declare the following variables:
double num1, num2; to store the two numbers entered by the user.
char operation; to store the selected arithmetic operation.
We prompt the user to enter two numbers using printf, and then we use scanf to read and store these numbers in num1 and num2.
Next, we ask the user to choose an operation (+, -, *, /) using printf and read their choice into the operation variable using scanf. Note that there is a space before %c in scanf to consume any leading whitespace characters or newline characters left in the input buffer.
We use a series of if-else statements to check the value of operation and perform the corresponding arithmetic operation:
If operation is +, we perform addition and print the result.
If operation is -, we perform subtraction and print the result.
If operation is *, we perform multiplication and print the result.
If operation is /, we perform division, but we also check if num2 is not zero to avoid division by zero. If it's not zero, we print the result; otherwise, we print an error message.
If none of the recognized operations is chosen, we print "Invalid operation."
The program returns 0 at the end of the main() function, indicating successful execution.
Problem Statement 2:
You are tasked with creating a program in C that converts temperatures between Fahrenheit and Celsius. The program should allow the user to choose the conversion direction using if-else statements and use arithmetic operators for the conversions. It should handle conversions from Celsius to Fahrenheit and from Fahrenheit to Celsius based on the unit provided by the user (C for Celsius, F for Fahrenheit).
Code:
#include <stdio.h>
int main()
{
double temperature;
char unit;
printf("Enter temperature followed by its unit (C or F): ");
scanf("%lf %c", &temperature, &unit);
if (unit == 'C' || unit == 'c')
{
double fahrenheit = (temperature * 9 / 5) + 32;
printf("%.2lf°C is equal to %.2lf°F\n", temperature, fahrenheit);
}
else if (unit == 'F' || unit == 'f')
{
double celsius = (temperature - 32) * 5 / 9;
printf("%.2lf°F is equal to %.2lf°C\n", temperature, celsius);
}
else
{
printf("Invalid unit. Please enter C for Celsius or F for Fahrenheit.\n");
}
return 0;
}
Explanation:
The code begins with the inclusion of the standard input/output library (<stdio.h>).
In the main() function, two variables are declared:
double temperature; to store the temperature value entered by the user.
char unit; to store the unit of the temperature (C for Celsius, F for Fahrenheit).
The program prompts the user to enter the temperature followed by its unit, such as "25 C" or "78 F." It uses printf to display the prompt and scanf to read the input values, storing the temperature in temperature and the unit in unit.
The program uses if-else statements to determine the conversion direction based on the value of unit:
If unit is 'C' or 'c', it converts from Celsius to Fahrenheit using the formula (Celsius * 9/5) + 32 and prints the result in both Celsius and Fahrenheit.
If unit is 'F' or 'f', it converts from Fahrenheit to Celsius using the formula (Fahrenheit - 32) * 5/9 and prints the result in both Fahrenheit and Celsius.
If unit is neither 'C'/'c' nor 'F'/'f', it prints an error message indicating that the unit is invalid.
The program returns 0 at the end of the main() function, indicating successful execution.
Problem Statement 3:
You are tasked with creating a program in C that calculates the factorial of a non-negative integer entered by the user. The program should use a loop to perform the calculation and display the result. It should handle the case of a negative input by informing the user that the factorial of a negative number doesn't exist.
Code:
#include <stdio.h>
int main()
{
int n, i;
unsigned long long factorial = 1;
printf("Enter a non-negative integer: ");
scanf("%d", &n);
if (n < 0)
{
printf("Factorial of a negative number doesn't exist.\n");
}
else
{
for (i = 1; i <= n; ++i)
{
factorial *= i;
}
printf("Factorial of %d = %llu\n", n, factorial);
}
return 0;
}
Explanation:
The code begins with the inclusion of the standard input/output library (<stdio.h>).
In the main() function, the following variables are declared:
int n to store the non-negative integer entered by the user.
int i to use as a loop counter.
unsigned long long factorial to store the factorial result. unsigned long long is used to handle larger numbers since factorials can become very large.
The program prompts the user to enter a non-negative integer using printf and reads the input into the variable n using scanf.
The program checks if the entered value of n is negative using an if statement. If n is negative, it prints an error message indicating that the factorial of a negative number doesn't exist.
If n is non-negative, the program proceeds to calculate the factorial using a for loop:
After the loop completes, the program prints the result, displaying the value of n and the calculated factorial.
The program returns 0 at the end of the main() function, indicating successful execution.
Problem Statement 4:
You are tasked with creating a program in C that calculates the result of raising a number to a certain power entered by the user. The program should use loops and arithmetic operators to perform the calculation. It should also handle negative exponents appropriately.
Code:
#include <stdio.h>
int main()
{
double base, result = 1.0;
int exponent, i;
printf("Enter a base number: ");
scanf("%lf", &base);
printf("Enter an exponent (integer): ");
scanf("%d", &exponent);
int originalExponent = exponent;
if (exponent < 0)
{
base = 1 / base;
exponent = -exponent;
}
for (i = 1; i <= exponent; ++i)
{
result *= base;
}
printf("%.2lf raised to the power of %d is %.2lf\n", base, originalExponent, result);
return 0;
}
Explanation:
The code begins with the inclusion of the standard input/output library (<stdio.h>).
In the main() function, the following variables are declared:
double base to store the base number entered by the user.
double result initialized to 1.0 to store the result of the calculation.
int exponent to store the integer exponent entered by the user.
int i to use as a loop counter.
The program prompts the user to enter a base number and an exponent (integer) using printf and reads these values into base and exponent using scanf.
To handle negative exponents, the program checks if exponent is less than 0. If it is, it calculates the reciprocal of the base and makes exponent positive.
The program then proceeds to calculate the power using a for loop:
After the loop completes, the program prints the result, displaying the value of base, the original value of exponent, and the calculated result.
The program returns 0 at the end of the main() function, indicating successful execution.
Problem Statement 5:
You are tasked with creating a program in C that checks whether a given year entered by the user is a leap year or not. The program should use if-else statements and conditions to determine if the year meets the leap year criteria.
Code:
#include <stdio.h>
int main()
{
int year;
printf("Enter a year: ");
scanf("%d", &year);
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
{
printf("%d is a leap year.\n", year);
}
else
{
printf("%d is not a leap year.\n", year);
}
return 0;
}
Explanation:
The code starts with the inclusion of the standard input/output library (<stdio.h>).
In the main() function, one variable is declared:
int year to store the year entered by the user.
The program prompts the user to enter a year using printf and reads the input into the variable year using scanf.
The program checks if the year is a leap year using an if-else statement and a series of conditions:
- If
year is divisible by 4 (year % 4 == 0) and not divisible by 100 (year % 100 != 0), or if it is divisible by 400 (year % 400 == 0), then it is a leap year.
If the above conditions are met, the program prints that the year is a leap year; otherwise, it prints that the year is not a leap year.
The program returns 0 at the end of the main() function, indicating successful execution.
Problem Statement 6:
You are tasked with creating a program in C that calculates the area of a circle. The radius of the circle should be entered by the user. The formula to calculate the area is: Area = π * radius * radius.
Code:
#include <stdio.h>
#define PI 3.14159
int main()
{
double radius, area;
printf("Enter the radius of the circle: ");
scanf("%lf", &radius);
area = PI * radius * radius;
printf("The area of the circle with radius %.2lf is %.2lf\n", radius, area);
return 0;
}
Explanation:
The code starts by including the standard input/output library (<stdio.h>).
It defines a constant PI with the value 3.14159 using a preprocessor directive (#define). This constant represents the mathematical value of π (pi).
In the main() function, two variables are declared:
The program prompts the user to enter the radius of the circle using printf and reads the input into the variable radius using scanf.
The program calculates the area of the circle using the formula Area = PI * radius * radius and stores the result in the variable area.
Finally, the program displays the result to the user using printf, showing the value of the radius and the calculated area with two decimal places.
The program returns 0 at the end of the main() function, indicating successful execution.
Problem Statement 7:
You are tasked with creating a program in C that swaps the values of two integer variables without using a third variable. The goal is to exchange the values of a and b using arithmetic operations, addition, and subtraction, in order to achieve the swap.
Code:
#include <stdio.h>
int main()
{
int a, b;
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
printf("Original values: a = %d, b = %d\n", a, b);
a = a + b;
b = a - b;
a = a - b;
printf("Swapped values: a = %d, b = %d\n", a, b);
return 0;
}
Explanation:
The code begins with the inclusion of the standard input/output library (<stdio.h>).
In the main() function, two integer variables, a and b, are declared. These variables will store the values entered by the user.
The program prompts the user to enter two integers using printf and reads these input values into a and b using scanf.
The original values of a and b are displayed to the user using printf.
To swap the values of a and b without using a third variable, we employ a sequence of arithmetic operations:
a = a + b;: In this step, we add the values of a and b and store the result in a. Now, a holds the sum of the original values of a and b.
b = a - b;: Next, we subtract the original value of b (before the addition in the previous step) from the new value of a. This operation effectively assigns the original value of a to b.
a = a - b;: Finally, we subtract the original value of b (now in a) from the new value of a (now in b). This operation assigns the original value of b to a.
After the swap, the program displays the swapped values of a and b using printf.
The program returns 0 at the end of the main() function, indicating successful execution.
Problem Statement 8:
You are tasked with creating a program in C that reverses the digits of a number entered by the user. The program should take an integer as input, reverse its digits, and display the reversed number.
Code:
#include <stdio.h>
int main()
{
int num, reversedNum = 0;
printf("Enter an integer: ");
scanf("%d", &num);
while (num != 0)
{
int digit = num % 10;
reversedNum = reversedNum * 10 + digit;
num /= 10;
}
printf("Reversed number: %d\n", reversedNum);
return 0;
}
Explanation:
The code begins with the inclusion of the standard input/output library (<stdio.h>).
In the main() function, two integer variables are declared:
The program prompts the user to enter an integer using printf and reads the input into the variable num using scanf.
To reverse the digits of the number, the program uses a while loop that continues until num becomes 0. Within the loop:
int digit = num % 10;: This line extracts the last digit of num and stores it in the variable digit.
reversedNum = reversedNum * 10 + digit;: It appends the extracted digit to the reversedNum by multiplying the existing reversed number by 10 (shifting digits to the left) and then adding the digit to the result.
num /= 10;: This line removes the last digit from num by integer division, effectively shifting digits to the right.
After the loop completes, the program displays the reversed number using printf.
The program returns 0 at the end of the main() function, indicating successful execution.
Problem Statement 9:
You are tasked with creating a program in C that calculates the sum of the first N natural numbers, where N is entered by the user. The program should ensure that N is a positive integer and then calculate and display the sum.
Code:
#include <stdio.h>
int main()
{
int N, sum = 0;
printf("Enter a positive integer N: ");
scanf("%d", &N);
if (N <= 0)
{
printf("Please enter a positive integer.\n");
}
else
{
for (int i = 1; i <= N; i++)
{
sum += i;
}
printf("Sum of the first %d natural numbers is: %d\n", N, sum);
}
return 0;
}
Explanation:
The code begins with the inclusion of the standard input/output library (<stdio.h>).
In the main() function, two integer variables are declared:
The program prompts the user to enter a positive integer N using printf and reads the input into the variable N using scanf.
It checks if N is positive by using an if statement. If N is not positive (less than or equal to 0), it prints an error message asking the user to enter a positive integer.
If N is positive, the program proceeds to calculate the sum of the first N natural numbers using a for loop:
- The loop runs from
1 to N, and in each iteration, it adds the value of i to the sum variable, where i represents the current natural number.
After the loop completes, the program displays the result by printing the sum of the first N natural numbers along with the value of N.
The program returns 0 at the end of the main() function, indicating successful execution.
Problem Statement 10:
You are tasked with creating a program in C that checks whether a number is prime or not. The program should take a positive integer as input, determine if it is prime, and display the result.
Code:
#include <stdio.h>
int main()
{
int num, i, isPrime = 1;
printf("Enter a positive integer: ");
scanf("%d", &num);
if (num <= 1)
{
isPrime = 0;
}
else
{
for (i = 2; i <= num / 2; i++)
{
if (num % i == 0)
{
isPrime = 0;
break;
}
}
}
if (isPrime)
{
printf("%d is a prime number.\n", num);
}
else
{
printf("%d is not a prime number.\n", num);
}
return 0;
}
Explanation:
The code begins with the inclusion of the standard input/output library (<stdio.h>).
In the main() function, three integer variables are declared:
int num to store the positive integer entered by the user.
int i for use in the loop to check for factors.
int isPrime initialized to 1 (true) to indicate that the number is assumed to be prime initially.
The program prompts the user to enter a positive integer using printf and reads the input into the variable num using scanf.
It checks if the entered number is less than or equal to 1. If num is less than or equal to 1, it sets isPrime to 0 (false), indicating that the number is not prime.
If num is greater than 1, the program proceeds to check for factors other than 1 and the number itself in the range from 2 to num / 2. It does this using a for loop:
- In each iteration, it checks if
num is divisible by i (i.e., num % i == 0). If it is, it sets isPrime to 0 (false) and breaks out of the loop.
After the loop completes, the program checks the value of isPrime to determine if the number is prime or not. If isPrime is 1, it prints that the number is prime; otherwise, it prints that the number is not prime.
The program returns 0 at the end of the main() function, indicating successful execution.
Problem Statement 11:
You are tasked with creating a program in C that finds the greatest common divisor (GCD) of two numbers entered by the user. The program should take two integers as input, calculate their GCD using the Euclidean algorithm, and display the result.
Code:
#include <stdio.h>
int main()
{
int num1, num2, gcd, temp, remainder;
printf("Enter two integers: ");
scanf("%d %d", &num1, &num2);
if (num2 > num1)
{
temp = num1;
num1 = num2;
num2 = temp;
}
while (num2 != 0)
{
remainder = num1 % num2;
num1 = num2;
num2 = remainder;
}
gcd = num1;
printf("GCD of the entered numbers is: %d\n", gcd);
return 0;
}
Explanation:
The code begins with the inclusion of the standard input/output library (<stdio.h>).
In the main() function, five integer variables are declared:
int num1 and int num2 to store the two integers entered by the user.
int gcd to store the GCD of the two numbers.
int temp to temporarily store the value of num1 during swapping if needed.
int remainder to store the remainder during the Euclidean algorithm.
The program prompts the user to enter two integers using printf and reads these inputs into num1 and num2 using scanf.
To ensure that num1 holds the larger number and num2 holds the smaller number, the program checks if num2 is greater than num1. If it is, a temporary variable temp is used to swap the values of num1 and num2.
The Euclidean algorithm is used to find the GCD of the two numbers in a while loop:
The loop continues as long as num2 is not equal to 0.
In each iteration, the program calculates the remainder of num1 divided by num2 and stores it in remainder.
num2 is updated to remainder, and num1 retains its original value.
This process continues until num2 becomes 0, at which point num1 holds the GCD.
The GCD is stored in the variable gcd.
The program displays the calculated GCD using printf.
The program returns 0 at the end of the main() function, indicating successful execution.
Problem Statement 12:
You are tasked with creating a program in C that reads an integer and prints the sum of its digits. The program should take an integer as input, calculate the sum of its digits, and display the result.
Code:
#include <stdio.h>
int main()
{
int num, sum = 0;
printf("Enter an integer: ");
scanf("%d", &num);
while (num != 0)
{
sum += num % 10;
num /= 10;
}
printf("Sum of the digits is: %d\n", sum);
return 0;
}
Explanation:
The code begins with the inclusion of the standard input/output library (<stdio.h>).
In the main() function, two integer variables are declared:
The program prompts the user to enter an integer using printf and reads the input into the variable num using scanf.
To sum the digits of the number, the program uses a while loop that continues until num becomes 0. Within the loop:
sum += num % 10;: In each iteration, it extracts the last digit of num using the modulo operator (num % 10) and adds it to the sum variable.
num /= 10;: It then removes the last digit from num by integer division, effectively shifting digits to the right.
After the loop completes, the program displays the sum of the digits using printf.
The program returns 0 at the end of the main() function, indicating successful execution.
Problem Statement 13:
You are tasked with creating a program in C that prints the first N numbers of the Fibonacci sequence. The program should take an integer N as input, calculate and display the first N terms of the Fibonacci sequence.
Code:
#include <stdio.h>
int main()
{
int n, first = 0, second = 1, next, i;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("First %d terms of Fibonacci sequence are: ", n);
for (i = 0; i < n; i++)
{
if (i <= 1)
next = i;
else
{
next = first + second;
first = second;
second = next;
}
printf("%d ", next);
}
printf("\n");
return 0;
}
Explanation:
The code begins with the inclusion of the standard input/output library (<stdio.h>).
In the main() function, several integer variables are declared:
int n to store the number of terms in the Fibonacci sequence requested by the user.
int first initialized to 0, representing the first number in the sequence.
int second initialized to 1, representing the second number in the sequence.
int next to store the next number in the sequence.
int i to control the loop counter.
The program prompts the user to enter the number of terms (n) they want to generate in the Fibonacci sequence using printf, and reads the input into the variable n using scanf.
It initializes the first and second variables with the values 0 and 1 respectively, which are the first two terms of the Fibonacci sequence.
The program enters a for loop that iterates from 0 to n-1, printing the first n terms of the Fibonacci sequence. Inside the loop:
For the first two terms (when i is 0 or 1), it sets next to i since the Fibonacci sequence starts with 0 and 1.
For subsequent terms, it calculates the next Fibonacci number by adding first and second and stores it in next.
It then updates first with the value of second, effectively shifting the values for the next iteration.
It also updates second with the value of next to prepare for the next iteration.
Finally, it prints the current value of next.
After printing all n terms, the program prints a newline character to separate the output.
The program returns 0 at the end of the main() function, indicating successful execution.
Problem Statement 14:
You are tasked with creating a program in C that checks whether a number is a palindrome or not. A palindrome number is one that remains the same when its digits are reversed. The program should take an integer as input, reverse its digits, and determine if it is a palindrome or not.
Code:
#include <stdio.h>
int main()
{
int num, originalNum, reversedNum = 0, remainder;
printf("Enter an integer: ");
scanf("%d", &num);
originalNum = num;
while (num != 0)
{
remainder = num % 10;
reversedNum = reversedNum * 10 + remainder;
num /= 10;
}
if (originalNum == reversedNum)
{
printf("%d is a palindrome.\n", originalNum);
}
else
{
printf("%d is not a palindrome.\n", originalNum);
}
return 0;
}
Explanation:
The code begins with the inclusion of the standard input/output library (<stdio.h>).
In the main() function, four integer variables are declared:
int num to store the integer entered by the user.
int originalNum to store the original number before reversal.
int reversedNum initialized to 0 to store the reversed number.
int remainder to store the remainder when extracting digits.
The program prompts the user to enter an integer using printf and reads the input into the variable num using scanf.
It stores the original value of num in the originalNum variable to compare it with the reversed number later.
To reverse the digits of the number, the program uses a while loop that continues until num becomes 0. Inside the loop:
remainder = num % 10;: In each iteration, it extracts the last digit of num using the modulo operator (num % 10) and stores it in the remainder variable.
reversedNum = reversedNum * 10 + remainder;: It then adds the extracted digit to the reversedNum, effectively reversing the digits.
num /= 10;: It removes the last digit from num by integer division, effectively shifting digits to the right.
After the loop completes, the program checks if the original number (originalNum) is equal to the reversed number (reversedNum) to determine if it is a palindrome.
Depending on the result of the comparison, the program prints whether the number is a palindrome or not using printf.
The program returns 0 at the end of the main() function, indicating successful execution.
Problem Statement 15:
You are tasked with creating a program in C that converts a decimal number (entered as an integer) to its binary equivalent. The program should take a decimal integer as input, perform the conversion, and display the binary equivalent.
Code:
#include <stdio.h>
int main()
{
int decimal, binary = 0, base = 1, remainder, originalDecimal;
printf("Enter a decimal number: ");
scanf("%d", &decimal);
originalDecimal = decimal;
while (decimal > 0)
{
remainder = decimal % 2;
binary = binary + remainder * base;
decimal = decimal / 2;
base = base * 10;
}
printf("Binary equivalent of %d is %d\n", originalDecimal, binary);
return 0;
}
Explanation:
The code begins with the inclusion of the standard input/output library (<stdio.h>).
In the main() function, five integer variables are declared:
int decimal to store the decimal number entered by the user.
int binary initialized to 0 to store the binary equivalent.
int base initialized to 1 to keep track of the positional value during binary conversion.
int remainder to store the remainder when dividing by 2.
int originalDecimal to store the original decimal number before conversion.
The program prompts the user to enter a decimal number using printf and reads the input into the variable decimal using scanf.
It stores the original value of decimal in the originalDecimal variable to display it later in the output.
To convert the decimal number to its binary equivalent, the program uses a while loop that continues as long as decimal is greater than 0. Inside the loop:
remainder = decimal % 2;: In each iteration, it calculates the remainder when decimal is divided by 2 and stores it in the remainder variable. This remainder will be a binary digit (either 0 or 1).
binary = binary + remainder * base;: It updates the binary variable by adding the calculated binary digit (remainder) multiplied by the current positional value (base). This effectively builds the binary number.
decimal = decimal / 2;: It updates the decimal by performing integer division by 2, effectively shifting digits to the right.
base = base * 10;: It updates the base by multiplying it by 10 to move to the next positional value.
After the loop completes, the program has constructed the binary equivalent in the binary variable.
The program displays the binary equivalent along with the original decimal number using printf.
The program returns 0 at the end of the main() function, indicating successful execution.
Problem Statement 16:
You are tasked with creating a program in C that finds the largest digit in a given integer. The program should take an integer as input, find the largest digit in it, and display the result.
Code:
#include <stdio.h>
int main()
{
int num, maxDigit = 0, digit;
printf("Enter an integer: ");
scanf("%d", &num);
if (num < 0)
{
num = -num;
}
while (num > 0)
{
digit = num % 10;
if (digit > maxDigit)
{
maxDigit = digit;
}
num /= 10;
}
printf("The largest digit is: %d\n", maxDigit);
return 0;
}
Explanation:
The code begins with the inclusion of the standard input/output library (<stdio.h>).
In the main() function, three integer variables are declared:
int num to store the integer entered by the user.
int maxDigit initialized to 0 to store the largest digit found.
int digit to temporarily store each digit during processing.
The program prompts the user to enter an integer using printf and reads the input into the variable num using scanf.
It checks if the entered number is negative (less than 0) and if so, makes it positive by applying the unary - operator. This ensures that the program finds the largest digit regardless of the sign of the input.
To find the largest digit in the number, the program uses a while loop that continues as long as num is greater than 0. Inside the loop:
digit = num % 10;: In each iteration, it calculates the last digit of num using the modulo operator (num % 10) and stores it in the digit variable.
It then compares digit with maxDigit to check if the current digit is larger. If it is, it updates maxDigit to the value of digit.
num /= 10;: It removes the last digit from num by performing integer division by 10, effectively shifting digits to the right.
After the loop completes, the program has found the largest digit in the number, stored in the maxDigit variable.
The program displays the largest digit using printf.
The program returns 0 at the end of the main() function, indicating successful execution.
Problem Statement 17:
You are tasked with creating a program in C that checks if a number is an Armstrong number or not. An Armstrong number, also known as a narcissistic number, is a three-digit integer such that the sum of the cubes of its digits is equal to the number itself. The program should take a three-digit integer as input, check if it is an Armstrong number, and display the result.
Code:
#include <stdio.h>
int main()
{
int num, originalNum, remainder, result = 0;
printf("Enter a three-digit integer: ");
scanf("%d", &num);
originalNum = num;
while (originalNum != 0)
{
remainder = originalNum % 10;
result += remainder * remainder * remainder;
originalNum /= 10;
}
if (result == num)
{
printf("%d is an Armstrong number.\n", num);
}
else
{
printf("%d is not an Armstrong number.\n", num);
}
return 0;
}
Explanation:
The code begins with the inclusion of the standard input/output library (<stdio.h>).
In the main() function, four integer variables are declared:
int num to store the three-digit integer entered by the user.
int originalNum to store the original number before processing.
int remainder to temporarily store the remainder when extracting digits.
int result initialized to 0 to store the sum of the cubes of the digits.
The program prompts the user to enter a three-digit integer using printf and reads the input into the variable num using scanf.
It stores the original value of num in the originalNum variable to check if it is an Armstrong number later.
To check if the number is an Armstrong number, the program uses a while loop that continues as long as originalNum is not equal to 0. Inside the loop:
remainder = originalNum % 10;: In each iteration, it calculates the last digit of originalNum using the modulo operator (originalNum % 10) and stores it in the remainder variable.
result += remainder * remainder * remainder;: It adds the cube of the digit (remainder) to the result, effectively calculating the sum of the cubes of its digits.
originalNum /= 10;: It removes the last digit from originalNum by performing integer division by 10, effectively shifting digits to the right.
After the loop completes, the program has calculated the sum of the cubes of the digits in the variable result.
The program checks if result is equal to the original number num. If they are equal, it means that the number is an Armstrong number, and it prints a corresponding message. Otherwise, it prints a message indicating that it is not an Armstrong number.
The program returns 0 at the end of the main() function, indicating successful execution.
Problem Statement 18:
You are tasked with creating a program in C that adds the digits of a number until the sum becomes a single digit. The program should take an integer as input, repeatedly sum its digits, and continue until the sum is a single digit. Then, it should display the final single-digit sum.
Code:
#include <stdio.h>
int main()
{
int num, sum = 0, temp;
printf("Enter an integer: ");
scanf("%d", &num);
while (num > 9)
{
sum = 0;
temp = num;
while (temp != 0)
{
sum += temp % 10;
temp /= 10;
}
num = sum;
}
printf("Single digit sum: %d\n", num);
return 0;
}
Explanation:
The code begins with the inclusion of the standard input/output library (<stdio.h>).
In the main() function, three integer variables are declared:
int num to store the integer entered by the user.
int sum initialized to 0 to store the sum of the digits.
int temp to temporarily store the number during processing.
The program prompts the user to enter an integer using printf and reads the input into the variable num using scanf.
The program enters a while loop that continues as long as num is greater than 9, which means it has more than one digit. The purpose of this loop is to continue adding the digits until a single digit result is achieved.
Inside the loop:
sum = 0;: At the beginning of each iteration, it resets the sum to 0 to calculate the sum of the digits for the current value of num.
temp = num;: It stores the current value of num in the temp variable to work with a temporary copy of the number.
It enters a nested while loop to sum the digits of temp until there are no more digits left:
sum += temp % 10;: In each iteration, it calculates the last digit of temp using the modulo operator (temp % 10) and adds it to the sum.
temp /= 10;: It removes the last digit from temp by performing integer division by 10, effectively shifting digits to the right.
After the inner loop completes, sum contains the sum of the digits of the original num.
It updates the value of num with the sum calculated in the inner loop. This is done to repeat the process with the new num value, which may still have multiple digits.
The outer loop continues to iterate until num becomes a single digit.
Once num becomes a single digit (i.e., it is less than or equal to 9), the program exits the loop.
It displays the single-digit sum using printf.
The program returns 0 at the end of the main() function, indicating successful execution.
Problem Statement 19:
You are tasked with creating a C program that includes a function named calculateCircleArea to calculate the area of a circle based on the radius. The program's main function should prompt the user to enter the radius, call the calculateCircleArea function to compute the area, and then display the calculated area.
Code:
#include <stdio.h>
#define PI 3.14159265359
double calculateCircleArea(double radius)
{
double area;
area = PI * radius * radius;
return area;
}
int main()
{
double radius, area;
printf("Enter the radius of the circle: ");
scanf("%lf", &radius);
area = calculateCircleArea(radius);
printf("The area of the circle with radius %.2lf is %.2lf\n", radius, area);
return 0;
}
Explanation:
The code starts with the inclusion of the standard input/output library (<stdio.h>).
It defines a constant PI with the value of pi (approximately 3.14159265359) to be used in the area calculation formula.
The program defines a function named calculateCircleArea that takes a double parameter radius and returns a double value, which is the calculated area of the circle.
Inside the calculateCircleArea function:
It declares a local double variable area to store the computed area.
The area is calculated using the formula: area = PI * radius * radius.
The calculated area is then returned as the function's result.
In the main function:
Two double variables are declared: radius to store the radius entered by the user and area to store the calculated area.
The program prompts the user to enter the radius of the circle using printf.
The user's input is read and stored in the radius variable using scanf.
The program calls the calculateCircleArea function and passes the radius as an argument. The returned value (the area) is stored in the area variable.
Finally, the program displays the calculated area using printf, rounding it to two decimal places for a more readable result.
The program returns 0 at the end of the main function, indicating successful execution.
Problem Statement 20:
You are tasked with creating a C program that includes a function named findGreatest. This function should take three integer arguments and return the greatest among them. The program's main function should prompt the user to enter three numbers, call the findGreatest function to determine the greatest number, and then display the greatest number.
Code:
#include <stdio.h>
int findGreatest(int num1, int num2, int num3)
{
int greatest = num1;
if (num2 > greatest)
{
greatest = num2;
}
if (num3 > greatest)
{
greatest = num3;
}
return greatest;
}
int main()
{
int num1, num2, num3, greatest;
printf("Enter three numbers: ");
scanf("%d %d %d", &num1, &num2, &num3);
greatest = findGreatest(num1, num2, num3);
printf("The greatest number is: %d\n", greatest);
return 0;
}
Explanation:
The code begins with the inclusion of the standard input/output library (<stdio.h>).
It defines a function named findGreatest that takes three integer parameters (num1, num2, and num3) and returns an integer value, which is the greatest among the three numbers.
Inside the findGreatest function:
It declares a local integer variable greatest and initializes it with the value of num1. This variable will store the greatest number among the three.
It compares num2 with greatest and updates greatest if num2 is greater.
It also compares num3 with greatest and updates greatest if num3 is greater.
Finally, it returns the value of greatest.
In the main function:
Four integer variables are declared: num1, num2, num3, and greatest.
The program prompts the user to enter three numbers using printf.
The user's input is read and stored in the variables num1, num2, and num3 using scanf.
The program calls the findGreatest function, passing num1, num2, and num3 as arguments. The returned value (the greatest number) is stored in the variable greatest.
Finally, the program displays the greatest number using printf.
The program returns 0 at the end of the main function, indicating successful execution.
Problem Statement 21:
You are tasked with creating a C program that takes an array of integers and calculates the sum of its elements.
Code:
#include <stdio.h>
int main()
{
int size, i, sum = 0;
printf("Enter the size of the array: ");
scanf("%d", &size);
int arr[size];
printf("Enter the elements of the array:\n");
for (i = 0; i < size; i++)
{
printf("Element %d: ", i + 1);
scanf("%d", &arr[i]);
}
for (i = 0; i < size; i++)
{
sum += arr[i];
}
printf("The sum of array elements is: %d\n", sum);
return 0;
}
Explanation:
The code begins with the inclusion of the standard input/output library (<stdio.h>).
It declares integer variables size, i, and sum. size will store the size of the array, i is used as a loop counter, and sum will store the sum of the array elements.
The program prompts the user to enter the size of the array using printf.
The user's input for the array size is read and stored in the size variable using scanf.
An integer array arr of the specified size is declared.
The program prompts the user to enter the elements of the array one by one using a loop. It displays a prompt for each element, and the user's input is stored in the corresponding position of the array arr.
After collecting all the array elements, the program enters a loop to calculate the sum of the array elements. It iterates through each element of the array, adds it to the sum variable, and accumulates the sum.
Finally, the program displays the calculated sum of the array elements using printf.
The program returns 0 at the end of the main function, indicating successful execution.
Problem Statement 22:
You are tasked with creating a C program that reads an array of numbers and finds the largest and smallest numbers among them.
Code:
#include <stdio.h>
int main()
{
int size, i;
int largest, smallest;
printf("Enter the size of the array: ");
scanf("%d", &size);
int arr[size];
printf("Enter the elements of the array:\n");
for (i = 0; i < size; i++)
{
printf("Element %d: ", i + 1);
scanf("%d", &arr[i]);
}
largest = arr[0];
smallest = arr[0];
for (i = 1; i < size; i++)
{
if (arr[i] > largest)
{
largest = arr[i];
}
if (arr[i] < smallest)
{
smallest = arr[i];
}
}
printf("The largest number is: %d\n", largest);
printf("The smallest number is: %d\n", smallest);
return 0;
}
Explanation:
The code begins with the inclusion of the standard input/output library (<stdio.h>).
It declares integer variables size, i, largest, and smallest. size will store the size of the array, i is used as a loop counter, and largest and smallest will store the largest and smallest numbers, respectively, among the array elements.
The program prompts the user to enter the size of the array using printf.
The user's input for the array size is read and stored in the size variable using scanf.
An integer array arr of the specified size is declared.
The program prompts the user to enter the elements of the array one by one using a loop. It displays a prompt for each element, and the user's input is stored in the corresponding position of the array arr.
After collecting all the array elements, the program initializes largest and smallest with the value of the first element of the array (arr[0]).
The program enters a loop starting from the second element of the array (arr[1]) and iterates through each element. Inside the loop, it checks whether the current element is larger than largest or smaller than smallest and updates these variables accordingly.
After the loop, the program has determined the largest and smallest numbers among the array elements.
Finally, the program displays the largest and smallest numbers using printf.
The program returns 0 at the end of the main function, indicating successful execution.
Problem Statement 23:
You are tasked with creating a C program that takes a string input and reverses it using a loop.
Code:
#include <stdio.h>
int main()
{
char input[100];
char reversed[100];
int i, length = 0;
printf("Enter a string: ");
scanf("%s", input);
while (input[length] != '\0')
{
length++;
}
for (i = length - 1; i >= 0; i--)
{
reversed[length - 1 - i] = input[i];
}
reversed[length] = '\0';
printf("Reversed string: %s\n", reversed);
return 0;
}
Explanation:
The code begins with the inclusion of the standard input/output library (<stdio.h>).
It declares character arrays input and reversed, an integer variable i, and an integer variable length initialized to 0. input will store the user's input string, reversed will store the reversed string, i is used as a loop counter, and length will store the length of the input string.
The program prompts the user to enter a string using printf.
The user's input for the string is read and stored in the input array using scanf. Note that scanf("%s", input) reads a string without spaces.
The program calculates the length of the input string by iterating through each character until it encounters the null character '\0' which marks the end of the string.
After finding the length of the input string, the program enters a loop to reverse the string character by character. It starts from the last character of the input string and copies it to the first position of the reversed array, then moves to the second last character and copies it to the second position of reversed, and so on. This loop effectively reverses the string.
The program adds the null character '\0' to the end of the reversed string to terminate it.
Finally, the program displays the reversed string using printf.
The program returns 0 at the end of the main function, indicating successful execution.
Problem Statement 24:
You are tasked with creating a C program that checks if a given string is a palindrome (reads the same backward as forward).
Code:
#include <stdio.h>
#include <string.h>
int main()
{
char input[100];
int i, j, isPalindrome = 1;
printf("Enter a string: ");
scanf("%s", input);
int length = strlen(input);
for (i = 0, j = length - 1; i < j; i++, j--)
{
if (input[i] != input[j])
{
isPalindrome = 0;
break;
}
}
if (isPalindrome)
{
printf("The string is a palindrome.\n");
}
else
{
printf("The string is not a palindrome.\n");
}
return 0;
}
Explanation:
The code begins with the inclusion of the standard input/output library (<stdio.h>) and the string manipulation library (<string.h>).
It declares a character array input to store the user's input string, integer variables i and j for loop counters, and an integer variable isPalindrome initialized to 1. isPalindrome is used to track whether the string is a palindrome or not.
The program prompts the user to enter a string using printf.
The user's input for the string is read and stored in the input array using scanf. Note that scanf("%s", input) reads a string without spaces.
The program calculates the length of the input string using strlen function and stores it in the length variable.
A loop is used to check if the string is a palindrome. The loop runs from i = 0 to j = length - 1 (from the beginning to the end of the string).
Inside the loop, it compares characters at position i and j in the input array. If they don't match, it sets isPalindrome to 0 (false) and exits the loop using break.
After the loop, it checks the value of isPalindrome. If it is 1, it prints "The string is a palindrome," indicating that the string is a palindrome. If it is 0, it prints "The string is not a palindrome," indicating that the string is not a palindrome.
Finally, the program returns 0 at the end of the main function, indicating successful execution.
Problem Statement 25:
You are tasked with creating a C program that takes a string and counts the number of vowels and consonants in it.
Code:
#include <stdio.h>
#include <ctype.h> // Include the ctype.h header for character functions
int main()
{
char input[100];
int vowels = 0, consonants = 0;
int i;
printf("Enter a string: ");
scanf("%s", input);
for (i = 0; input[i]; i++)
{
input[i] = tolower(input[i]);
}
for (i = 0; input[i]; i++)
{
char ch = input[i];
if (ch >= 'a' && ch <= 'z')
{
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
{
vowels++;
}
else
{
consonants++;
}
}
}
printf("Number of vowels: %d\n", vowels);
printf("Number of consonants: %d\n", consonants);
return 0;
}
Explanation:
The code begins with the inclusion of the standard input/output library (<stdio.h>) and the character handling library (<ctype.h>) for character functions.
It declares a character array input to store the user's input string, integer variables vowels and consonants to keep count of vowels and consonants, and an integer variable i for loop control.
The program prompts the user to enter a string using printf.
The user's input for the string is read and stored in the input array using scanf. Note that scanf("%s", input) reads a string without spaces.
To simplify vowel checking, the program converts the characters in the input array to lowercase using a loop. This ensures that both uppercase and lowercase vowels are counted correctly.
Two loops are used to count vowels and consonants in the input string. The first loop iterates through each character of the input string.
Inside the loop, it checks if the character ch is a lowercase letter ('a' to 'z') using the islower function from ctype.h. If it's a lowercase letter, it further checks if it is a vowel ('a', 'e', 'i', 'o', or 'u'). If it is, it increments the vowels count; otherwise, it increments the consonants count.
After both loops, it displays the counts of vowels and consonants using printf.
Finally, the program returns 0 at the end of the main function, indicating successful execution.
Problem Statement 26:
You are tasked with creating a C program that simulates a digital clock. The program should utilize a structure named Time with fields for hours, minutes, and seconds to represent the current time. Additionally, you need to write a function named incrementSeconds that takes a Time structure as input and increments the time by one second, properly adjusting the minutes and hours while considering the 24-hour time format. In the main function, the program should start from a user-input time and continuously print the time after each second. It is crucial that the program handles the transition from 23:59:59 to 00:00:00 correctly.
Code:
#include <stdio.h>
struct Time
{
int hours;
int minutes;
int seconds;
};
void incrementSeconds(struct Time *time)
{
time->seconds++;
if (time->seconds == 60)
{
time->seconds = 0;
time->minutes++;
if (time->minutes == 60)
{
time->minutes = 0;
time->hours++;
if (time->hours == 24)
{
time->hours = 0;
}
}
}
}
int main()
{
struct Time currentTime;
printf("Enter the initial time in format hh:mm:ss: ");
scanf("%d:%d:%d", ¤tTime.hours, ¤tTime.minutes, ¤tTime.seconds);
if (currentTime.hours < 0 || currentTime.hours >= 24 ||
currentTime.minutes < 0 || currentTime.minutes >= 60 ||
currentTime.seconds < 0 || currentTime.seconds >= 60)
{
printf("Invalid input. Please enter a valid time.\n");
return 1;
}
while (1)
{
printf("%02d:%02d:%02d\n", currentTime.hours, currentTime.minutes, currentTime.seconds);
incrementSeconds(¤tTime);
for (int i = 0; i < 10000000; i++)
{
}
}
return 0;
}
Explanation:
We start by defining a structure named Time to represent time. This structure has three fields: hours, minutes, and seconds.
The incrementSeconds function takes a pointer to a Time structure as an argument and increments the time by one second while adjusting the minutes and hours accordingly. It ensures that the time remains in the 24-hour format.
In the main function:
a. We declare a variable currentTime of type Time to store the current time.
b. We prompt the user to enter the initial time in the format "hh:mm:ss" (hours, minutes, and seconds) and use scanf to read and store these values in the currentTime structure.
c. We validate the user input to ensure that the entered values for hours, minutes, and seconds are within valid ranges (hours: 0-23, minutes: 0-59, seconds: 0-59). If the input is invalid, we display an error message and exit the program with an error code (return 1;).
d. Next, we enter an infinite loop (while (1)) to continuously update and print the time.
e. Inside the loop, we:
Print the current time using printf, formatting it as "hh:mm:ss" with leading zeros for single-digit values.
Call the incrementSeconds function to increment the time by one second, taking care of minutes and hours rollover.
Add a delay (a simple loop that does nothing) to simulate one second. In a real application, a sleep function or a timer interrupt would be used for more accurate timing.
The program will continue running indefinitely, incrementing and displaying the time in a simulated clock fashion.
Problem Statement 27:
You are tasked with writing a C program that efficiently finds the maximum and minimum values within an array of integers. The program should define a structure to hold the results (both maximum and minimum values) and implement a function that takes an integer array (along with its size) as input, then returns the maximum and minimum values. The solution should demonstrate usage of this function by finding and printing the maximum and minimum values from a provided array.
Code:
#include <stdio.h>
struct MaxMinResult
{
int max;
int min;
};
struct MaxMinResult findMaxMin(int arr[], int size)
{
struct MaxMinResult result;
result.max = arr[0];
result.min = arr[0];
for (int i = 1; i < size; i++)
{
if (arr[i] > result.max)
{
result.max = arr[i];
}
if (arr[i] < result.min)
{
result.min = arr[i];
}
}
return result;
}
int main()
{
int arr[] = {12, 45, 6, 78, 32, 9, 53, 62, 17};
int size = sizeof(arr) / sizeof(arr[0]);
struct MaxMinResult result = findMaxMin(arr, size);
printf("Maximum value: %d\n", result.max);
printf("Minimum value: %d\n", result.min);
return 0;
}
Explanation:
The #include <stdio.h> line includes the Standard Input Output header file, allowing the program to use the printf function for output.
The struct MaxMinResult is defined to store two integers, max and min, which represent the maximum and minimum values found in an array.
The findMaxMin function is declared to take two parameters: an integer array arr[] and its size size. It returns a struct MaxMinResult containing the maximum and minimum values found in the array.
Inside the findMaxMin function, the result variable is initialized with the first element of the array for both max and min. This is a common approach to ensure that max and min are valid elements of the array.
The function iterates through the array starting from the second element (since the first is already used for initialization). It compares each element with result.max and result.min to find the maximum and minimum values, respectively.
The main function defines an array arr with a set of integers and calculates its size using sizeof(arr) / sizeof(arr[0]). This size is necessary because the findMaxMin function requires the array size to iterate correctly through the array.
The main function calls findMaxMin, passing the array and its size. The returned structure contains the maximum and minimum values, which are then printed using printf.
Finally, the program outputs the maximum and minimum values found in the array to the standard output.
Problem Statement 28:
You are tasked with creating a function that concatenates two strings without using the built-in strcat function from the C Standard Library. Additionally, you need to demonstrate how to use this function in a simple C program.
Code:
#include <stdio.h>
void concatenateStrings(char dest[], const char source[])
{
int i, j;
for (i = 0; dest[i] != '\0'; i++)
{
}
for (j = 0; source[j] != '\0'; j++)
{
dest[i + j] = source[j];
}
dest[i + j] = '\0';
}
int main()
{
char str1[100] = "Hello, ";
const char str2[] = "world!";
concatenateStrings(str1, str2);
printf("Concatenated string: %s\n", str1);
return 0;
}
Explanation:
The #include <stdio.h> directive includes the Standard Input Output Library for basic input/output operations, such as printf.
void concatenateStrings(char dest[], const char source[]) defines a function that takes two strings: dest (the destination string where the result will be stored) and source (the string to be appended to dest). It does not return any value (void).
Inside concatenateStrings, a for-loop iterates over the dest array until it finds the null terminator ('\0'), which signifies the end of the string. This determines where to start appending the source string.
Another for-loop iterates over the source string. Each character of source is appended to dest starting at the index immediately after dest's last character. This effectively concatenates source to the end of dest.
After appending all characters from source, a null terminator ('\0') is added to the end of dest to mark the new end of the concatenated string.
In main(), two strings str1 and str2 are defined, with str1 having enough space to hold the concatenated result. concatenateStrings is called with str1 and str2 as arguments.
Finally, the concatenated string stored in str1 is printed to the console using printf.
Problem Statement 29:
You are tasked with creating a C program that defines structures for various shapes: a circle, a rectangle, and a triangle. For each shape, you need to write functions that calculate their areas. The program should allow the user to select a shape, input the necessary dimensions, and then display the area of the chosen shape.
Code:
#include <stdio.h>
#include <math.h>
typedef struct
{
double radius;
} Circle;
typedef struct
{
double length;
double width;
} Rectangle;
typedef struct
{
double base;
double height;
} Triangle;
double calculateCircleArea(Circle circle)
{
return 3.14159265359 * circle.radius * circle.radius;
}
double calculateRectangleArea(Rectangle rectangle)
{
return rectangle.length * rectangle.width;
}
double calculateTriangleArea(Triangle triangle)
{
return 0.5 * triangle.base * triangle.height;
}
int main()
{
int choice;
printf("Choose a shape:\n");
printf("1. Circle\n");
printf("2. Rectangle\n");
printf("3. Triangle\n");
printf("Enter your choice (1/2/3): ");
scanf("%d", &choice);
switch (choice)
{
case 1:
Circle circle;
printf("Enter the radius of the circle: ");
scanf("%lf", &circle.radius);
double area = calculateCircleArea(circle);
printf("Area of the circle: %lf\n", area);
break;
case 2:
Rectangle rectangle;
printf("Enter the length and width of the rectangle: ");
scanf("%lf %lf", &rectangle.length, &rectangle.width);
double area = calculateRectangleArea(rectangle);
printf("Area of the rectangle: %lf\n", area);
break;
case 3:
Triangle triangle;
printf("Enter the base and height of the triangle: ");
scanf("%lf %lf", &triangle.base, &triangle.height);
double area = calculateTriangleArea(triangle);
printf("Area of the triangle: %lf\n", area);
break;
default:
printf("Invalid choice\n");
}
return 0;
}
Explanation:
The code begins by defining three structures: Circle, Rectangle, and Triangle, each containing the necessary fields to represent dimensions of the respective shapes.
For each shape, a function is defined to calculate its area. These functions use the respective shape's dimensions (passed as a structure) to calculate the area. The circle area calculation uses a predefined value for Pi.
The main function starts by asking the user to choose a shape by entering a number corresponding to the shape (1 for circle, 2 for rectangle, 3 for triangle).
Depending on the user's choice, the program prompts for the necessary dimensions (radius for circle, length and width for rectangle, base and height for triangle), reads these values from the user, and stores them in the appropriate structure.
After reading the input, the program calls the corresponding area calculation function and prints the area to the console.
If the user enters an invalid choice, the program prints an "Invalid choice" message.
Problem Statement 30:
You need to write a C program that takes an integer n from the user, representing the number of elements in an array. The program should then allow the user to input n values to fill the array. Additionally, you must implement a function that counts how many times a specific number, also provided by the user, appears in the array. Finally, the program should display this count to the user.
Code:
#include <stdio.h>
int countOccurrences(int arr[], int n, int target)
{
int count = 0;
for (int i = 0; i < n; i++)
{
if (arr[i] == target)
{
count++;
}
}
return count;
}
int main()
{
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
int target;
printf("Enter the number to count: ");
scanf("%d", &target);
int count = countOccurrences(arr, n, target);
printf("The number %d appears %d times in the array.\n", target, count);
return 0;
}
Explanation:
The program begins by including the stdio.h header for input and output functions.
A function countOccurrences is defined to count how many times a specific number appears in an array. It takes an array arr, its size n, and the target number target as arguments.
The main function first asks the user for the number of elements n and then declares an array arr of size n.
The user is prompted to enter n elements, which are read into the array using a for-loop.
The user is then asked for a target number whose occurrences in the array are to be counted.
The countOccurrences function is called with the array, its size, and the target number as arguments. It iterates through the array, incrementing a count variable each time the target number is found.
Finally, the program prints the number of times the target number appears in the array.
Problem Statement 31:
Develop a C program that can reverse the contents of a user-defined array without utilizing a secondary array to store the reversed sequence. The program must prompt the user to input the size of the array followed by its elements. Once the array is reversed in place, the modified array should be displayed to the user. This task aims to assess your skills in manipulating arrays and implementing in-place algorithms in C.
Code:
#include <stdio.h>
void reverseArray(int arr[], int size)
{
int start = 0;
int end = size - 1;
while (start < end)
{
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
int main()
{
int size;
printf("Enter the size of the array: ");
scanf("%d", &size);
int arr[size];
printf("Enter %d elements:\n", size);
for (int i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
reverseArray(arr, size);
printf("Reversed array:\n");
for (int i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Explanation:
The program starts with including the standard input-output header file necessary for input/output operations.
A function named reverseArray is defined to reverse the array in place. It takes an integer array and its size as arguments.
Inside this function, two pointers start and end are initialized to point to the beginning and the end of the array, respectively.
A loop is used to swap the elements at the start and end positions until they meet in the middle, effectively reversing the array.
The main function begins by asking the user for the size of the array and reads this value.
Based on the size input by the user, an array of that size is declared.
The program then prompts the user to input the elements of the array, which are stored in the array using a loop.
After the array is populated, the reverseArray function is called with the array and its size as arguments to reverse it.
Finally, the reversed array is printed to the screen, demonstrating that the original array has been reversed in place.
Problem Statement 32:
Create a C program that determines whether a given array is a palindrome. A palindrome is a sequence that reads the same backward as forward, such as [1, 2, 3, 2, 1]. The program should prompt the user to enter the size of the array and its elements. After evaluating the array, the program should output whether the array is a palindrome or not. This challenge aims to test your ability to implement algorithms that involve array manipulation and comparison logic in C.
Code:
#include <stdio.h>
int isPalindrome(int arr[], int size)
{
int start = 0;
int end = size - 1;
while (start <= end)
{
if (arr[start] != arr[end])
{
return 0;
}
start++;
end--;
}
return 1;
}
int main()
{
int size;
printf("Enter the size of the array: ");
scanf("%d", &size);
int arr[size];
printf("Enter %d elements:\n", size);
for (int i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
int result = isPalindrome(arr, size);
if (result)
{
printf("The array is a palindrome.\n");
}
else
{
printf("The array is not a palindrome.\n");
}
return 0;
}
Explanation:
The program includes the standard input-output header file for input and output functions.
A function named isPalindrome is defined to check if the array is a palindrome. It accepts an integer array and its size as parameters.
Two variables, start and end, are initialized to mark the beginning and the end of the array.
A while loop is used to iterate through the array from both ends towards the center. During each iteration, it compares the elements at start and end.
If at any point the elements at start and end are not equal, the function returns 0, indicating the array is not a palindrome.
The loop continues until start and end meet or cross. If all mirrored elements are equal, the function returns 1, indicating the array is a palindrome.
In the main function, the user is prompted to input the size of the array and its elements.
After gathering the input, the isPalindrome function is called with the array and its size.
The result of the isPalindrome function is used to print whether the array is a palindrome or not.
This program efficiently checks for palindrome properties in arrays without using extra space for a reversed copy, demonstrating in-place comparison logic.
Problem Statement 33:
Develop a C program that transposes a matrix input by the user and displays both the original and the transposed matrix. The transpose of a matrix is achieved by flipping the matrix over its diagonal, which turns its rows into columns and vice versa. This program aims to assess your understanding of two-dimensional arrays in C and how to manipulate them to achieve matrix transposition.
Code:
#include <stdio.h>
int main()
{
int rows, cols;
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &cols);
int matrix[rows][cols];
int transposedMatrix[cols][rows];
printf("Enter elements of the matrix:\n");
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
scanf("%d", &matrix[i][j]);
}
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
transposedMatrix[j][i] = matrix[i][j];
}
}
printf("Original matrix:\n");
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
printf("Transposed matrix:\n");
for (int i = 0; i < cols; i++)
{
for (int j = 0; j < rows; j++)
{
printf("%d\t", transposedMatrix[i][j]);
}
printf("\n");
}
return 0;
}
Explanation:
The program begins by including the standard input-output header file for input and output functions.
It then prompts the user to input the number of rows and columns for the matrix.
Two matrices are declared: matrix for the original matrix and transposedMatrix for storing the transposed version. The dimensions of transposedMatrix are reversed relative to matrix.
The program collects the elements of the matrix from the user through nested loops.
It transposes the matrix by assigning the element at matrix[i][j] to transposedMatrix[j][i]. This effectively swaps the rows and columns of the matrix.
The original matrix is displayed by iterating through matrix and printing its elements.
The transposed matrix is then displayed by iterating through transposedMatrix and printing its elements. The loops ensure that elements are printed in a matrix format with tabs separating the columns.
This program effectively demonstrates how to work with two-dimensional arrays and perform matrix transposition, showcasing array indexing and element swapping.
Problem Statement 34:
Construct a C program to perform the addition of two matrices (2D arrays) and display the resulting matrix. Matrix addition is a straightforward operation where each element of the first matrix is added to the corresponding element of the second matrix. This task is intended to evaluate your skills in handling two-dimensional arrays, iterating through array elements, and performing element-wise operations in C.
Code:
#include <stdio.h>
void addMatrices(int mat1[][100], int mat2[][100], int result[][100], 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];
}
}
}
int main()
{
int rows, cols;
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &cols);
int matrix1[100][100], matrix2[100][100], result[100][100];
printf("Enter elements of the first matrix:\n");
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
scanf("%d", &matrix1[i][j]);
}
}
printf("Enter elements of the second matrix:\n");
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
scanf("%d", &matrix2[i][j]);
}
}
if (rows > 0 && cols > 0)
{
addMatrices(matrix1, matrix2, result, rows, cols);
printf("Result matrix after addition:\n");
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
printf("%d\t", result[i][j]);
}
printf("\n");
}
}
else
{
printf("Matrix sizes are not valid for addition.\n");
}
return 0;
}
Explanation:
The program starts by declaring a function addMatrices that will add two matrices. It takes two input matrices, a result matrix, and their dimensions (rows and columns) as parameters.
Inside this function, a nested loop iterates through each element of the matrices, adding corresponding elements and storing the sum in the result matrix.
In the main function, the user is prompted to input the dimensions of the matrices.
Three matrices are declared with a fixed size of 100x100: matrix1, matrix2, and result. These matrices will hold the input matrices and the result of their addition.
The program then collects the elements of the first and second matrices from the user.
Before proceeding with the addition, the program checks if the matrices have valid sizes (rows and columns must be greater than 0).
The addMatrices function is called with the input matrices and their dimensions to perform the addition.
Finally, the resulting matrix is displayed by iterating through its elements and printing them in a formatted manner, showing the outcome of the matrix addition operation.
This program showcases how to perform operations on two-dimensional arrays and manipulate them to achieve a specific computational goal in C.
Problem Statement 35:
Design a C program that identifies and displays any duplicate elements within a user-defined array. This task involves iterating over the array to compare each element with every other element for duplicates. The program should first ask the user to enter the size of the array, followed by its elements. After processing, it should output the duplicate elements found within the array. This challenge will test your ability to work with arrays, implement nested loops, and utilize basic conditional logic in C.
Code:
#include <stdio.h>
void findDuplicates(int arr[], int size)
{
int found[size];
for (int i = 0; i < size; i++)
{
found[i] = 0;
}
for (int i = 0; i < size; i++)
{
for (int j = i + 1; j < size; j++)
{
if (arr[i] == arr[j] && found[j] != 1)
{
printf("Duplicate element: %d\n", arr[i]);
found[j] = 1;
break;
}
}
}
}
int main()
{
int size;
printf("Enter the size of the array: ");
scanf("%d", &size);
int arr[size];
printf("Enter %d elements:\n", size);
for (int i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
findDuplicates(arr, size);
return 0;
}
Explanation:
The program includes the standard input-output header file necessary for utilizing input and output functions.
A function named findDuplicates is defined for identifying and displaying duplicate elements within an array. It takes the array and its size as parameters.
Inside this function, an array named found is declared to track which elements have been checked for duplicates. This array is initialized to zero.
A nested loop structure is employed where each element of the array (outer loop) is compared with every subsequent element (inner loop) to find duplicates.
If a duplicate is found (i.e., two elements are equal), and the duplicate has not been previously identified (checked using the found array), the function prints the duplicate element.
The found array is updated to mark the element as identified to prevent the same duplicate from being reported multiple times.
In the main function, the user is prompted to input the size of the array and its elements.
After collecting the array elements, the findDuplicates function is called to detect and display any duplicates within the array.
This program demonstrates an effective method for duplicate detection in arrays, illustrating concepts such as array manipulation, nested iteration, and conditional logic in C programming.
Problem Statement 36:
Create a C program that rotates the elements of a given array to the right by 'n' positions. Rotating an array involves shifting its elements to the right such that the last elements wrap around to the front of the array. The program should prompt the user to input the size of the array, the elements of the array, and the number of positions ('n') by which the array should be rotated. This task aims to test your ability to manipulate array indices and implement modular arithmetic in C programming.
Code:
#include <stdio.h>
void rotateRight(int arr[], int size, int n)
{
n = n % size;
int temp1, temp2, current, next;
for (int i = 0; i < n; i++)
{
temp1 = arr[size - 1];
current = size - 1;
for (int j = 0; j < size; j++)
{
next = (current + 1) % size;
temp2 = arr[next];
arr[next] = temp1;
temp1 = temp2;
current = next;
}
}
}
int main()
{
int size, n;
printf("Enter the size of the array: ");
scanf("%d", &size);
int arr[size];
printf("Enter %d elements:\n", size);
for (int i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
printf("Enter the number of positions to rotate to the right: ");
scanf("%d", &n);
rotateRight(arr, size, n);
printf("Rotated array:\n");
for (int i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Explanation:
The program includes the standard input-output header for input and output functions.
A function named rotateRight is defined to rotate the array elements to the right by 'n' positions. It takes the array, its size, and the number of positions to rotate as parameters.
Inside the function, it first adjusts 'n' to handle cases where 'n' is larger than the array size using modular arithmetic (n = n % size).
It uses two temporary variables (temp1 and temp2) to store elements during the rotation process.
The function performs the rotation in a nested loop. The outer loop runs 'n' times, and the inner loop cycles through the array to shift each element to its new position.
The inner loop uses modular arithmetic to calculate the next index position, ensuring that elements wrap around the array correctly.
In the main function, the user is asked to enter the size of the array, its elements, and the number of positions 'n' to rotate the array.
After collecting the inputs, the rotateRight function is called to perform the rotation.
Finally, the rotated array is printed to showcase the result of the rotation operation.
This program effectively demonstrates array manipulation, specifically how to rotate elements within an array using index manipulation and modular arithmetic in C.
Problem Statement 37:
Create a C program that verifies whether a given array is sorted in ascending order. Ascending order means that each element in the array is less than or equal to the next element. The program should prompt the user to input the size of the array followed by its elements. After assessing the array, the program should then indicate whether the array is sorted in ascending order. This task is aimed at testing your ability to iterate through array elements and apply conditional logic to compare their values in C.
Code:
#include <stdio.h>
#include <stdbool.h>
bool isSortedAscending(int arr[], int size)
{
for (int i = 1; i < size; i++)
{
if (arr[i] < arr[i - 1])
{
return false;
}
}
return true;
}
int main()
{
int size;
printf("Enter the size of the array: ");
scanf("%d", &size);
int arr[size];
printf("Enter %d elements:\n", size);
for (int i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
bool result = isSortedAscending(arr, size);
if (result)
{
printf("The array is sorted in ascending order.\n");
}
else
{
printf("The array is not sorted in ascending order.\n");
}
return 0;
}
Explanation:
The program begins with including the standard input-output header for input and output functions and the boolean header for using bool type.
A function named isSortedAscending is defined to check if the array is sorted in ascending order. It takes an array and its size as parameters.
The function iterates through the array starting from the second element (index 1). For each element, it compares it with the previous one. If any element is found to be smaller than its predecessor, the function immediately returns false, indicating the array is not sorted in ascending order.
If the loop completes without finding any out-of-order elements, the function returns true, indicating the array is sorted in ascending order.
In the main function, the user is prompted to input the size of the array and its elements.
After collecting the inputs, the isSortedAscending function is called with the array and its size as arguments.
The result of the function is used to print a message indicating whether the array is sorted in ascending order.
This program effectively demonstrates how to check for ascending order in an array, showcasing basic array manipulation, loop iteration, and conditional logic in C programming.
Problem Statement 38:
Develop a C program that inserts an element into a specified position within an array. The program should initially prompt the user to input the current size of the array, followed by the actual elements of the array. It should then ask for the element to be inserted and the position at which this element should be placed. The task aims to assess your ability to manipulate array indices, handle dynamic array sizes, and implement basic input and output operations in C.
Code:
#include <stdio.h>
void insertElement(int arr[], int *size, int element, int position)
{
if (position >= 0 && position <= *size)
{
for (int i = *size; i > position; i--)
{
arr[i] = arr[i - 1];
}
arr[position] = element;
(*size)++;
}
else
{
printf("Invalid position for insertion.\n");
}
}
int main()
{
int size;
printf("Enter the size of the array: ");
scanf("%d", &size);
int arr[100];
printf("Enter %d elements:\n", size);
for (int i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
int element, position;
printf("Enter the element to insert: ");
scanf("%d", &element);
printf("Enter the position to insert (0 to %d): ", size);
scanf("%d", &position);
insertElement(arr, &size, element, position);
printf("Updated array:\n");
for (int i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Explanation:
The program starts by including the standard input-output header for utilizing input and output functions.
A function named insertElement is declared to insert an element into the array at a specified position. It accepts the array, a pointer to its size, the element to be inserted, and the position at which to insert the element as parameters.
The function first checks if the given position is within the valid range (0 to the current size of the array) to ensure the integrity of the operation.
If the position is valid, it shifts the elements from that position one place to the right, creating space for the new element. This is done in a for loop that iterates backward from the last element to the insertion position.
The new element is inserted into the array at the specified position.
The size of the array is incremented by 1 to reflect the addition of the new element.
If the position is invalid, the function prints an error message.
In the main function, the user is prompted to input the initial size of the array and its elements. The array has been assumed to have a maximum size of 100 elements.
The user is then asked to enter the element to be inserted and its insertion position.
The insertElement function is called with the provided inputs to perform the insertion operation.
Finally, the updated array, including the newly inserted element, is displayed.
This program demonstrates basic array manipulation techniques, such as element insertion and dynamic resizing, while handling user inputs in C.
Problem Statement 39:
Design a C program that includes a structure named Point which holds two members: x and y coordinates, both of integer type. Implement a function to calculate the Euclidean distance between two points represented by this structure. The Euclidean distance is the straight-line distance between two points in Euclidean space. The program should prompt the user to input the x and y coordinates for two points and then compute and display the Euclidean distance between these points. This task is aimed at testing your understanding of structures in C, mathematical computations, and handling user input/output.
Code:
#include <stdio.h>
#include <math.h> // Include math.h for the sqrt function
typedef struct
{
int x;
int y;
} Point;
double calculateDistance(Point p1, Point p2)
{
int deltaX = p2.x - p1.x;
int deltaY = p2.y - p1.y;
return sqrt(deltaX * deltaX + deltaY * deltaY);
}
int main()
{
Point point1, point2;
printf("Enter coordinates for Point 1 (x y): ");
scanf("%d %d", &point1.x, &point1.y);
printf("Enter coordinates for Point 2 (x y): ");
scanf("%d %d", &point2.x, &point2.y);
double distance = calculateDistance(point1, point2);
printf("Euclidean distance between Point 1 and Point 2: %.2lf\n", distance);
return 0;
}
Explanation:
The program begins with including the standard input-output header for input and output functions and the math header to use the sqrt function for square root calculations.
A structure named Point is defined, which contains two integer members: x and y, representing the coordinates of a point in 2D space.
A function calculateDistance is declared to compute the Euclidean distance between two points. It accepts two Point structures as parameters.
Inside the function, it calculates the differences in the x and y coordinates between the two points (deltaX and deltaY), then applies the Euclidean distance formula: sqrt((deltaX)^2 + (deltaY)^2).
In the main function, two Point variables (point1 and point2) are declared, and the user is prompted to enter their coordinates.
The calculateDistance function is called with these two points, and the computed distance is stored in a double variable named distance.
Finally, the calculated Euclidean distance is displayed to the user with a precision of two decimal places.
This program demonstrates the use of structures to represent data, mathematical calculations in C, and basic input/output handling.
Problem Statement 40:
Create a C program that utilizes a structure named Student, which contains two members: studentId (an integer) and grade (a float). Your program should create an array of Student structures to store information for multiple students. The program should prompt the user to enter the number of students, and then for each student, it should accept the student ID and grade as input. After collecting the data, the program should use a loop to print out each student's ID and grade. This task is designed to assess your ability to work with arrays of structures, handle user input/output, and iterate through arrays in C.
Code:
#include <stdio.h>
struct Student
{
int studentId;
float grade;
};
int main()
{
int numStudents;
printf("Enter the number of students: ");
scanf("%d", &numStudents);
struct Student students[numStudents];
for (int i = 0; i < numStudents; i++)
{
printf("Enter Student %d ID: ", i + 1);
scanf("%d", &students[i].studentId);
printf("Enter Student %d Grade: ", i + 1);
scanf("%f", &students[i].grade);
}
printf("Student Information:\n");
for (int i = 0; i < numStudents; i++)
{
printf("Student %d ID: %d, Grade: %.2f\n", i + 1, students[i].studentId, students[i].grade);
}
return 0;
}
Explanation:
The program starts with including the standard input-output header for utilizing input and output functions.
A structure named Student is defined, which has two members: studentId (an integer) and grade (a floating-point number).
In the main function, the user is prompted to enter the total number of students, which determines the size of the Student array to be created.
An array named students of the Student structure is declared with the size based on the user's input.
A for loop is used to iterate through each student in the array, prompting the user to input the student ID and grade for each. These values are stored in the respective fields of the Student structure within the array.
After collecting the data, another for loop is used to iterate through the array and print out the ID and grade of each student, formatted to show the grade to two decimal places.
This program demonstrates the use of structures and arrays to store and manipulate a collection of related data, as well as basic input/output handling in C.
Problem Statement 41:
Develop a C program that swaps the values of two integers using pointers. The program should define a function that takes the addresses of two integer variables and swaps their values. This exercise is intended to demonstrate your understanding of pointer usage in C for direct memory manipulation.
Code:
#include <stdio.h>
void swap(int *num1, int *num2)
{
int temp = *num1;
*num1 = *num2;
*num2 = temp;
}
int main()
{
int a = 10;
int b = 20;
printf("Before swapping:\n");
printf("a = %d, b = %d\n", a, b);
swap(&a, &b);
printf("After swapping:\n");
printf("a = %d, b = %d\n", a, b);
return 0;
}
Explanation:
The program starts by including the standard input-output header for utilizing input and output functions.
A function named swap is declared to swap the values of two integers. It accepts two arguments: pointers to the integers (int *num1 and int *num2).
Inside the swap function, a temporary variable temp is used to store the value pointed to by num1. Then, the value pointed to by num2 is assigned to the location pointed to by num1. Finally, the value stored in temp is assigned to the location pointed to by num2, completing the swap.
In the main function, two integer variables a and b are declared and initialized.
The program prints the values of a and b before the swap for demonstration purposes.
The swap function is then called with the addresses of a and b (&a and &b) as its arguments.
After the swap operation, the program prints the values of a and b again, showing that their values have been swapped.
This program demonstrates the basic concept of pointers in C by directly manipulating the memory locations of variables to swap their values.
Problem Statement 42:
Design a C program that manages a library system capable of adding books, checking them in and out, updating book details, and displaying the library inventory. Utilize a Book structure that includes title, author, ISBN, and availability status. The program should demonstrate functionality for adding a new book, checking out and returning a book, updating a book's details, and displaying all books in the library. Implement functions for each of these actions and test them within your program. This task aims to evaluate your ability to work with structures, arrays, and pointers in C, as well as your understanding of basic library operations.
Code:
#include <stdio.h>
#include <string.h>
#define MAX_BOOKS 100
typedef struct {
char title[100];
char author[100];
char ISBN[20];
int available;
} Book;
void addBook(Book *library, int *numBooks, Book newBook);
void updateBookDetails(Book *book, const char *newTitle, const char *newAuthor, const char *newISBN);
void checkOutBook(Book *book);
void returnBook(Book *book);
void displayLibrary(Book *library, int numBooks);
int main() {
Book library[MAX_BOOKS];
int numBooks = 0;
Book exampleBook = {"Example Title", "Example Author", "123-456-789", 1};
addBook(library, &numBooks, exampleBook);
if (numBooks > 0) {
printf("\nChecking out the first book...\n");
checkOutBook(&library[0]);
}
printf("\nReturning the first book...\n");
returnBook(&library[0]);
printf("\nUpdating the first book's details...\n");
updateBookDetails(&library[0], "New Title", "New Author", "987-654-321");
printf("\nLibrary Inventory:\n");
displayLibrary(library, numBooks);
return 0;
}
void addBook(Book *library, int *numBooks, Book newBook) {
if (*numBooks < MAX_BOOKS) {
library[*numBooks] = newBook;
(*numBooks)++;
printf("New book added to the library.\n");
} else {
printf("Library is full. Cannot add more books.\n");
}
}
void updateBookDetails(Book *book, const char *newTitle, const char *newAuthor, const char *newISBN) {
strcpy(book->title, newTitle);
strcpy(book->author, newAuthor);
strcpy(book->ISBN, newISBN);
printf("Book details updated.\n");
}
void checkOutBook(Book *book) {
if (book->available) {
book->available = 0;
printf("Book checked out successfully.\n");
} else {
printf("Book is already checked out.\n");
}
}
void returnBook(Book *book) {
if (!book->available) {
book->available = 1;
printf("Book returned successfully.\n");
} else {
printf("Book is not checked out.\n");
}
}
void displayLibrary(Book *library, int numBooks) {
for (int i = 0; i < numBooks; i++) {
printf("Title: %s, Author: %s, ISBN: %s, Status: %s\n",
library[i].title, library[i].author, library[i].ISBN,
library[i].available ? "Available" : "Checked Out");
}
}
Explanation:
The Book structure is defined with title, author, ISBN, and available as its members. This structure represents each book in the library.
The program includes prototypes for functions that add a book to the library, update a book's details, check out a book, return a book, and display all books in the library.
Main Function:
Initializes an array of Book structures named library with a maximum size defined by MAX_BOOKS.
Manages the current number of books with numBooks.
Demonstrates adding a book, checking out and returning a book, updating a book's details, and displaying the library's inventory.
Function Implementations:
addBook: Adds a new book to the library array and increments the numBooks counter.
updateBookDetails: Updates the title, author, and ISBN of a book.
checkOutBook: Marks a book as checked out (not available).
returnBook: Marks a book as returned (available).
displayLibrary: Loops through the library array and prints the details of each book, indicating whether each is available or checked out.
Problem Statement 43:
Develop a C program that calculates the factorial of a given number using recursion. The factorial of a number n is defined as the product of all positive integers less than or equal to n. For example, the factorial of 5 (denoted as 5!) is 5 * 4 * 3 * 2 * 1 = 120. The program should define a recursive function that takes an integer n as its argument and returns the factorial of n. The base case for the recursion should handle the fact that the factorial of 0 and 1 is 1. After computing the factorial, the program should display the result. This task aims to test your understanding of recursion in C programming, a powerful technique for solving problems that can be divided into smaller instances of the same problem.
Code:
#include <stdio.h>
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
}
return n * factorial(n - 1);
}
int main() {
int num = 5;
printf("Factorial of %d is %d\n", num, factorial(num));
return 0;
}
Explanation:
Factorial Function: The program includes a recursive function factorial that calculates the factorial of a given integer n. The function uses a simple recursive formula: n! = n * (n-1)!, with the base cases being 0! = 1 and 1! = 1.
Recursion: The key concept demonstrated in this program is recursion, where the function factorial calls itself with a decremented value of n until it reaches the base case.
Main Function: In the main function, an example number num is defined, and the factorial of this number is computed by calling the factorial function. The result is then printed to the console.
Problem Statement 44:
Write a C program to compute the nth number in the Fibonacci sequence using recursion. The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. That is, the sequence begins 0, 1, 1, 2, 3, 5, 8, 13, ... and so on. Your program should define a recursive function that takes an integer n as its argument and returns the nth Fibonacci number. Make sure to handle the base cases where n is 0 or 1. The program should prompt the user to enter a number, calculate the corresponding Fibonacci number, and display the result.
Code:
#include <stdio.h>
int fibonacci(int n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int num;
printf("Enter a number to find its Fibonacci value: ");
scanf("%d", &num);
printf("Fibonacci(%d) is %d\n", num, fibonacci(num));
return 0;
}
Explanation:
Fibonacci Function: The program includes a recursive function named fibonacci that calculates the nth number in the Fibonacci sequence. This function has two base cases: when n is 0, it returns 0, and when n is 1, it returns 1. For all other values of n, it returns the sum of the two preceding numbers in the sequence, computed by recursively calling itself with n - 1 and n - 2.
Recursion: This program demonstrates the use of recursion, a technique where a function calls itself to solve smaller instances of the same problem. Recursion is particularly well-suited for solving problems like generating Fibonacci numbers, which are defined in terms of previous values in the sequence.
Main Function: The main function prompts the user to enter a number for which the Fibonacci value is to be calculated. It reads this number using scanf, calls the fibonacci function with the input number as the argument, and prints the result.
Problem Statement 45:
Develop a C program that checks if a given string is a palindrome using recursion. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). Your program should implement a recursive function that takes a string, along with starting and ending indices as arguments, and returns true if the string is a palindrome and false otherwise. The base case of the recursion should handle the scenario where the comparison has reached the middle of the string or if the characters being compared do not match. Test your function by determining if a predefined string is a palindrome and display the result.
Code:
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
bool isPalindrome(char str[], int start, int end) {
if (start >= end) {
return true;
}
if (str[start] != str[end]) {
return false;
}
return isPalindrome(str, start + 1, end - 1);
}
int main() {
char str[] = "racecar";
if (isPalindrome(str, 0, strlen(str) - 1)) {
printf("%s is a palindrome\n", str);
} else {
printf("%s is not a palindrome\n", str);
}
return 0;
}
Explanation:
Palindrome Function: The program includes a recursive function isPalindrome that checks if a given string is a palindrome. The function takes three arguments: the string str, and two integers, start and end, which represent the indices of the characters currently being compared.
Recursion Logic: The function compares the characters at the start and end indices. If these characters are not equal, it immediately returns false, indicating that the string is not a palindrome. If the characters are equal, the function calls itself with start incremented by 1 and end decremented by 1, moving the comparison inward towards the center of the string.
Base Case: The recursion has two base cases:
If start is greater than or equal to end, it means the entire string (or the relevant portion of it) has been checked without finding any mismatched characters, so the function returns true.
If the characters at the start and end indices are different, the function returns false.
Main Function: The main function defines a test string str and calls the isPalindrome function with the initial start index of 0 and an end index of strlen(str) - 1 (which is the last character of the string). It then prints whether the string is a palindrome based on the function's return value.
Problem Statement 46:
Write a C program that converts a decimal number to its binary representation using recursion. The program should define a recursive function that takes an integer n (the decimal number) as its argument and prints its binary representation. In computing the binary representation, remember that the binary form of a decimal number can be obtained by dividing the number by 2 and recording the remainder (0 or 1) for each division, working from the least significant bit to the most significant bit. The base case of the recursion occurs when n is reduced to 0. The program should test this function by converting a predefined decimal number to binary and displaying the result.
Code:
#include <stdio.h>
void decimalToBinary(int n) {
if (n > 0) {
decimalToBinary(n / 2);
printf("%d", n % 2);
}
}
int main() {
int decimalNumber = 10;
printf("Binary representation of %d is: ", decimalNumber);
decimalToBinary(decimalNumber);
printf("\n");
return 0;
}
Explanation:
Recursive Function (decimalToBinary): The function takes an integer n as input and prints its binary representation. It works by recursively dividing n by 2 (shifting right in binary terms) until n is 0. After each recursive call, it prints the remainder of the division by 2 (n % 2), which is either 0 or 1, representing a binary digit. The recursive calls build up on the call stack, and as they return, the remainders are printed in the correct order, from the most significant bit to the least significant bit.
Recursion Logic: The recursion begins with the most significant part of the binary number (due to the recursive call being placed before the printf statement). This ensures that the binary digits are printed in the correct order as the function unwinds from its recursion.
Main Function: The main function defines a test case with a decimal number, decimalNumber, and calls decimalToBinary to convert it to binary. It starts by printing a message indicating the decimal number being converted, calls the recursive function to print its binary representation, and ends with a newline for clarity.
Problem Statement 47:
Develop a C program that calculates the length of a string using recursion. The program should implement a recursive function that takes a string (character array) as its argument and returns the length of that string. The function should determine the length by counting characters until it reaches the null terminator ('\0'), which marks the end of the string.
Code:
#include <stdio.h>
#include <string.h>
int stringLength(char str[]) {
if (str[0] == '\0') {
return 0;
}
return 1 + stringLength(str + 1);
}
int main() {
char str[] = "Hello, World!";
printf("Length of the string is %d\n", stringLength(str));
return 0;
}
Explanation:
Recursive Function (stringLength): The function checks if the first character of the string is the null terminator ('\0'). If it is, the string's length is 0, which is the base case of the recursion. If not, the function calls itself with a pointer to the next character in the string (str + 1), effectively reducing the problem size by one character. It adds 1 to the result of this recursive call, counting each character until the base case is reached.
Recursion Logic: This approach exploits the fact that a string in C is an array of characters terminated by a null character. By recursively calling the function with the next substring (excluding the first character), and adding 1 for each call, the function accumulates the total number of characters before the null terminator.
Main Function: The main function defines an example string str and calls stringLength to find its length. It then prints the length of the string. This demonstrates how recursion can be used to iterate through a string and calculate its length without using traditional loop constructs or the built-in strlen function.
Problem Statement 48:
Write a C program that calculates the sum of the digits of a given integer using recursion. The program should define a recursive function that takes an integer n as its argument and returns the sum of its digits. The base case for the recursion occurs when n is reduced to 0, at which point the function should return 0. For any other value of n, the function should return the last digit of n plus the sum of the digits of the number obtained by removing the last digit from n (achieved by dividing n by 10).
Code:
#include <stdio.h>
int sumOfDigits(int n) {
if (n == 0) {
return 0;
}
return n % 10 + sumOfDigits(n / 10);
}
int main() {
int num = 12345;
printf("Sum of digits of %d is %d\n", num, sumOfDigits(num));
return 0;
}
Explanation:
Recursive Function (sumOfDigits): This function calculates the sum of the digits of an integer n recursively. It identifies the base case as n being 0, in which case it returns 0, signifying that there are no more digits to add.
Recursion Logic: For values of n greater than 0, the function separates the last digit of n using the modulus operator (n % 10) and adds it to the result of a recursive call to itself with the rest of the number (n / 10). This effectively peels off one digit at a time from n, adding each digit to the cumulative sum until n is reduced to 0.
Main Function: An example integer num is defined in the main function. The sumOfDigits function is then called with num as the argument to calculate the sum of its digits. The result is printed to demonstrate the functionality of the recursive solution.
Problem Statement 49:
Develop a C program that requests a string input from the user. This program should analyze the entered string and calculate the total number of words contained within it. For the purpose of this program, a word is defined as a sequence of characters that are separated by spaces. Assume that the input string will not start or end with spaces, and there will not be multiple consecutive spaces between words.
Code:
#include <stdio.h>
#include <string.h>
int main() {
char str[1000];
int count = 0, i;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = 0;
if (str[0] != ' ') {
count = 1;
}
for (i = 0; str[i] != '\0'; i++) {
if (str[i] == ' ' && str[i + 1] != ' ' && str[i + 1] != '\0') {
count++;
}
}
printf("Number of words in the string: %d\n", count);
return 0;
}
Explanation:
The program begins by declaring a character array str[1000] to store the input string and two integer variables: count to keep track of the number of words, and i for loop control.
It then prompts the user to enter a string, which is read using fgets(). This function is chosen over scanf() to allow for spaces within the input. The newline character introduced by pressing enter is removed to prevent it from affecting the word count.
An initial check is performed to see if the first character of the string is not a space. If it isn't, count is set to 1, assuming that the string starts with a word.
The program then iterates over each character in the string using a for loop. Inside the loop, it checks for a pattern where a space character is followed by a non-space character (and that the next character is not the end of the string). This pattern indicates the start of a new word, and thus count is incremented.
After the loop completes, the program prints the total word count. This approach effectively counts the number of transitions from a space to a non-space character across the string, which corresponds to counting words as defined in the problem statement.
Problem Statement 50:
Create a C program that prompts the user to input a string. The program should then calculate and display the frequency of each character within the string. It is important to treat uppercase and lowercase versions of a character as the same (i.e., 'A' and 'a' should be considered identical for counting purposes). The output should list characters and their frequencies.
Code:
#include <stdio.h>
#include <ctype.h> // For tolower function
int main() {
char str[1000];
int freq[26] = {0};
int i;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
for (i = 0; str[i] != '\0'; i++) {
if (str[i] >= 'A' && str[i] <= 'Z' || str[i] >= 'a' && str[i] <= 'z') {
freq[tolower(str[i]) - 'a']++;
}
}
printf("Frequency of each character in the string:\n");
for (i = 0; i < 26; i++) {
if (freq[i] != 0) {
printf("%c: %d\n", i + 'a', freq[i]);
}
}
return 0;
}
Explanation:
The program starts by declaring a character array str[1000] to store the user's input and an integer array freq[26] to hold the frequency of each letter in the alphabet. The freq array is initialized with zeros.
It prompts the user to input a string, which is read using fgets(). This approach allows spaces and punctuation in the string and ensures that the input doesn't overflow the buffer.
The program then iterates over each character in the string with a for loop. If a character is an alphabet letter (either uppercase or lowercase), it converts the character to lowercase using tolower() and increments the corresponding index in the freq array. The index is determined by subtracting 'a' from the character value, which maps 'a' to 0, 'b' to 1, and so on, up to 'z'.
After processing the entire string, the program iterates over the freq array and prints the frequency of each character that appears at least once. Characters are converted back to their alphabetical representations by adding 'a' to the index value.
This program effectively counts and displays the frequency of each letter in the input string, ignoring case differences between uppercase and lowercase letters.
Problem Statement 51:
Design a C program that prompts the user to input a string. This program should process the input string by removing all extra spaces, ensuring that only a single space remains between words and no leading or trailing spaces are present. For instance, if the input string is "Hello World !", the program should modify it to "Hello World !".
Code:
#include <stdio.h>
#include <string.h>
#include <ctype.h> // For isspace function
void removeExtraSpaces(char* input) {
int i, x = 0;
for (i = 0; input[i]; ++i) {
if (!isspace(input[i]) || (i > 0 && !isspace(input[i-1]))) {
input[x++] = input[i];
}
}
if (isspace(input[x-1])) x--;
input[x] = '\0';
}
int main() {
char str[1000];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = 0;
removeExtraSpaces(str);
printf("String after removing extra spaces: '%s'\n", str);
return 0;
}
Explanation:
The program starts by defining a function removeExtraSpaces that takes a character array (string) as its input. This function is responsible for modifying the input string to remove extra spaces.
Inside removeExtraSpaces, a for loop iterates through each character in the input string. The function uses the isspace function from ctype.h to check if a character is a space. It copies the character to a new position in the same string (input[x++]) if it is not a space or if it is the first space following a non-space character. This effectively collapses multiple spaces into a single space and preserves non-space characters.
After the loop, the function checks if the last copied character is a space. If so, it decrements the index x to remove this trailing space.
The main function reads a string from the user, removes the trailing newline character, calls removeExtraSpaces to modify the string in place, and then prints the modified string.
This approach ensures that leading spaces, trailing spaces, and extra spaces between words are removed from the input string, leaving only single spaces between words.
Problem Statement 52:
Craft a C program that requests a string from the user and reverses each word within the string while maintaining the original order of the words. For example, if the input string is "Hello World", the program should output "olleH dlroW".
Code:
#include <stdio.h>
#include <string.h>
#include <ctype.h> // For isspace function
void reverseWord(char* start, char* end) {
char temp;
while (start < end) {
temp = *start;
*start++ = *end;
*end-- = temp;
}
}
int main() {
char str[1000];
char* start = str;
char* temp = str;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = 0;
while (*temp) {
start = temp;
while (*temp && !isspace(*temp)) {
temp++;
}
reverseWord(start, temp - 1);
if (!*temp) break;
temp++;
}
printf("String with each word reversed: '%s'\n", str);
return 0;
}
Explanation:
The program includes a helper function reverseWord that takes two pointers, start and end, as arguments. It reverses the characters between these pointers, effectively reversing a word.
In the main function, the program reads a string from the user and removes the trailing newline character.
It then uses two pointers, start and temp, to iterate through the string. start marks the beginning of a word, and temp is used to find the end of the word.
The while loop iterates through the string. Inside the loop, temp advances until it finds a space or the end of the string, marking the end of a word.
Once the end of a word is found, reverseWord is called with start and temp - 1 as arguments to reverse the word in place.
After reversing the word, if the end of the string (*temp) is reached, the loop breaks. Otherwise, temp is incremented to skip the space, and the process repeats for the next word.
Finally, the program prints the modified string, which now has each word reversed but maintains the original word order.
Problem Statement 53:
Develop a C program that takes a string input from the user, reverses the entire string, and then reverses each word within the reversed string. This process will ultimately reverse the order of the words in the original string. For instance, if the user inputs "Hello World", the program should first reverse the string to "dlroW olleH" and then reverse each word to achieve the final output "World Hello".
Code:
#include <stdio.h>
#include <string.h>
#include <ctype.h> // For isspace function
void reverse(char* start, char* end) {
char temp;
while (start < end) {
temp = *start;
*start++ = *end;
*end-- = temp;
}
}
int main() {
char str[1000];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = 0;
reverse(str, str + strlen(str) - 1);
char* word_begin = str;
char* temp = str;
while (*temp) {
temp++;
if (*temp == '\0' || isspace(*temp)) {
reverse(word_begin, temp - 1);
word_begin = temp + 1;
}
}
printf("After reversing the string and then reversing each word: '%s'\n", str);
return 0;
}
Explanation:
The program defines a function reverse that takes two pointers, start and end, as arguments. This function reverses the portion of the string between these two pointers by swapping characters from the start and end until they meet in the middle.
In the main function, the program reads a string from the user and removes the trailing newline character.
It first reverses the entire string by calling reverse with pointers to the beginning and the end of the string. This action transforms the string as per the first step of the problem statement (e.g., "Hello World" becomes "dlroW olleH").
Next, the program aims to reverse each word within this reversed string. It uses a temporary pointer temp to traverse the string and a pointer word_begin to mark the start of each word.
As temp advances through the string, when it encounters a space or the end of the string (*temp == '\0'), it calls reverse for the word identified by word_begin and temp - 1. This reverses the individual word back to its original orientation but in the new reversed order.
After reversing each word in the reversed string, the program prints the final result, which is the original string with the word order reversed (e.g., "World Hello").
Problem Statement 54:
Construct a C program that prompts the user to enter two strings: a main string and a substring. The program should then check whether the main string contains the given substring. If the substring is found within the main string, the program should output "True"; otherwise, it should output "False". For instance, if the main string is "Hello world" and the substring is "world", the program should return "True".
Code:
#include <stdio.h>
#include <string.h>
int containsSubstring(char* str, char* substr) {
char* pos = strstr(str, substr);
if (pos != NULL) {
return 1;
} else {
return 0;
}
}
int main() {
char mainStr[1000];
char substr[1000];
printf("Enter the main string: ");
fgets(mainStr, sizeof(mainStr), stdin);
mainStr[strcspn(mainStr, "\n")] = 0;
printf("Enter the substring: ");
fgets(substr, sizeof(substr), stdin);
substr[strcspn(substr, "\n")] = 0;
if (containsSubstring(mainStr, substr)) {
printf("True\n");
} else {
printf("False\n");
}
return 0;
}
Explanation:
The program defines a function containsSubstring that takes two strings as arguments: the main string and the substring. It uses the strstr function from the C standard library, which returns a pointer to the first occurrence of the substring in the main string, or NULL if the substring is not found.
In the main function, the program reads two strings from the user: the main string and the substring. It removes the trailing newline character from both inputs to ensure accurate comparison.
The containsSubstring function is then called with the main string and the substring as arguments. If strstr returns a non-NULL value, indicating that the substring is present in the main string, containsSubstring returns 1 (True). Otherwise, it returns 0 (False).
Based on the return value of containsSubstring, the program outputs "True" if the substring is found within the main string, and "False" if it is not.
This approach allows the program to efficiently determine the presence of a substring within a main string, providing a simple method for substring search in C.