C Programming Examples
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;
// Prompt the user to enter two numbers
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
// Ask the user to choose an operation (+, -, *, /)
printf("Enter an operation (+, -, *, /): ");
scanf(" %c", &operation);
// Use if-else statements to perform the selected operation
if (operation == '+')
{
// Addition
printf("%.2lf + %.2lf = %.2lf\n", num1, num2, num1 + num2);
}
else if (operation == '-')
{
// Subtraction
printf("%.2lf - %.2lf = %.2lf\n", num1, num2, num1 - num2);
}
else if (operation == '*')
{
// Multiplication
printf("%.2lf * %.2lf = %.2lf\n", num1, num2, num1 * num2);
}
else if (operation == '/')
{
// Division
// Check if the second number is not zero to avoid division by zero
if (num2 != 0.0)
{
printf("%.2lf / %.2lf = %.2lf\n", num1, num2, num1 / num2);
}
else
{
printf("Cannot divide by zero.\n");
}
}
else
{
// If the operation is not recognized
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 usescanf
to read and store these numbers innum1
andnum2
.Next, we ask the user to choose an operation (+, -, *, /) using
printf
and read their choice into theoperation
variable usingscanf
. Note that there is a space before%c
inscanf
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 ofoperation
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 ifnum2
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 themain()
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;
// Prompt the user to enter the temperature and its unit (C or F)
printf("Enter temperature followed by its unit (C or F): ");
scanf("%lf %c", &temperature, &unit);
// Using if-else statements to determine the conversion direction
if (unit == 'C' || unit == 'c')
{
// Convert from Celsius to Fahrenheit
double fahrenheit = (temperature * 9 / 5) + 32;
printf("%.2lf°C is equal to %.2lf°F\n", temperature, fahrenheit);
}
else if (unit == 'F' || unit == 'f')
{
// Convert from Fahrenheit to Celsius
double celsius = (temperature - 32) * 5 / 9;
printf("%.2lf°F is equal to %.2lf°C\n", temperature, celsius);
}
else
{
// If the unit is not recognized
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 andscanf
to read the input values, storing the temperature intemperature
and the unit inunit
.The program uses
if-else
statements to determine the conversion direction based on the value ofunit
: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 themain()
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; // long long is used to handle larger numbers
// Prompt the user to enter a non-negative integer
printf("Enter a non-negative integer: ");
scanf("%d", &n);
// Check if the user entered a negative number
if (n < 0)
{
printf("Factorial of a negative number doesn't exist.\n");
}
else
{
// Calculate the factorial using a loop
for (i = 1; i <= n; ++i)
{
factorial *= i; // factorial = 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 variablen
usingscanf
.The program checks if the entered value of
n
is negative using anif
statement. Ifn
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 afor
loop:It initializes
factorial
to 1.It then uses a loop to calculate the factorial by multiplying
factorial
with consecutive integers from 1 ton
.
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 themain()
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;
// Prompt the user to enter the base and exponent
printf("Enter a base number: ");
scanf("%lf", &base);
printf("Enter an exponent (integer): ");
scanf("%d", &exponent);
// Saving the original exponent value for display purposes
int originalExponent = exponent;
// Handling negative exponents
if (exponent < 0)
{
base = 1 / base;
exponent = -exponent;
}
// Calculate the power using a loop
for (i = 1; i <= exponent; ++i)
{
result *= base;
}
// Display the result
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 to1.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 intobase
andexponent
usingscanf
.To handle negative exponents, the program checks if
exponent
is less than0
. If it is, it calculates the reciprocal of thebase
and makesexponent
positive.The program then proceeds to calculate the power using a
for
loop:It initializes
result
to1.0
.It uses a loop that runs from
1
toexponent
to repeatedly multiplyresult
bybase
.
After the loop completes, the program prints the result, displaying the value of
base
, the original value ofexponent
, and the calculated result.The program returns
0
at the end of themain()
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;
// Prompt the user to enter a year
printf("Enter a year: ");
scanf("%d", &year);
// Check if the year is a leap year
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
{
// If the year is divisible by 4 but not divisible by 100, or divisible by 400, it is a leap year
printf("%d is a leap year.\n", year);
}
else
{
// If the above conditions are not met, it is not a leap year
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 variableyear
usingscanf
.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
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 themain()
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;
// Prompt the user to enter the radius of the circle
printf("Enter the radius of the circle: ");
scanf("%lf", &radius);
// Calculate the area of the circle
area = PI * radius * radius;
// Display the result
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 value3.14159
using a preprocessor directive (#define
). This constant represents the mathematical value of π (pi).In the
main()
function, two variables are declared:double radius
to store the radius of the circle entered by the user.double area
to store the calculated area of the circle.
The program prompts the user to enter the radius of the circle using
printf
and reads the input into the variableradius
usingscanf
.The program calculates the area of the circle using the formula
Area = PI * radius * radius
and stores the result in the variablearea
.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 themain()
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;
// Prompt the user to enter two integers
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
// Displaying original values
printf("Original values: a = %d, b = %d\n", a, b);
// Swapping the values without a third variable using arithmetic operations
a = a + b; // Step 1: Add both values and store the sum in 'a'
b = a - b; // Step 2: Subtract the original 'b' value from the new 'a' value and store it in 'b' (resulting in the original 'a' value in 'b')
a = a - b; // Step 3: Subtract the original 'b' value (now in 'a') from the new 'a' value (now in 'b') and store it in 'a' (resulting in the original 'b' value in 'a')
// Displaying swapped values
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
andb
, 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 intoa
andb
usingscanf
.The original values of
a
andb
are displayed to the user usingprintf
.To swap the values of
a
andb
without using a third variable, we employ a sequence of arithmetic operations:a = a + b;
: In this step, we add the values ofa
andb
and store the result ina
. Now,a
holds the sum of the original values ofa
andb
.b = a - b;
: Next, we subtract the original value ofb
(before the addition in the previous step) from the new value ofa
. This operation effectively assigns the original value ofa
tob
.a = a - b;
: Finally, we subtract the original value ofb
(now ina
) from the new value ofa
(now inb
). This operation assigns the original value ofb
toa
.
After the swap, the program displays the swapped values of
a
andb
usingprintf
.The program returns
0
at the end of themain()
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;
// Prompt the user to enter an integer
printf("Enter an integer: ");
scanf("%d", &num);
// Process to reverse the digits of the number
while (num != 0)
{
int digit = num % 10; // Extract the last digit of num
reversedNum = reversedNum * 10 + digit; // Append the digit to reversedNum
num /= 10; // Remove the last digit from num
}
// Display the reversed number
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:int num
to store the integer entered by the user.int reversedNum
initialized to0
to store the reversed number.
The program prompts the user to enter an integer using
printf
and reads the input into the variablenum
usingscanf
.To reverse the digits of the number, the program uses a
while
loop that continues untilnum
becomes0
. Within the loop:int digit = num % 10;
: This line extracts the last digit ofnum
and stores it in the variabledigit
.reversedNum = reversedNum * 10 + digit;
: It appends the extracteddigit
to thereversedNum
by multiplying the existing reversed number by10
(shifting digits to the left) and then adding thedigit
to the result.num /= 10;
: This line removes the last digit fromnum
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 themain()
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;
// Prompt the user to enter the value of N
printf("Enter a positive integer N: ");
scanf("%d", &N);
// Check if N is positive
if (N <= 0)
{
printf("Please enter a positive integer.\n");
}
else
{
// Calculate the sum of the first N natural numbers
for (int i = 1; i <= N; i++)
{
sum += i; // Add each number to sum
}
// Display the result
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:int N
to store the positive integer entered by the user (N).int sum
initialized to0
to store the sum of the first N natural numbers.
The program prompts the user to enter a positive integer N using
printf
and reads the input into the variableN
usingscanf
.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
toN
, and in each iteration, it adds the value ofi
to thesum
variable, wherei
represents the current natural number.
- The loop runs from
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 themain()
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; // isPrime is set to 1 (true)
// Prompt the user to enter a number
printf("Enter a positive integer: ");
scanf("%d", &num);
// Check if the number is less than or equal to 1
if (num <= 1)
{
isPrime = 0; // 0 represents false
}
else
{
// Check for factors other than 1 and the number itself
for (i = 2; i <= num / 2; i++)
{
if (num % i == 0)
{
isPrime = 0; // 0 represents false
break;
}
}
}
// Display if the number is prime or not
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 to1
(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 variablenum
usingscanf
.It checks if the entered number is less than or equal to
1
. Ifnum
is less than or equal to1
, it setsisPrime
to0
(false), indicating that the number is not prime.If
num
is greater than1
, the program proceeds to check for factors other than1
and the number itself in the range from2
tonum / 2
. It does this using afor
loop:- In each iteration, it checks if
num
is divisible byi
(i.e.,num % i == 0
). If it is, it setsisPrime
to0
(false) and breaks out of the loop.
- In each iteration, it checks if
After the loop completes, the program checks the value of
isPrime
to determine if the number is prime or not. IfisPrime
is1
, it prints that the number is prime; otherwise, it prints that the number is not prime.The program returns
0
at the end of themain()
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;
// Prompt the user to enter two integers
printf("Enter two integers: ");
scanf("%d %d", &num1, &num2);
// Making sure num1 is the larger number
if (num2 > num1)
{
temp = num1;
num1 = num2;
num2 = temp;
}
// Euclidean algorithm to find the GCD
while (num2 != 0)
{
remainder = num1 % num2;
num1 = num2;
num2 = remainder;
}
gcd = num1;
// Display the GCD
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
andint 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 ofnum1
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 intonum1
andnum2
usingscanf
.To ensure that
num1
holds the larger number andnum2
holds the smaller number, the program checks ifnum2
is greater thannum1
. If it is, a temporary variabletemp
is used to swap the values ofnum1
andnum2
.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 to0
.In each iteration, the program calculates the remainder of
num1
divided bynum2
and stores it inremainder
.num2
is updated toremainder
, andnum1
retains its original value.This process continues until
num2
becomes0
, at which pointnum1
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 themain()
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;
// Prompt the user to enter an integer
printf("Enter an integer: ");
scanf("%d", &num);
// Process to sum the digits of the number
while (num != 0)
{
sum += num % 10; // Add the last digit to sum
num /= 10; // Remove the last digit from num
}
// Display the sum of the digits
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:int num
to store the integer entered by the user.int sum
initialized to0
to store the sum of the digits.
The program prompts the user to enter an integer using
printf
and reads the input into the variablenum
usingscanf
.To sum the digits of the number, the program uses a
while
loop that continues untilnum
becomes0
. Within the loop:sum += num % 10;
: In each iteration, it extracts the last digit ofnum
using the modulo operator (num % 10
) and adds it to thesum
variable.num /= 10;
: It then removes the last digit fromnum
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 themain()
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;
// Prompt the user to enter the number of terms N
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; // The first two numbers are 0 and 1
else
{
next = first + second; // Calculate the next Fibonacci number
first = second; // Update first with the value of the second
second = next; // Update second with the value of the next
}
printf("%d ", next); // Print the current Fibonacci number
}
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 to0
, representing the first number in the sequence.int second
initialized to1
, 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 usingprintf
, and reads the input into the variablen
usingscanf
.It initializes the
first
andsecond
variables with the values0
and1
respectively, which are the first two terms of the Fibonacci sequence.The program enters a
for
loop that iterates from0
ton-1
, printing the firstn
terms of the Fibonacci sequence. Inside the loop:For the first two terms (when
i
is0
or1
), it setsnext
toi
since the Fibonacci sequence starts with0
and1
.For subsequent terms, it calculates the next Fibonacci number by adding
first
andsecond
and stores it innext
.It then updates
first
with the value ofsecond
, effectively shifting the values for the next iteration.It also updates
second
with the value ofnext
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 themain()
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;
// Prompt the user to enter an integer
printf("Enter an integer: ");
scanf("%d", &num);
originalNum = num; // Store the original number
// Process to reverse the digits of the number
while (num != 0)
{
remainder = num % 10; // Get the last digit
reversedNum = reversedNum * 10 + remainder; // Add it to the reversed number
num /= 10; // Remove the last digit
}
// Check if the number is a palindrome
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 to0
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 variablenum
usingscanf
.It stores the original value of
num
in theoriginalNum
variable to compare it with the reversed number later.To reverse the digits of the number, the program uses a
while
loop that continues untilnum
becomes0
. Inside the loop:remainder = num % 10;
: In each iteration, it extracts the last digit ofnum
using the modulo operator (num % 10
) and stores it in theremainder
variable.reversedNum = reversedNum * 10 + remainder;
: It then adds the extracted digit to thereversedNum
, effectively reversing the digits.num /= 10;
: It removes the last digit fromnum
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 themain()
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;
// Prompt the user to enter a decimal number
printf("Enter a decimal number: ");
scanf("%d", &decimal);
originalDecimal = decimal; // Store the original decimal number
// Process to convert decimal to binary
while (decimal > 0)
{
remainder = decimal % 2;
binary = binary + remainder * base;
decimal = decimal / 2;
base = base * 10;
}
// Display the binary equivalent
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 to0
to store the binary equivalent.int base
initialized to1
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 variabledecimal
usingscanf
.It stores the original value of
decimal
in theoriginalDecimal
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 asdecimal
is greater than0
. Inside the loop:remainder = decimal % 2;
: In each iteration, it calculates the remainder whendecimal
is divided by2
and stores it in theremainder
variable. This remainder will be a binary digit (either0
or1
).binary = binary + remainder * base;
: It updates thebinary
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 thedecimal
by performing integer division by2
, effectively shifting digits to the right.base = base * 10;
: It updates thebase
by multiplying it by10
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 themain()
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;
// Prompt the user to enter an integer
printf("Enter an integer: ");
scanf("%d", &num);
// Check if the number is negative, make it positive
if (num < 0)
{
num = -num;
}
// Process to find the largest digit in the number
while (num > 0)
{
digit = num % 10; // Get the last digit
if (digit > maxDigit)
{
maxDigit = digit; // Update maxDigit if the current digit is larger
}
num /= 10; // Remove the last digit
}
// Display the largest digit
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 to0
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 variablenum
usingscanf
.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 asnum
is greater than0
. Inside the loop:digit = num % 10;
: In each iteration, it calculates the last digit ofnum
using the modulo operator (num % 10
) and stores it in thedigit
variable.It then compares
digit
withmaxDigit
to check if the current digit is larger. If it is, it updatesmaxDigit
to the value ofdigit
.num /= 10;
: It removes the last digit fromnum
by performing integer division by10
, 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 themain()
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;
// Prompt the user to enter a three-digit integer
printf("Enter a three-digit integer: ");
scanf("%d", &num);
originalNum = num; // Store the original number
// Process to check if the number is an Armstrong number
while (originalNum != 0)
{
remainder = originalNum % 10;
result += remainder * remainder * remainder; // Add the cube of the digit to result
originalNum /= 10; // Remove the last digit
}
// Check if the number is an Armstrong number
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 to0
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 variablenum
usingscanf
.It stores the original value of
num
in theoriginalNum
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 asoriginalNum
is not equal to0
. Inside the loop:remainder = originalNum % 10;
: In each iteration, it calculates the last digit oforiginalNum
using the modulo operator (originalNum % 10
) and stores it in theremainder
variable.result += remainder * remainder * remainder;
: It adds the cube of the digit (remainder
) to theresult
, effectively calculating the sum of the cubes of its digits.originalNum /= 10;
: It removes the last digit fromoriginalNum
by performing integer division by10
, 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 numbernum
. 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 themain()
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;
// Prompt the user to enter an integer
printf("Enter an integer: ");
scanf("%d", &num);
while (num > 9)
{ // Continue until the number is a single digit
sum = 0; // Reset sum for each iteration of the outer loop
temp = num; // Work with a temporary variable
// Sum the digits of the number
while (temp != 0)
{
sum += temp % 10; // Add the last digit to sum
temp /= 10; // Remove the last digit
}
num = sum; // Update num with the sum of its digits
}
// Display the single digit 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 to0
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 variablenum
usingscanf
.The program enters a
while
loop that continues as long asnum
is greater than9
, 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 thesum
to0
to calculate the sum of the digits for the current value ofnum
.temp = num;
: It stores the current value ofnum
in thetemp
variable to work with a temporary copy of the number.
It enters a nested
while
loop to sum the digits oftemp
until there are no more digits left:sum += temp % 10;
: In each iteration, it calculates the last digit oftemp
using the modulo operator (temp % 10
) and adds it to thesum
.temp /= 10;
: It removes the last digit fromtemp
by performing integer division by10
, effectively shifting digits to the right.
After the inner loop completes,
sum
contains the sum of the digits of the originalnum
.It updates the value of
num
with thesum
calculated in the inner loop. This is done to repeat the process with the newnum
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 to9
), the program exits the loop.It displays the single-digit sum using
printf
.The program returns
0
at the end of themain()
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 a constant for pi
#define PI 3.14159265359
// Function to calculate the area of a circle
double calculateCircleArea(double radius)
{
double area;
// Calculate the area using the formula: area = pi * radius * radius
area = PI * radius * radius;
return area;
}
int main()
{
double radius, area;
// Prompt the user to enter the radius of the circle
printf("Enter the radius of the circle: ");
scanf("%lf", &radius);
// Call the function to calculate the area
area = calculateCircleArea(radius);
// Display the calculated area
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 (approximately3.14159265359
) to be used in the area calculation formula.The program defines a function named
calculateCircleArea
that takes adouble
parameterradius
and returns adouble
value, which is the calculated area of the circle.Inside the
calculateCircleArea
function:It declares a local
double
variablearea
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 andarea
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 usingscanf
.
The program calls the
calculateCircleArea
function and passes theradius
as an argument. The returned value (the area) is stored in thearea
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 themain
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>
// Function to find the greatest among three integers
int findGreatest(int num1, int num2, int num3)
{
int greatest = num1;
// Compare num2 with greatest
if (num2 > greatest)
{
greatest = num2;
}
// Compare num3 with greatest
if (num3 > greatest)
{
greatest = num3;
}
return greatest;
}
int main()
{
int num1, num2, num3, greatest;
// Prompt the user to enter three numbers
printf("Enter three numbers: ");
scanf("%d %d %d", &num1, &num2, &num3);
// Call the function to find the greatest number
greatest = findGreatest(num1, num2, num3);
// Display the greatest number
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
, andnum3
) 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 ofnum1
. This variable will store the greatest number among the three.It compares
num2
withgreatest
and updatesgreatest
ifnum2
is greater.It also compares
num3
withgreatest
and updatesgreatest
ifnum3
is greater.Finally, it returns the value of
greatest
.
In the
main
function:Four integer variables are declared:
num1
,num2
,num3
, andgreatest
.The program prompts the user to enter three numbers using
printf
.The user's input is read and stored in the variables
num1
,num2
, andnum3
usingscanf
.
The program calls the
findGreatest
function, passingnum1
,num2
, andnum3
as arguments. The returned value (the greatest number) is stored in the variablegreatest
.Finally, the program displays the greatest number using
printf
.The program returns
0
at the end of themain
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;
// Prompt the user to enter the size of the array
printf("Enter the size of the array: ");
scanf("%d", &size);
int arr[size]; // Declare an array of the specified size
// Prompt the user to enter the array elements
printf("Enter the elements of the array:\n");
for (i = 0; i < size; i++)
{
printf("Element %d: ", i + 1);
scanf("%d", &arr[i]);
}
// Calculate the sum of array elements
for (i = 0; i < size; i++)
{
sum += arr[i];
}
// Display the sum of array elements
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
, andsum
.size
will store the size of the array,i
is used as a loop counter, andsum
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 usingscanf
.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 themain
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; // Variables to store the largest and smallest numbers
// Prompt the user to enter the size of the array
printf("Enter the size of the array: ");
scanf("%d", &size);
int arr[size]; // Declare an array of the specified size
// Prompt the user to enter the array elements
printf("Enter the elements of the array:\n");
for (i = 0; i < size; i++)
{
printf("Element %d: ", i + 1);
scanf("%d", &arr[i]);
}
// Initialize largest and smallest with the first element
largest = arr[0];
smallest = arr[0];
// Find the largest and smallest numbers in the array
for (i = 1; i < size; i++)
{
if (arr[i] > largest)
{
largest = arr[i];
}
if (arr[i] < smallest)
{
smallest = arr[i];
}
}
// Display the largest and smallest numbers
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
, andsmallest
.size
will store the size of the array,i
is used as a loop counter, andlargest
andsmallest
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 usingscanf
.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
andsmallest
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 thanlargest
or smaller thansmallest
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 themain
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]; // Assuming a maximum input length of 100 characters
char reversed[100];
int i, length = 0;
// Prompt the user to enter a string
printf("Enter a string: ");
scanf("%s", input); // Read the string without spaces
// Find the length of the input string
while (input[length] != '\0')
{
length++;
}
// Reverse the string character by character
for (i = length - 1; i >= 0; i--)
{
reversed[length - 1 - i] = input[i];
}
reversed[length] = '\0'; // Add the null character to terminate the reversed string
// Display the reversed string
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
andreversed
, an integer variablei
, and an integer variablelength
initialized to0
.input
will store the user's input string,reversed
will store the reversed string,i
is used as a loop counter, andlength
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 usingscanf
. Note thatscanf("%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 ofreversed
, and so on. This loop effectively reverses the string.The program adds the null character
'\0'
to the end of thereversed
string to terminate it.Finally, the program displays the reversed string using
printf
.The program returns
0
at the end of themain
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]; // Assuming a maximum input length of 100 characters
int i, j, isPalindrome = 1; // Initialize isPalindrome to 1 (true)
// Prompt the user to enter a string
printf("Enter a string: ");
scanf("%s", input); // Read the string without spaces
int length = strlen(input);
// Check if the string is a palindrome
for (i = 0, j = length - 1; i < j; i++, j--)
{
if (input[i] != input[j])
{
isPalindrome = 0; // Set isPalindrome to 0 (false) if characters don't match
break; // Exit the loop early if a mismatch is found
}
}
// Display the result
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 variablesi
andj
for loop counters, and an integer variableisPalindrome
initialized to1
.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 usingscanf
. Note thatscanf("%s", input)
reads a string without spaces.The program calculates the length of the input string using
strlen
function and stores it in thelength
variable.A loop is used to check if the string is a palindrome. The loop runs from
i = 0
toj = length - 1
(from the beginning to the end of the string).Inside the loop, it compares characters at position
i
andj
in theinput
array. If they don't match, it setsisPalindrome
to0
(false) and exits the loop usingbreak
.After the loop, it checks the value of
isPalindrome
. If it is1
, it prints "The string is a palindrome," indicating that the string is a palindrome. If it is0
, 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 themain
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]; // Assuming a maximum input length of 100 characters
int vowels = 0, consonants = 0;
int i;
// Prompt the user to enter a string
printf("Enter a string: ");
scanf("%s", input); // Read the string without spaces
// Convert the input string to lowercase for easier vowel checking
for (i = 0; input[i]; i++)
{
input[i] = tolower(input[i]);
}
// Count vowels and consonants
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++;
}
}
}
// Display the counts of vowels and 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 variablesvowels
andconsonants
to keep count of vowels and consonants, and an integer variablei
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 usingscanf
. Note thatscanf("%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 theislower
function fromctype.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 thevowels
count; otherwise, it increments theconsonants
count.After both loops, it displays the counts of vowels and consonants using
printf
.Finally, the program returns
0
at the end of themain
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>
// Define a structure to represent time
struct Time
{
int hours;
int minutes;
int seconds;
};
// Function to increment time by one second
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; // Wrap around to 00:00:00 at midnight
}
}
}
}
int main()
{
struct Time currentTime;
// Prompt the user to enter the initial time
printf("Enter the initial time in format hh:mm:ss: ");
scanf("%d:%d:%d", ¤tTime.hours, ¤tTime.minutes, ¤tTime.seconds);
// Validate the input
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; // Exit with an error code
}
// Infinite loop to continuously increment and print the time
while (1)
{
// Print the current time
printf("%02d:%02d:%02d\n", currentTime.hours, currentTime.minutes, currentTime.seconds);
// Increment the time by one second
incrementSeconds(¤tTime);
// Add a delay to simulate one second
// Sleep function or delay function can be used here (platform-dependent)
// For simplicity, we'll add a simple loop to waste time
for (int i = 0; i < 10000000; i++)
{
// Wasting time
}
}
return 0;
}
Explanation:
We start by defining a structure named
Time
to represent time. This structure has three fields:hours
,minutes
, andseconds
.The
incrementSeconds
function takes a pointer to aTime
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 typeTime
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 thecurrentTime
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>
// Define a structure to store the maximum and minimum values
struct MaxMinResult
{
int max;
int min;
};
// Function to find the maximum and minimum values in an integer array
struct MaxMinResult findMaxMin(int arr[], int size)
{
struct MaxMinResult result;
// Initialize max and min with the first element of the array
result.max = arr[0];
result.min = arr[0];
// Iterate through the array to find max and min
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 theprintf
function for output.The
struct MaxMinResult
is defined to store two integers,max
andmin
, which represent the maximum and minimum values found in an array.The
findMaxMin
function is declared to take two parameters: an integer arrayarr[]
and its sizesize
. It returns astruct MaxMinResult
containing the maximum and minimum values found in the array.Inside the
findMaxMin
function, theresult
variable is initialized with the first element of the array for bothmax
andmin
. This is a common approach to ensure thatmax
andmin
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
andresult.min
to find the maximum and minimum values, respectively.The
main
function defines an arrayarr
with a set of integers and calculates its size usingsizeof(arr) / sizeof(arr[0])
. This size is necessary because thefindMaxMin
function requires the array size to iterate correctly through the array.The
main
function callsfindMaxMin
, passing the array and its size. The returned structure contains the maximum and minimum values, which are then printed usingprintf
.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>
// Function to concatenate two strings
void concatenateStrings(char dest[], const char source[])
{
int i, j;
// Find the length of the destination string
for (i = 0; dest[i] != '\0'; i++)
{
}
// Copy the source string to the end of the destination string
for (j = 0; source[j] != '\0'; j++)
{
dest[i + j] = source[j];
}
// Add a null terminator to the end of the concatenated string
dest[i + j] = '\0';
}
int main()
{
char str1[100] = "Hello, ";
const char str2[] = "world!";
// Call the concatenateStrings function to concatenate str2 to str1
concatenateStrings(str1, str2);
// Print the concatenated string
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 asprintf
.void concatenateStrings(char dest[], const char source[])
defines a function that takes two strings:dest
(the destination string where the result will be stored) andsource
(the string to be appended todest
). It does not return any value (void
).Inside
concatenateStrings
, a for-loop iterates over thedest
array until it finds the null terminator ('\0'
), which signifies the end of the string. This determines where to start appending thesource
string.Another for-loop iterates over the
source
string. Each character ofsource
is appended todest
starting at the index immediately afterdest
's last character. This effectively concatenatessource
to the end ofdest
.After appending all characters from
source
, a null terminator ('\0'
) is added to the end ofdest
to mark the new end of the concatenated string.In
main()
, two stringsstr1
andstr2
are defined, withstr1
having enough space to hold the concatenated result.concatenateStrings
is called withstr1
andstr2
as arguments.Finally, the concatenated string stored in
str1
is printed to the console usingprintf
.
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>
// Define a structure for a circle
typedef struct
{
double radius;
} Circle;
// Define a structure for a rectangle
typedef struct
{
double length;
double width;
} Rectangle;
// Define a structure for a triangle
typedef struct
{
double base;
double height;
} Triangle;
// Function to calculate the area of a circle
double calculateCircleArea(Circle circle)
{
return 3.14159265359 * circle.radius * circle.radius; // Using the value of pi
}
// Function to calculate the area of a rectangle
double calculateRectangleArea(Rectangle rectangle)
{
return rectangle.length * rectangle.width;
}
// Function to calculate the area of a triangle
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
, andTriangle
, 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>
// Function to count the occurrences of a specific number in an array
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; // Number of elements in the array
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n]; // Declare an array of size n
// Initialize the array with values provided by the user
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
int target; // Number to search for
printf("Enter the number to count: ");
scanf("%d", &target);
// Call the countOccurrences function to count occurrences of the target number
int count = countOccurrences(arr, n, target);
// Display the count to the user
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 arrayarr
, its sizen
, and the target numbertarget
as arguments.The
main
function first asks the user for the number of elementsn
and then declares an arrayarr
of sizen
.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 acount
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>
// Function to reverse the array in-place
void reverseArray(int arr[], int size)
{
int start = 0; // Index of the first element
int end = size - 1; // Index of the last element
while (start < end)
{
// Swap elements at start and end indices
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
// Move indices towards the center
start++;
end--;
}
}
int main()
{
int size;
printf("Enter the size of the array: ");
scanf("%d", &size);
int arr[size]; // Variable-length array declaration
printf("Enter %d elements:\n", size);
for (int i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
// Call the reverseArray function to reverse the array in-place
reverseArray(arr, size);
// Display the reversed array
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
andend
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
andend
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>
// Function to check if an array is a palindrome
int isPalindrome(int arr[], int size)
{
int start = 0; // Index of the first element
int end = size - 1; // Index of the last element
// Continue comparing elements until start is less than or equal to end
while (start <= end)
{
// If elements at start and end are not equal, it's not a palindrome
if (arr[start] != arr[end])
{
return 0; // Not a palindrome
}
// Move indices towards the center
start++;
end--;
}
// If we reach here, the array is a palindrome
return 1; // It's a palindrome
}
int main()
{
int size;
printf("Enter the size of the array: ");
scanf("%d", &size);
int arr[size]; // Variable-length array declaration
printf("Enter %d elements:\n", size);
for (int i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
// Call the isPalindrome function to check if the array is a palindrome
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
andend
, 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
andend
.If at any point the elements at
start
andend
are not equal, the function returns 0, indicating the array is not a palindrome.The loop continues until
start
andend
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;
// Input the number of rows and columns of the matrix
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]; // Transposed matrix with rows and columns swapped
// Input elements of the matrix
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]);
}
}
// Transpose the matrix
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
transposedMatrix[j][i] = matrix[i][j]; // Swap rows and columns
}
}
// Display the original matrix
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");
}
// Display the transposed matrix
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 andtransposedMatrix
for storing the transposed version. The dimensions oftransposedMatrix
are reversed relative tomatrix
.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]
totransposedMatrix[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>
// Function to add two matrices
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;
// Input the number of rows and columns for the matrices
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];
// Input elements of the first matrix
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]);
}
}
// Input elements of the second matrix
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]);
}
}
// Check if the matrices are compatible for addition (same size)
if (rows > 0 && cols > 0)
{
// Call the addMatrices function to add the matrices
addMatrices(matrix1, matrix2, result, rows, cols);
// Display the result matrix
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
, andresult
. 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>
// Function to find and display duplicate elements in an array
void findDuplicates(int arr[], int size)
{
int found[size]; // Array to keep track of found elements (initialized to 0)
// Initialize the found array to 0
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 the current element is equal to any element ahead in the array
if (arr[i] == arr[j] && found[j] != 1)
{
// Display the duplicate element (if not already displayed)
printf("Duplicate element: %d\n", arr[i]);
found[j] = 1; // Mark the element as found to avoid repeating
break; // Once a duplicate is found, no need to check further for this element
}
}
}
}
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]);
}
// Call the findDuplicates function to find and display duplicate elements
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>
// Function to rotate an array to the right by 'n' positions without reversing
void rotateRight(int arr[], int size, int n)
{
// Handle cases where 'n' is larger than the array size
n = n % size;
int temp1, temp2, current, next;
for (int i = 0; i < n; i++)
{
temp1 = arr[size - 1]; // Store the last element
current = size - 1;
for (int j = 0; j < size; j++)
{
next = (current + 1) % size; // Find the new destination index
temp2 = arr[next]; // Store the element at the new destination
arr[next] = temp1; // Insert the stored element
temp1 = temp2; // Update temp1 with the stored element
current = next; // Update current index
}
}
}
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);
// Call the rotateRight function to rotate the array to the right by 'n' positions
rotateRight(arr, size, n);
// Display the rotated array
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
andtemp2
) 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>
// Function to check if an array is sorted in ascending order
bool isSortedAscending(int arr[], int size)
{
for (int i = 1; i < size; i++)
{
// If the current element is greater than the previous element, it's not sorted
if (arr[i] < arr[i - 1])
{
return false;
}
}
// If we reach here, the array is sorted in ascending order
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]);
}
// Call the isSortedAscending function to check if the array is sorted
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>
// Function to insert an element at a specific position in an array
void insertElement(int arr[], int *size, int element, int position)
{
// Check if the position is valid (within the array bounds)
if (position >= 0 && position <= *size)
{
// Shift elements to the right to make space for the new element
for (int i = *size; i > position; i--)
{
arr[i] = arr[i - 1];
}
// Insert the new element at the specified position
arr[position] = element;
// Increment the size of the array
(*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]; // Assuming a maximum size of 100 for the array
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);
// Call the insertElement function to insert the element at the specified position
insertElement(arr, &size, element, position);
// Display the updated array
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
// Define the Point structure with x and y coordinates
typedef struct
{
int x;
int y;
} Point;
// Function to calculate the Euclidean distance between two Point structures
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);
// Call the calculateDistance function to calculate the Euclidean distance
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
andy
, representing the coordinates of a point in 2D space.A function
calculateDistance
is declared to compute the Euclidean distance between two points. It accepts twoPoint
structures as parameters.Inside the function, it calculates the differences in the
x
andy
coordinates between the two points (deltaX
anddeltaY
), then applies the Euclidean distance formula: sqrt((deltaX)^2 + (deltaY)^2).In the
main
function, twoPoint
variables (point1
andpoint2
) 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 nameddistance
.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>
// Define the Student structure with studentId and grade members
struct Student
{
int studentId;
float grade;
};
int main()
{
int numStudents;
printf("Enter the number of students: ");
scanf("%d", &numStudents);
// Create an array of Student structures based on user input
struct Student students[numStudents];
// Input student information
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);
}
// Print student information
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) andgrade
(a floating-point number).In the
main
function, the user is prompted to enter the total number of students, which determines the size of theStudent
array to be created.An array named
students
of theStudent
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>
// Function to swap two numbers using pointers
void swap(int *num1, int *num2)
{
int temp = *num1; // Save the value at address num1 in temp
*num1 = *num2; // Assign the value at address num2 to address num1
*num2 = temp; // Assign the value in temp (original value at num1) to num2
}
int main()
{
int a = 10;
int b = 20;
printf("Before swapping:\n");
printf("a = %d, b = %d\n", a, b);
// Call the swap function with the addresses of a and 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
andint *num2
).Inside the
swap
function, a temporary variabletemp
is used to store the value pointed to bynum1
. Then, the value pointed to bynum2
is assigned to the location pointed to bynum1
. Finally, the value stored intemp
is assigned to the location pointed to bynum2
, completing the swap.In the
main
function, two integer variablesa
andb
are declared and initialized.The program prints the values of
a
andb
before the swap for demonstration purposes.The
swap
function is then called with the addresses ofa
andb
(&a
and&b
) as its arguments.After the swap operation, the program prints the values of
a
andb
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 the maximum number of books in the library
#define MAX_BOOKS 100
// Define the Book structure
typedef struct {
char title[100];
char author[100];
char ISBN[20];
int available; // 1 for available, 0 for checked out
} Book;
// Function prototypes
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() {
// Initialize the library
Book library[MAX_BOOKS];
int numBooks = 0; // Current number of books in the library
// Example book to add
Book exampleBook = {"Example Title", "Example Author", "123-456-789", 1};
addBook(library, &numBooks, exampleBook);
// Check out the first book
if (numBooks > 0) {
printf("\nChecking out the first book...\n");
checkOutBook(&library[0]);
}
// Return the first book
printf("\nReturning the first book...\n");
returnBook(&library[0]);
// Update the first book's details
printf("\nUpdating the first book's details...\n");
updateBookDetails(&library[0], "New Title", "New Author", "987-654-321");
// Display all books in the library
printf("\nLibrary Inventory:\n");
displayLibrary(library, numBooks);
return 0;
}
// Add a new book to the library
void addBook(Book *library, int *numBooks, Book newBook) {
if (*numBooks < MAX_BOOKS) {
library[*numBooks] = newBook; // Add the new book to the array
(*numBooks)++; // Increment the total number of books
printf("New book added to the library.\n");
} else {
printf("Library is full. Cannot add more books.\n");
}
}
// Update a book's details
void updateBookDetails(Book *book, const char *newTitle, const char *newAuthor, const char *newISBN) {
strcpy(book->title, newTitle); // Update title
strcpy(book->author, newAuthor); // Update author
strcpy(book->ISBN, newISBN); // Update ISBN
printf("Book details updated.\n");
}
// Check out a book
void checkOutBook(Book *book) {
if (book->available) {
book->available = 0; // Mark as checked out
printf("Book checked out successfully.\n");
} else {
printf("Book is already checked out.\n");
}
}
// Return a book
void returnBook(Book *book) {
if (!book->available) {
book->available = 1; // Mark as available
printf("Book returned successfully.\n");
} else {
printf("Book is not checked out.\n");
}
}
// Display all books in the library
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 withtitle
,author
,ISBN
, andavailable
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 namedlibrary
with a maximum size defined byMAX_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 thenumBooks
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>
// Recursive function to calculate the factorial of a number
int factorial(int n) {
// Base case: factorial of 0 or 1 is 1
if (n == 0 || n == 1) {
return 1;
}
// Recursive case: n * factorial of (n-1)
return n * factorial(n - 1);
}
int main() {
int num = 5; // Example number
// Calculate and print the factorial of the number
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 integern
. The function uses a simple recursive formula:n! = n * (n-1)!
, with the base cases being0! = 1
and1! = 1
.Recursion: The key concept demonstrated in this program is recursion, where the function
factorial
calls itself with a decremented value ofn
until it reaches the base case.Main Function: In the
main
function, an example numbernum
is defined, and the factorial of this number is computed by calling thefactorial
function. The result is then printed to the console.
Problem Statement 44:
Write a C program to compute the n
th 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 n
th 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>
// Recursive function to calculate the n-th Fibonacci number
int fibonacci(int n) {
// Base cases: Fibonacci(0) = 0, Fibonacci(1) = 1
if (n <= 1) {
return n;
}
// Recursive case: Fibonacci(n) = Fibonacci(n-1) + Fibonacci(n-2)
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int num; // Variable to store the number input by the user
// Prompt the user for the number
printf("Enter a number to find its Fibonacci value: ");
scanf("%d", &num);
// Calculate and display the n-th Fibonacci number
printf("Fibonacci(%d) is %d\n", num, fibonacci(num));
return 0;
}
Explanation:
Fibonacci Function: The program includes a recursive function named
fibonacci
that calculates then
th number in the Fibonacci sequence. This function has two base cases: whenn
is 0, it returns 0, and whenn
is 1, it returns 1. For all other values ofn
, it returns the sum of the two preceding numbers in the sequence, computed by recursively calling itself withn - 1
andn - 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 usingscanf
, calls thefibonacci
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>
// Recursive function to check if a string is a palindrome
bool isPalindrome(char str[], int start, int end) {
// Base case: If the start index is greater than or equal to the end index
if (start >= end) {
return true;
}
// Check if the characters at the start and end are different
if (str[start] != str[end]) {
return false;
}
// Move towards the middle of the string
return isPalindrome(str, start + 1, end - 1);
}
int main() {
char str[] = "racecar"; // Example string to check
// Check if the string is a palindrome
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 stringstr
, and two integers,start
andend
, which represent the indices of the characters currently being compared.Recursion Logic: The function compares the characters at the
start
andend
indices. If these characters are not equal, it immediately returnsfalse
, indicating that the string is not a palindrome. If the characters are equal, the function calls itself withstart
incremented by 1 andend
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 toend
, it means the entire string (or the relevant portion of it) has been checked without finding any mismatched characters, so the function returnstrue
.If the characters at the
start
andend
indices are different, the function returnsfalse
.
Main Function: The
main
function defines a test stringstr
and calls theisPalindrome
function with the initialstart
index of 0 and anend
index ofstrlen(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>
// Recursive function to convert a decimal number to binary
void decimalToBinary(int n) {
// Base case: When n is reduced to 0, the recursion stops
if (n > 0) {
decimalToBinary(n / 2); // Recursive call with n divided by 2
printf("%d", n % 2); // Print the remainder, which represents the binary digit
}
}
int main() {
int decimalNumber = 10; // Example decimal number to convert
// Print the introduction to the binary representation
printf("Binary representation of %d is: ", decimalNumber);
// Call the recursive function to print the binary representation
decimalToBinary(decimalNumber);
// Print a newline character for neatness
printf("\n");
return 0;
}
Explanation:
Recursive Function (
decimalToBinary
): The function takes an integern
as input and prints its binary representation. It works by recursively dividingn
by 2 (shifting right in binary terms) untiln
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 callsdecimalToBinary
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>
// Recursive function to calculate the length of a string
int stringLength(char str[]) {
// Base case: If the first character is the null terminator, return 0
if (str[0] == '\0') {
return 0;
}
// Recursive step: Move to the next character and add 1 to the length
return 1 + stringLength(str + 1);
}
int main() {
char str[] = "Hello, World!"; // Example string
// Calculate and print the length of the string
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 stringstr
and callsstringLength
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-instrlen
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>
// Recursive function to calculate the sum of digits of an integer
int sumOfDigits(int n) {
// Base case: If n is 0, return 0
if (n == 0) {
return 0;
}
// Recursive step: Return the last digit plus the sum of the remaining digits
return n % 10 + sumOfDigits(n / 10);
}
int main() {
int num = 12345; // Example integer
// Calculate and print the sum of the digits of num
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 integern
recursively. It identifies the base case asn
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 ofn
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 fromn
, adding each digit to the cumulative sum untiln
is reduced to 0.Main Function: An example integer
num
is defined in themain
function. ThesumOfDigits
function is then called withnum
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]; // Array to hold user input
int count = 0, i; // Variables for word count and loop control
printf("Enter a string: ");
fgets(str, sizeof(str), stdin); // Read string from user input
str[strcspn(str, "\n")] = 0; // Remove trailing newline character
// Initial check to see if the string starts with a non-space character
if (str[0] != ' ') {
count = 1; // If so, we have at least one word
}
// Loop through the string
for (i = 0; str[i] != '\0'; i++) {
// Check for space followed by a non-space character (indicating the start of a new word)
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, andi
for loop control.It then prompts the user to enter a string, which is read using
fgets()
. This function is chosen overscanf()
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]; // Array to hold the input string
int freq[26] = {0}; // Array to store frequency of each alphabet letter, initialized to 0
int i;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin); // Read string from user input
// Convert each character to lowercase and calculate frequency
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']++;
}
}
// Display the frequency of each character
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 arrayfreq[26]
to hold the frequency of each letter in the alphabet. Thefreq
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 thefreq
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--; // Remove trailing space if exists
input[x] = '\0'; // Null-terminate the modified string
}
int main() {
char str[1000]; // Array to hold the input string
printf("Enter a string: ");
fgets(str, sizeof(str), stdin); // Read string from user input
str[strcspn(str, "\n")] = 0; // Remove trailing newline character
removeExtraSpaces(str); // Function call to remove extra spaces
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 theisspace
function fromctype.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]; // Array to hold the input string
char* start = str; // Pointer to track the start of a word
char* temp = str; // Temporary pointer for iteration
printf("Enter a string: ");
fgets(str, sizeof(str), stdin); // Read string from user input
str[strcspn(str, "\n")] = 0; // Remove trailing newline character
// Loop through the string
while (*temp) {
// Find the start of a word
start = temp;
// Move temp to the end of the word
while (*temp && !isspace(*temp)) {
temp++;
}
// Reverse the word
reverseWord(start, temp - 1);
// If we've reached the end of the string, break
if (!*temp) break;
// Otherwise, skip the space
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
andend
, 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
andtemp
, to iterate through the string.start
marks the beginning of a word, andtemp
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 withstart
andtemp - 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
// Function to reverse any part of the string from start to end
void reverse(char* start, char* end) {
char temp;
while (start < end) {
temp = *start;
*start++ = *end;
*end-- = temp;
}
}
int main() {
char str[1000]; // Array to hold the input string
printf("Enter a string: ");
fgets(str, sizeof(str), stdin); // Read string from user input
str[strcspn(str, "\n")] = 0; // Remove trailing newline character
// Reverse the entire string
reverse(str, str + strlen(str) - 1);
// Reverse each word in the reversed string
char* word_begin = str;
char* temp = str; // Temporary pointer for traversal
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
andend
, 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 pointerword_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 callsreverse
for the word identified byword_begin
andtemp - 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>
// Function to check if the main string contains the substring
int containsSubstring(char* str, char* substr) {
char* pos = strstr(str, substr); // Use strstr to find the substring in the main string
if (pos != NULL) {
return 1; // Substring found
} else {
return 0; // Substring not found
}
}
int main() {
char mainStr[1000]; // Array to hold the main string
char substr[1000]; // Array to hold the substring
printf("Enter the main string: ");
fgets(mainStr, sizeof(mainStr), stdin); // Read the main string
mainStr[strcspn(mainStr, "\n")] = 0; // Remove trailing newline character
printf("Enter the substring: ");
fgets(substr, sizeof(substr), stdin); // Read the substring
substr[strcspn(substr, "\n")] = 0; // Remove trailing newline character
// Check if the main string contains the substring
if (containsSubstring(mainStr, substr)) {
printf("True\n"); // Substring found
} else {
printf("False\n"); // Substring not found
}
return 0;
}
Explanation:
The program defines a function
containsSubstring
that takes two strings as arguments: the main string and the substring. It uses thestrstr
function from the C standard library, which returns a pointer to the first occurrence of the substring in the main string, orNULL
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. Ifstrstr
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.