Basic
Practice Problems based on chapter which you learn in previous Tutorials.
1. Prime number using Interval using Function
#include <stdio.h>
Copy Code
bool
isPrime
(
int
num) {
if
(num <= 1) {
return
false
;
}
for
(
int
i = 2; i * i <= num; i++) {
if
(num % i == 0) {
return
false
;
}
}
return
true
;
}
void
printPrimesInInterval
(
int
start,
int
end) {
printf
("Prime numbers in the interval [%d, %d]: ", start, end);
for
(
int
i = start; i <= end; i++) {
if
(
isPrime
(i)) {
printf
("%d ", i);
}
}
printf
("
");
}
int
main
() {
int
start, end;
printf
("Enter the start of the interval: ");
scanf
("%d", &start);
printf
("Enter the end of the interval: ");
scanf
("%d", &end);
printPrimesInInterval
(start, end);
return
0;
}
This program defines a function isPrime to check whether a given number is prime or not. Then, it defines another function printPrimesInInterval to print prime numbers within a specified interval.
2. Sum of Natural number using Recursion
#include <stdio.h>
Copy Code
int
sumOfNaturalNumbers
(
int
n) {
if
(n == 0) {
return
0;
}
else
{
return
n +
sumOfNaturalNumbers
(n - 1);
}
}
int
main
() {
int
n;
printf
("Enter a positive integer n: ");
scanf
("%d", &n);
if
(n < 0) {
printf
("Please enter a non-negative integer.
");
}
else
{
int
sum =
sumOfNaturalNumbers
(n);
printf
("Sum of first %d natural numbers is %d.
", n, sum);
}
return
0;
}
3. Binary to Decimal using Function
#include <stdio.h>
Copy Code
int
binaryToDecimal
(
long long
binaryNumber) {
int
decimalNumber = 0, i = 0, remainder;
while
(binaryNumber != 0) {
remainder
= binaryNumber % 10;
binaryNumber
/= 10;
decimalNumber
+= remainder *
pow
(2, i);
++i;
}
return
decimalNumber;
}
int
main
() {
long long
binaryNumber;
printf
("Enter a binary number: ");
scanf
("%lld", &binaryNumber);
int
decimalNumber =
binaryToDecimal
(binaryNumber);
printf
("Decimal equivalent: %d
", decimalNumber);
return
0;
}
4. GCD using Recursion
gcd() is a recursive function. It has two parameters i.e. a and b. If b is greater than 0, then a is returned to the main() function. Otherwise, the gcd() function recursively calls itself with the values b and a%b.
#include <stdio.h>
Copy Code
int
gcd
(
int
a,
int
b) {
if
(b == 0) {
return
a;
}
else
{
return
gcd
(b, a % b);
}
}
int
main
() {
int
num1, num2;
printf
("Enter first number: ");
scanf
("%d", &num1);
printf
("Enter second number: ");
scanf
("%d", &num2);
int
result =
gcd
(num1, num2);
printf
("GCD of %d and %d is %d
", num1, num2, result);
return
0;
}