This article will help you with the answers of Problem Solving Through Programming in C NPTEL Week 8 programs.
Week 8 Program 01 Solution
Write a C Program to find HCF of 4 given numbers using recursive function.
#include<stdio.h>
int HCF(int, int); //You have to write this function which calculates the HCF.
int main()
{
int a, b, c, d, result;
scanf("%d %d %d %d", &a, &b, &c, &d); /* Takes 4 number as input from the test data */
result = HCF(HCF(a, b), HCF(c,d));
printf("The HCF is %d", result);
}
int HCF(int c, int d) {
while(c!=d) {
if(c>d)
return HCF(c-d, d);
else
return HCF(c, d-c);
}
return c;
}
Week 8 Program 02 Solution
Write a C Program to find power of a given number using recursion. The number and the power to be calculated is taken from test case.
#include <stdio.h>
long power(int, int);
int main()
{
int pow, num;
long result;
scanf("%d", &num); //The number taken as input from test case data
scanf("%d", &pow); //The power is taken from the test case
result = power(num, pow);
printf("%d^%d is %ld", num, pow, result);
return 0;
}
long power(int n, int p) {
if(p != 0)
return n*power(n, p-1);
else
return 1;
}
Week 8 Program 03 Solution
Write a C Program to print Binary Equivalent of an Integer using Recursion.
#include <stdio.h>
int binary_conversion(int); //function to convert binary to decimal number
int main()
{
int num, bin; //num is the decimal number and bin is the binary equivalent for the number
scanf("%d", &num); //The decimal number is taken from the test case data
bin = binary_conversion(num); //binary number is stored in variable bin
printf("The binary equivalent of %d is %d\n", num, bin);
return 0;
}
int binary_conversion(int n) {
if(n == 0)
return 0;
else
return (n%2)+10*binary_conversion(n/2);
}
Week 8 Program 04 Solution
Write a C program to print a triangle of prime numbers upto given number of lines of the triangle. e.g If number of lines is 3 the triangle will be
2
3 5
7 11 13
#include<stdio.h>
int prime(int num); //Function to find whether the number is prime or not.
int main() {
int lines;
scanf("%d", &lines); //Number of lines of the triangle is taken from test data.
//use the printf statement as printf("%d\t", variable_name); to print the elements in a row
int n=2, p;
for(int i=1; i<=lines; i++) {
for(int j=1; j<=i; j++) {
while(!prime(n))
n++;
printf("%d\t", n);
n++;
}
printf("\n");
}
return 0;
}
int prime(int n) {
int i;
for(i=2; i<n; i++) {
if(n%i==0)
break;
}
if(i==n)
return 1;
else
return 0;
}
For discussion about any question, join the below comment section. And get the solution of your query. Also, try to share your thoughts about the topics covered in this particular quiz.