Let's learn about 'C Programming' with practical questions along with their explanations.
[Programming] Question 1: Find the largest number among the three numbers
in C?
|
Learn how
to write a C program to find the largest number among three given numbers.
This tutorial walks you through the process of comparing three integers and
identifying the largest one using basic conditional statements. Ideal for
beginners looking to understand fundamental programming concepts in C. #include
<stdio.h> int main() { int num1, num2, num3; printf("Enter three
numbers: "); scanf("%d %d %d",
&num1, &num2, &num3); if (num1 >= num2 &&
num1 >= num3) printf("%d
is the largest number.\n", num1); else if (num2 >= num1
&& num2 >= num3) printf("%d
is the largest number.\n", num2); else printf("%d
is the largest number.\n", num3); return 0; } Explanation: Inside the
main() function: - Three integer variables num1, num2, and num3 are declared
to store the user's input. - The user is
prompted to enter three numbers using printf. - The scanf
function reads the three numbers entered by the user. - Conditional
statements (if, else if, else) are used to compare the numbers and find the
largest one. - The largest number is printed to the console using printf. |
[Programming] Question 2: Find the sum of all elements in an array in C?
|
Learn how
to write a C program to calculate the sum of all elements in an array. This
guide provides a clear explanation of how to initialize an array, iterate
through its elements, and compute the total sum. Perfect for beginners
looking to understand array manipulation and basic programming operations in
C. #include
<stdio.h> int main() { int arr[] = {1, 2, 3, 4, 5}; int sum = 0; int i; for (i = 0; i <
sizeof(arr)/sizeof(arr[0]); i++) { sum += arr[i]; } printf("Sum of array
elements: %d\n", sum); return 0; } Explanation: Inside the
main() function: - An
integer array arr is declared and initialized with values. - An integer
variable sum is initialized to zero to store the sum of array elements. - A for loop
is used to iterate through each element of the array. - Within the
loop, each element of the array is added to the sum. - Finally,
the sum of array elements is printed to the console. |
[Programming] Question 3: Find the largest element in an array in C?
|
Learn how
to write a C program to find the largest element in an array. This tutorial
demonstrates how to traverse an array, compare its elements, and identify the
largest one. Ideal for those new to C programming and looking to enhance
their skills in array handling and basic algorithms. #include
<stdio.h> int main() { int arr[] = {10, 20, 30, 40,
50}; int max = arr[0]; int i; for (i = 1; i <
sizeof(arr)/sizeof(arr[0]); i++) { if (arr[i] >
max) max
= arr[i]; } printf("Largest element in
array: %d\n", max); return 0; } Explanation: Inside the
main() function: - An integer
array arr is declared and initialized with values. - An integer
variable max is initialized to the first element of the array. - A for loop
is used to iterate through each element of the array, starting from the
second element. - Within the
loop, if the current element is greater than the current maximum, update max
to the current element. - Finally,
the largest element in the array is printed to the console. |
[Programming] Question 4: Find the smallest element in an array in C?
|
Explore how
to write a C program to find the smallest element in an array. This guide
provides a detailed explanation on initializing an array, iterating through
its elements, and identifying the smallest value. Perfect for beginners
looking to understand array operations and basic programming techniques in C. #include
<stdio.h> int main() { int arr[] = {10, 20, 5, 40, 50}; int min = arr[0]; int i; for (i = 1; i <
sizeof(arr)/sizeof(arr[0]); i++) { if (arr[i] <
min) min
= arr[i]; } printf("Smallest element in
array: %d\n", min); return 0; } Explanation: Inside the
main() function: - An integer
array arr is declared and initialized with values. - An integer
variable min is initialized to the first element of the array. - A for loop
is used to iterate through each element of the array, starting from the
second element. - Within the
loop, if the current element is smaller than the current minimum, update min
to the current element. - Finally,
the smallest element in the array is printed to the console. |
[Programming] Question 5: Find the average of all elements in an array in
C?
|
Learn how
to write a C program to calculate the average of all elements in an array.
This tutorial walks you through the process of summing the elements of an
array, computing the average, and handling arrays in C. Ideal for those
looking to understand basic array operations and arithmetic in C programming. #include
<stdio.h> int main() { int arr[] = {1, 2, 3, 4, 5}; int sum = 0; int avg; int i; for (i = 0; i <
sizeof(arr)/sizeof(arr[0]); i++) { sum += arr[i]; } avg = sum /
sizeof(arr)/sizeof(arr[0]); printf("Average of array
elements: %d\n", avg); return 0; } Explanation: Inside the
main() function: - An integer
array arr is declared and initialized with values. - An integer
variable sum is initialized to zero to store the sum of array elements. - An integer
variable avg is declared to store the average. - A for loop
is used to iterate through each element of the array. - Within the
loop, each element of the array is added to the sum. - After the
loop, the average is calculated by dividing the sum by the number of elements
in the array. - Finally,
the average of array elements is printed to the console. |
[Programming] Question 6: Calculate the factorial of a number in C?
Learn how to write a C program to calculate the factorial of a number. This guide explains how to implement iterative methods for computing the factorial, including detailed examples and explanations. Ideal for beginners who want to understand fundamental concepts in C programming and factorial computation.
#include <stdio.h>
int main() {
int n, i;
unsigned long long factorial = 1;
printf("Enter a positive integer: ");
scanf("%d", &n);
for (i = 1; i <= n; ++i) {
factorial *= i;
}
printf("Factorial of %d = %llu\n", n, factorial);
return 0;
} Explanation: Inside the main() function:
- An integer variable n is declared to store the input number.
- An unsigned long long variable factorial is initialized to 1 to store the factorial value.
- The user is prompted to enter a positive integer.
- A for loop is used to iterate from 1 to the entered number.
- Within the loop, each number is multiplied to the factorial variable.
- Finally, the factorial of the entered number is printed to the console.
[Programming] Question 7: Calculate Greatest Common Divisor (GCD) of two numbers in C?
Learn how to write a C program to calculate the Greatest Common Divisor (GCD) of two numbers. This tutorial covers recursive approach using Euclidean algorithm for finding the GCD, providing clear examples and explanations. Perfect for those new to C programming and looking to grasp fundamental mathematical algorithms.
#include <stdio.h>
int gcd(int a, int b) {
if (b == 0)
return a;
else
return gcd(b, a % b);
}
int main() {
int num1, num2;
printf("Enter two positive integers: ");
scanf("%d %d", &num1, &num2);
printf("GCD of %d and %d is %d.\n", num1, num2, gcd(num1, num2));
return 0;
} Inside the gcd function:
- Recursive implementation of Euclidean algorithm to find the GCD of two numbers.
Inside the main() function:
- Two integer variables num1 and num2 are declared to store the input numbers.
- The user is prompted to enter two positive integers.
- The gcd function is called with the two numbers as arguments, and the result is printed.
[Programming] Question 8: Calculate Least Common Multiple (LCM) of two numbers in C?
Learn how to write a C program to calculate the Least Common Multiple (LCM) of two numbers. This guide explains how to use the relationship between GCD and LCM to compute the LCM efficiently. It includes step-by-step instructions, sample code, and explanations of key concepts. Ideal for beginners who want to understand basic number theory and programming techniques in C.
#include <stdio.h>
int gcd(int a, int b) {
if (b == 0)
return a;
else
return gcd(b, a % b);
}
int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
int main() {
int num1, num2;
printf("Enter two positive integers: ");
scanf("%d %d", &num1, &num2);
printf("LCM of %d and %d is %d.\n", num1, num2, lcm(num1, num2));
return 0;
} Inside the gcd function:
- Recursive implementation of Euclidean algorithm to find the GCD of two numbers.
Inside the lcm function:
- Calculates the LCM using the formula: (a * b) / gcd(a, b)
Inside the main() function:
- Two integer variables num1 and num2 are declared to store the input numbers.
- The user is prompted to enter two positive integers.
- The lcm function is called with the two numbers as arguments, and the result is printed.
[Programming] Question 9: Generate Fibonacci series in C?
Learn how to write a C program to generate the Fibonacci series. This tutorial explains how to calculate and print Fibonacci numbers using iterative approach. It includes clear examples and code snippets to help you understand the logic behind the Fibonacci sequence and implement it effectively in C.
#include <stdio.h>
int main() {
int n, first = 0, second = 1, next, i;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: \n");
for (i = 0; i < n; i++) {
printf("%d, ", first);
next = first + second;
first = second;
second = next;
}
return 0;
}
Inside the main() function:
- An integer variable n is declared to store the number of terms in the Fibonacci series.
- Integer variables first and second are initialized to 0 and 1, respectively, as the first two terms of the series.
- An integer variable next is declared to calculate the next term in the series.
- The user is prompted to enter the number of terms.
- The Fibonacci series is generated using a for loop.
- Within the loop, each term is printed, and the values of first, second, and next are updated to generate the next term.
[Programming] Question 10: Demonstrate the use of left shift operator in C?
Explore how to use the left shift operator (<<) in C with this comprehensive guide. Learn how the operator shifts the bits of a number to the left, effectively multiplying the number by powers of two. This tutorial includes clear explanations, practical examples, and code snippets to help you understand the application of the left shift operator in various programming scenarios.
#include <stdio.h>
int main() {
int num = 5;
printf("Original number: %d\n", num);
num = num << 2; // Left shifting the number by 2 bits
printf("After left shift by 2: %d\n", num);
return 0;
} Inside the main() function:
- An integer variable num is initialized with the value 5.
- The original value of num is printed to the console.
- The num variable is left shifted by 2 bits using the `<<` operator.
- The result after left shift is printed to the console.
[Programming] Question 11: Demonstrate the use of right shift operator in C?
Learn how to use the right shift operator (>>) in C with this detailed guide. This tutorial demonstrates how the operator shifts the bits of a number to the right, effectively dividing the number by powers of two. It includes clear explanations, practical examples, and code snippets to help you grasp the concept and apply the right shift operator effectively in your C programs.
#include <stdio.h>
int main() {
int num = 20;
printf("Original number: %d\n", num);
num = num >> 2; // Right shifting the number by 2 bits
printf("After right shift by 2: %d\n", num);
return 0;
}
Inside the main() function:
- An integer variable num is initialized with the value 20.
- The original value of num is printed to the console.
- The num variable is right shifted by 2 bits using the `>>` operator.
- The result after right shift is printed to the console.
[Programming] Question 12: Demonstrate multiplication by powers of 2 using left shift operator in C?
#include <stdio.h>
int main() {
int num = 5;
printf("Original number: %d\n", num);
num = num << 3; // Multiply by 2^3 = 8
printf("After multiplication by 8: %d\n", num);
return 0;
} Inside the main() function:
- An integer variable num is initialized with the value 5.
- The original value of num is printed to the console.
- The num variable is left shifted by 3 bits using the `<<` operator, effectively multiplying it by 8 (2^3).
- The result after multiplication is printed to the console.
[Programming] Question 13: Demonstrate division by powers of 2 using right shift operator in C?
Learn how to efficiently divide integers by powers of 2 using the right shift operator (>>) in C. This guide explains how shifting the bits of a number to the right effectively performs division by powers of 2, offering a faster alternative to traditional division operations. The tutorial includes clear examples, step-by-step explanations, and sample code to help you understand and apply this technique in your C programs.
#include <stdio.h>
int main() {
int num = 32;
printf("Original number: %d\n", num);
num = num >> 2; // Divide by 2^2 = 4
printf("After division by 4: %d\n", num);
return 0;
}Inside the main() function:
- An integer variable num is initialized with the value 32.
- The original value of num is printed to the console.
- The num variable is right shifted by 2 bits using the `>>` operator, effectively dividing it by 4 (2^2).
- The result after division is printed to the console.
[Programming] Question 14: Write a Program to check whether a number is prime or not
Learn how to write a C program to determine whether a given number is prime. This guide provides a step-by-step explanation of how to implement a function that checks for primality by testing divisibility from 2 up to the square root of the number. The tutorial includes sample code, explanations of the logic used, and tips for optimizing the program.
#include <stdio.h>
int main() {
int num, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &num);
for (i = 2; i <= num / 2; ++i) {
if (num % i == 0) {
flag = 1;
break;
}
}
if (num == 1) {
printf("1 is neither prime nor composite.\n");
}
else {
if (flag == 0)
printf("%d is a prime number.\n", num);
else
printf("%d is not a prime number.\n", num);
}
return 0;
} Inside the main() function:
- An integer variable num is declared to store the input number.
- The user is prompted to enter a positive integer.
- A for loop is used to iterate from 2 to num/2.
- Within the loop, it checks if the number is divisible by any number other than 1 and itself.
- If the number is prime, it sets flag to 0, otherwise to 1.
- Finally, it prints whether the number is prime or not based on the value of flag.
[Programming] Question 15: Write a C program to calculate Compound Interest
Learn how to write a C program to calculate compound interest. This guide explains how to implement the formula for compound interest, which includes principal amount, interest rate, number of times interest is compounded per year, and the total number of years. The tutorial includes sample code, explanations of the formula used, and tips for accurate calculations.
#include <stdio.h>
#include <math.h>
int main() {
float principal, rate, time, compoundInterest;
printf("Enter principal amount: ");
scanf("%f", &principal);
printf("Enter rate of interest: ");
scanf("%f", &rate);
printf("Enter time in years: ");
scanf("%f", &time);
compoundInterest = principal * (pow((1 + rate / 100), time)) - principal;
printf("Compound Interest = %.2f\n", compoundInterest);
return 0;
} Inside the main() function:
- Float variables principal, rate, time, and compoundInterest are declared to store principal amount, rate of interest, time, and compound interest respectively.
- The user is prompted to enter the principal amount, rate of interest, and time.
- Compound interest is calculated using the formula: CI = P * (1 + R/100)^T - P.
- The calculated compound interest is printed to the console.
[Programming] Question 17: Write a Program to Replace all 0's with 1's in a Number
Learn how to write a C program to replace all occurrences of 0 with 1 in a given number. This guide provides a step-by-step approach to modifying the digits of an integer, using mathematical operations to achieve the desired result. The tutorial includes clear explanations, sample code, and tips for handling different scenarios. Ideal for those looking to manipulate and process numeric data in C.
#include <stdio.h>
int main() {
int num, remainder, result = 0, multiplier = 1;
printf("Enter a number: ");
scanf("%d", &num);
while (num > 0) {
remainder = num % 10;
if (remainder == 0)
remainder = 1;
result += remainder * multiplier;
num /= 10;
multiplier *= 10;
}
printf("Number after replacing 0's with 1's: %d\n", result);
return 0;
} Inside the main() function:
- Integer variables `num`, `remainder`, `result`, and `multiplier` are declared to store the input number, remainder, result after replacement, and multiplier respectively.
- The user is prompted to enter a number.
- Using a while loop, each digit of the number is extracted from right to left.
- If the digit is 0, it is replaced with 1.
- The result is updated by adding the modified digit multiplied by the corresponding place value.
- Finally, the number after replacing 0's with 1's is printed to the console.
[Programming] Question 18: Write a Program to convert the binary number into a decimal number
Learn how to write a C program to convert a binary number into its decimal equivalent. This guide provides a step-by-step explanation of how to process a binary number, compute its decimal value using bitwise operations or mathematical calculations, and output the result. The tutorial includes sample code and detailed instructions to help you understand and implement the conversion effectively in C.
#include <stdio.h>
int main() {
long long binaryNumber;
int decimalNumber = 0, i = 0, remainder;
printf("Enter a binary number: ");
scanf("%lld", &binaryNumber);
while (binaryNumber != 0) {
remainder = binaryNumber % 10;
binaryNumber /= 10;
decimalNumber += remainder * pow(2, i);
++i;
}
printf("Decimal equivalent: %d\n", decimalNumber);
return 0;
} Inside the main() function:
- A long long variable `binaryNumber` is declared to store the binary number entered by the user.
- Integer variables `decimalNumber`, `i`, and `remainder` are declared to store the equivalent decimal number, index, and remainder respectively.
- The user is prompted to enter a binary number.
- Using a while loop, each digit of the binary number is extracted from right to left.
- For each digit, the decimal equivalent is calculated using the formula: `decimalNumber += remainder * pow(2, i)`.
- Finally, the decimal equivalent is printed to the console.
[Programming] Question 19: Write a Program to check if the year is a leap year or not
Learn how to write a C program to determine whether a given year is a leap year or not. This guide explains the rules for identifying leap years (divisible by 4 but not by 100, unless also divisible by 400) and how to implement these rules in code. The tutorial includes step-by-step instructions, sample code, and explanations to help you accurately perform this check in C.
#include <stdio.h>
int main() {
int year;
printf("Enter a year: ");
scanf("%d", &year);
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
printf("%d is a leap year.\n", year);
else
printf("%d is not a leap year.\n", year);
return 0;
} Inside the main() function:
- An integer variable `year` is declared to store the year entered by the user.
- The user is prompted to enter a year.
- Using conditional statements, it checks whether the year is divisible by 4 but not divisible by 100, or divisible by 400.
- If the condition is true, it prints that the year is a leap year; otherwise, it prints that the year is not a leap year.
[Programming] Question 20: Write a Program to Check if a number is an Armstrong number or not
#include <stdio.h>
int main() {
int num, originalNum, remainder, result = 0, n = 0;
printf("Enter an integer: ");
scanf("%d", &num);
originalNum = num;
// store the number of digits of num in n
while (originalNum != 0) {
originalNum /= 10;
++n;
}
originalNum = num;
// check if the number is Armstrong
while (originalNum != 0) {
remainder = originalNum % 10;
result += pow(remainder, n);
originalNum /= 10;
}
if (result == num)
printf("%d is an Armstrong number.\n", num);
else
printf("%d is not an Armstrong number.\n", num);
return 0;
} Inside the main() function:
- Integer variables `num`, `originalNum`, `remainder`, `result`, and `n` are declared to store the input number, its original value, remainders, result after calculation, and number of digits respectively.
- The user is prompted to enter an integer.
- The number of digits of the input number is calculated and stored in `n`.
- Using a while loop, the sum of nth power of individual digits is calculated.
- If the calculated result is equal to the original number, it is an Armstrong number; otherwise, it is not.
- The program prints the result accordingly.
[Programming] Question 22: Write a program to Find all the roots of a quadratic equation in C
#include <stdio.h>
#include <math.h>
int main() {
float a, b, c, discriminant, root1, root2, realPart, imaginaryPart;
printf("Enter coefficients a, b, and c: ");
scanf("%f %f %f", &a, &b, &c);
discriminant = b * b - 4 * a * c;
if (discriminant > 0) {
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("Roots are real and different.\n");
printf("Root1 = %.2f\n", root1);
printf("Root2 = %.2f\n", root2);
}
else if (discriminant == 0) {
root1 = root2 = -b / (2 * a);
printf("Roots are real and same.\n");
printf("Root1 = Root2 = %.2f\n", root1);
}
else {
realPart = -b / (2 * a);
imaginaryPart = sqrt(-discriminant) / (2 * a);
printf("Roots are complex and different.\n");
printf("Root1 = %.2f + %.2fi\n", realPart, imaginaryPart);
printf("Root2 = %.2f - %.2fi\n", realPart, imaginaryPart);
}
return 0;
} Inside the main() function:
- Float variables `a`, `b`, `c`, `discriminant`, `root1`, `root2`, `realPart`, and `imaginaryPart` are declared to store the coefficients of the quadratic equation, discriminant, roots, real part, and imaginary part respectively.
- The user is prompted to enter the coefficients of the quadratic equation.
- Discriminant is calculated using the formula b^2 - 4ac.
- Based on the value of discriminant, the nature of roots (real, equal, or complex) is determined and printed along with the roots.
[Programming] Question 23: Write a Program to reverse a number
#include <stdio.h>
int main() {
int num, reversedNumber = 0, remainder;
printf("Enter an integer: ");
scanf("%d", &num);
while (num != 0) {
remainder = num % 10;
reversedNumber = reversedNumber * 10 + remainder;
num /= 10;
}
printf("Reversed number = %d\n", reversedNumber);
return 0;
} Inside the main() function:
- Integer variables `num`, `reversedNumber`, and `remainder` are declared to store the input number, reversed number, and remainders respectively.
- The user is prompted to enter an integer.
- Using a while loop, the number is reversed digit by digit by extracting each digit using the modulus operator and adding it to the reversedNumber after multiplying it by 10.
- Finally, the reversed number is printed to the console.
[Programming] Question 26: Write a C program to find the GCD of two numbers
#include <stdio.h>
int main() {
int num1, num2, i, gcd;
printf("Enter two positive integers: ");
scanf("%d %d", &num1, &num2);
for(i=1; i <= num1 && i <= num2; ++i) {
// Check if i is a factor of both num1 and num2
if(num1 % i == 0 && num2 % i == 0)
gcd = i;
}
printf("GCD of %d and %d is %d\n", num1, num2, gcd);
return 0;
} Inside the main() function:
- Integer variables `num1`, `num2`, `i`, and `gcd` are declared to store the input numbers, loop iterator, and the greatest common divisor respectively.
- The user is prompted to enter two positive integers.
- A for loop iterates from 1 up to the smaller of the two numbers.
- Within the loop, it checks if the current value of `i` is a factor of both `num1` and `num2`.
- If it is, `i` is assigned to `gcd`.
- Finally, the program prints the greatest common divisor.
[Programming] Question 27: Write a C program to find the LCM of two numbers
#include <stdio.h>
int main() {
int num1, num2, max;
printf("Enter two positive integers: ");
scanf("%d %d", &num1, &num2);
// Find maximum of two numbers
max = (num1 > num2) ? num1 : num2;
// Loop until both conditions become false
while(1) {
if(max % num1 == 0 && max % num2 == 0) {
printf("LCM of %d and %d is %d\n", num1, num2, max);
break;
}
++max;
}
return 0;
} Inside the main() function:
- Integer variables `num1`, `num2`, and `max` are declared to store the input numbers and the maximum of the two numbers.
- The user is prompted to enter two positive integers.
- The maximum of the two numbers is determined using a ternary operator.
- A while loop iterates indefinitely.
- Within the loop, it checks if the current value of `max` is divisible by both `num1` and `num2`.
- If it is, it prints the least common multiple (LCM) and breaks out of the loop.
- If not, it increments `max` and continues the loop.