C Program To Find Sum of Squares of Digits using Recursion

Write a C program to find sum of squares of digits of a positive integer number input by the user, using recursive function.

Example:

If user inputs num value as 123. Then we fetch the individual digits present in 123 i.e., 3, 2 and 1, square it and add it to get the final result.

i.e., (3 x 3) + (2 x 2) + (1 x 1) = 14.

So, sum of squares of digits of 123 is 14.

Video Tutorial: C Program To Find Sum of Squares of Digits using Recursion


[youtube https://www.youtube.com/watch?v=7YaJ2pIkzKc]

YouTube Link: https://www.youtube.com/watch?v=7YaJ2pIkzKc [Watch the Video In Full Screen.]

Source Code: C Program To Find Sum of Squares of Digits using Recursion

#include<stdio.h>

int square(int num)
{
    if(num == 0)
        return 0;
    else
        return( (num%10) * (num%10) + square(num/10) );
}

int main()
{
    int num;

    printf("Enter a positive integer number:\n");
    scanf("%d", &num);

    printf("Sum of squares of digits of %d is %d.\n", num, square(num));

    return 0;
}

Output:
Enter a positive integer number:
123
Sum of squares of digits of 123 is 14.

Source Code: C Program To Find Sum of Squares of Digits using Recursion and pow() method

#include<stdio.h>
#include<math.h>

int square(int num)
{
    if(num == 0)
        return 0;
    else
        return( pow((num%10), 2) + square(num/10) );
}

int main()
{
    int num;

    printf("Enter a positive integer number:\n");
    scanf("%d", &num);

    printf("Sum of squares of digits of %d is %d.\n", num, square(num));

    return 0;
}

Output:
Enter a positive integer number:
123
Sum of squares of digits of 123 is 14.

Here we are making use of pow() method present inside math.h library file. pow() takes base value as first argument and exponent value as its second argument.

Source Code: C Program To Find Sum of Squares of Digits using Recursion, Ternary/Conditional Operator and pow() method

#include<stdio.h>
#include<math.h>

int square(int);

int main()
{
    int num;

    printf("Enter a positive integer number:\n");
    scanf("%d", &num);

    printf("Sum of squares of digits of %d is %d.\n", num, square(num));

    return 0;
}

int square(int num)
{
    return( (num == 0) ? 0 : ( pow((num % 10), 2) + square(num/10) ));
}

Output 1:
Enter a positive integer number:
123
Sum of squares of digits of 123 is 14.

Output 2:
Enter a positive integer number:
2103
Sum of squares of digits of 2103 is 14.

Output 3:
Enter a positive integer number:
456
Sum of squares of digits of 456 is 77.

Output 4:
Enter a positive integer number:
2020
Sum of squares of digits of 2020 is 8.

Output 5:
Enter a positive integer number:
2021
Sum of squares of digits of 2021 is 9.

To know more about Ternary or Conditional Operator visit:
Ternary Operator / Conditional Operator In C.

Dry Run: Example

Lets assume that user has input num value as 123.

num(num%10)2num/10(num%10)2+square(num/10)
123(3)2129+square(12)
12(2)214+square(1)
1(1)201+square(0)

Value Returning – Control Shifting back.

Return ValueToResult
return 0;square(0)1+0=1
1square(1)4+1=5
5square(12)9+5=14

So, sum of squares of digits of 123 is 14.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Count Prime Numbers Between Range

Lets write a C program to count prime numbers between user entered/input range of numbers, using function/method.

Prime Number: is a natural number greater than 1, which has no positive divisors other than 1 and itself.

Related Read:
C Program To Find Prime Number or Not using For Loop

Video Tutorial: C Program To Count Prime Numbers Between Range


[youtube https://www.youtube.com/watch?v=vY6HFMblBJY]

YouTube Link: https://www.youtube.com/watch?v=vY6HFMblBJY [Watch the Video In Full Screen.]

Source Code: C Program To Count Prime Numbers Between Range

#include<stdio.h>
#include<math.h>

int isPrime(int num)
{
    int inum = sqrt(num), prime = 1, count;

    for(count = 2; count <= inum; count++)
    {
         if(num % count == 0)
         {
            prime = 0;
            break;
         }
    }

    return(prime);
}

int main()
{
    int start, end, temp, num, slno = 0, on_off;

    printf("Enter start and end value\n");
    scanf("%d%d", &start, &end);

    printf("Do you want to print prime numbers? (yes = 1, no = 0)\n");
    scanf("%d", &on_off);

    if(start > end)
    {
        temp  = start;
        start = end;
        end   = temp;
    }

    if(on_off)
        printf("\nPrime numbers between %d and %d are:\n\n", start, end);

    for(num = start; num <= end; num++)
    {
        if(num == 1)
        {
            continue;
        }

        if( isPrime(num) )
        {
            slno++;

            if(on_off)
            {
                printf("%d. %d is prime number.\n", slno, num);
            }
         }
    }

    printf("\nThere are %d prime numbers between %d and %d.\n", 
             slno, start, end);

    return 0;
}

Output 1:
Enter start and end value
10
30
Do you want to print prime numbers? (yes = 1, no = 0)
1

Prime numbers between 10 and 30 are:

1. 11 is prime number.
2. 13 is prime number.
3. 17 is prime number.
4. 19 is prime number.
5. 23 is prime number.
6. 29 is prime number.

There are 6 prime numbers between 10 and 30.

Output 2:
Enter start and end value
10
30
Do you want to print prime numbers? (yes = 1, no = 0)
0

There are 6 prime numbers between 10 and 30.

Output 3:
Enter start and end value
1
10
Do you want to print prime numbers? (yes = 1, no = 0)
1

Prime numbers between 1 and 10 are:

1. 2 is prime number.
2. 3 is prime number.
3. 5 is prime number.
4. 7 is prime number.

There are 4 prime numbers between 1 and 10.

Output 4:
Enter start and end value
1
300
Do you want to print prime numbers? (yes = 1, no = 0)
0

There are 62 prime numbers between 1 and 300.

Output 5:
Enter start and end value
1
1000
Do you want to print prime numbers? (yes = 1, no = 0)
0

There are 168 prime numbers between 1 and 1000.

Logic To Count Prime Numbers Between Range

First we ask the user to enter the range and store it inside address of variables start and end. We make sure that start value is less than end value. If start value is greater than end value, we use a temporary variable to swap the values of start and end.

Swap 2 Numbers Using a Temporary Variable: C

Next we ask the user if he / she wants to display the prime numbers between the range or just want to know the count of prime numbers between the entered range. We store the user answer in a variable called on_off.

We start the for loop: We initialize the loop counter variable num to start and iterate through the loop until num is less than or equal to end. For each iteration of the for loop we increment the value of num by 1. This for loop selects number one by one from start to end. And this selected number, which is present inside variable num is checked for prime or not. If its prime we display it to the console window and keep track of the count of prime numbers, if not we simply ignore that non-prime number.

We use a function to check if the selected number present in variable num is a prime number or not. We call the function/method isPrime() inside if condition and pass the value of num to it. isPrime() returns 1 or 0 value. 1 means true and 0 means false. So if isPrime() returns 1, then the if condition becomes true and we increment the value of slno by 1 and optionally printout the prime number. If isPrime() returns 0, then we simply ignore it and go to the next number.

isPrime() function has the logic to determine if the given number is prime or not. We have explained the complete logic of this in a separate video tutorial, link to which is present below.

C Program To Find Prime Number or Not using For Loop

Note:
1. We are including math.h header file or library file since we are using sqrt() builtin method. sqrt() method is present inside math.h file.

2. We are also using continue and break keywords in our program and we’ve explained about it in detail in separate videos. Please watch them for more clarity about the topic.

Continue Statement In C Programming Language
break Statement In C Programming Language

Stay subscribed to our blog and YouTube channel. Thank you ..

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Calculate One Number Raised To Another using Function

Write a function power( a, b ), to calculate the value of a raised to b.

Note: In today’s video tutorial lets see 2 methods of calculating value of a raised to b.
1. In first method lets write the entire logic ourselves.
2. In second method lets use the built in method pow() which is present in math.h library file.

Problem Statement

To clarify, the problem statement is: User inputs two numbers through the keyboard. Write a C program to find the value of one number raised to the power of another, using function / method.

Related Read:
Function / Methods In C Programming Language
Calculate Power of a Number: C Program
Calculate Power of a Number using pow(): C Program

Video Tutorial: C Program To Calculate One Number Raised To Another using Function


[youtube https://www.youtube.com/watch?v=NN_m-I_2auE]

YouTube Link: https://www.youtube.com/watch?v=NN_m-I_2auE [Watch the Video In Full Screen.]


Source Code: C Program To Calculate One Number Raised To Another using Function

#include<stdio.h>

int power(int base, int exp)
{
    int count, result = 1;

    for(count = 1; count <= exp; count++)
    {
        result = result * base;
    }

    return(result);
}

int main()
{
    int a, b;

    printf("Enter integer values for base and exponent\n");
    scanf("%d%d", &a, &b);

    printf("%d to the power of %d is %d\n", a, b, power(a, b));

    return 0;
}

Output 1:
Enter integer values for base and exponent
2
4
2 to the power of 4 is 16

Output 2:
Enter integer values for base and exponent
3
2
3 to the power of 2 is 9

Output 3:
Enter integer values for base and exponent
5
2
5 to the power of 2 is 25

Output 4:
Enter integer values for base and exponent
5
3
5 to the power of 3 is 125

Logic

In above code, we ask the user to enter base and exponent values. We pass these 2 values to function power(). Inside power() function/method, we use for loop to multiply the value of base exponent number of times. This would give us the result and we return the result.

Example: In above code, if the user inputs 2 as base and 4 as exponent, then: for loop executes or iterates exponent number of times i.e., 4 times in our case. So 2 is multiplied 4 times.

2 x 2 x 2 x 2 = 16.

Source Code: C Program To Calculate One Number Raised To Another using Function and builtin method pow()

#include<stdio.h>
#include<math.h>

float power(int base, int exp)
{
    return( pow(base, exp) );
}

int main()
{
    int a, b;

    printf("Enter integer values for base and exponent\n");
    scanf("%d%d", &a, &b);

    printf("%d to the power of %d is %0.2f\n", a, b, power(a, b));

    return 0;
}

Output 1:
Enter integer values for base and exponent
2
4
2 to the power of 4 is 16

Output 2:
Enter integer values for base and exponent
3
2
3 to the power of 2 is 9

Output 3:
Enter integer values for base and exponent
5
2
5 to the power of 2 is 25

Output 4:
Enter integer values for base and exponent
5
3
5 to the power of 3 is 125

Logic

Here we ask the user to enter the value of base and exponent. We pass the values of base and exponent to power() method. Inside power() method we use pow() builtin method which is present in math.h header file. We pass base and exponent value to pow() function and it returns the result, which we return to calling function i.e., main method.

Note:
pow() method is present in math.h library, so we include it at the top of our c source code.

Important Note: Note that we are using float as return type in above program(second method), since built in method pow() returns floating point or double type data. If we use integer type data as return type then it would give wrong results for certain inputs.

For example, if you have below code for power() function

int power(int base, int exp)
{
    return( pow(base, exp) );
}

If would return 24 for 5 raise to 2. And 124 as result for 5 raise to 3. Both these results are wrong.

Important Note: As you might have observed already we are not using function prototype in above programs. That is because we are writing function definition at the top before main function from where we are calling power() function. So main method already knows that there is a method called power() in our program.

If we want to write more than 1 function and we need to arrange it properly, we can write function prototype at the top – so that we can know about the functions present in our program in one glance, in one place. And then we can write the function definition anywhere in our program, in any order. Function prototype and function definition orders do not matter.

Also note that, writing function prototype is optional if you write function definition before main.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Find Prime Number or Not using For Loop

Lets write a C program to check whether user input number is prime number or not, using for loop.

Prime Number: is a natural number greater than 1, which has no positive divisors other than 1 and itself.

Related Read:
For Loop In C Programming Language
if else statement in C
break Statement In C Programming Language

In this video tutorial we’re illustrating 3 methods to find if the user entered number is prime number or not.

For loop Logic

All the numbers are perfectly divisible by number 1, so we initialize the variable count to 2. So our c program starts checking for divisibility from number 2.

Video Tutorial: C Program To Find Prime Number or Not using For Loop


[youtube https://www.youtube.com/watch?v=FzHHB5EqNA0]

YouTube Link: https://www.youtube.com/watch?v=FzHHB5EqNA0 [Watch the Video In Full Screen.]

Method 1 Source Code: Prime Number or Not

#include<stdio.h>

int main()
{
    int num, count, prime = 1;

    printf("Enter a positive number\n");
    scanf("%d", &num);

    for(count = 2; count < num; count++)
    {
        if(num % count == 0)
        {
            prime = 0;
            break;
        }
    }

    if(prime)
        printf("%d is a Prime Number\n", num);
    else
        printf("%d is a not Prime Number\n", num);

    return 0;
}

Output 1:
Enter a number
7
7 is prime number

Output 2:
Enter a number
10
10 is not prime number

Logic: Method 1

We ask the user to enter a positive number and store it in variable num. Using for loop we start dividing the user entered number from 2 to num-1 times. If any number from 2 to num-1 perfectly divide the user entered number, then it’s not a prime number. We assign value 0 to variable prime and break out of the loop and print the message to the user.

Method 2 Source Code: Prime Number or Not: Divide By 2

#include<stdio.h>

int main()
{
    int num, count, prime = 1, inum;

    printf("Enter a positive number\n");
    scanf("%d", &num);

    inum = num / 2;

    for(count = 2; count <= inum; count++)
    {
        if(num % count == 0)
        {
            prime = 0;
            break;
        }
    }

    if(prime)
        printf("%d is a Prime Number\n", num);
    else
        printf("%d is a not Prime Number\n", num);

    return 0;
}

Output 1:
Enter a number
41
41 is prime number

Output 2:
Enter a number
15
15 is not prime number

Logic: Method 2

Please read the logic for method 1 above before proceeding.
In this method, we divide the user entered number by 2. This reduces the number of iterations of for loop.

If num = 41;
inum = num / 2;
inum = 41 / 2;
inum = 20;

So its enough if we iterate through the for loop 19(num/2) times to check if number 41 is perfectly divisible by any number from 2 to 20.

Method 3 Source Code: Prime Number or Not: square root Method

#include<stdio.h>
#include<math.h>

int main()
{
    int num, count, prime = 1, inum;

    printf("Enter a positive number\n");
    scanf("%d", &num);

    inum = sqrt(num);

    for(count = 2; count <= inum; count++)
    {
        if(num % count == 0)
        {
            prime = 0;
            break;
        }
    }

    if(prime)
        printf("%d is a Prime Number\n", num);
    else
        printf("%d is a not Prime Number\n", num);

    return 0;
}

Output 1:
Enter a number
50
50 is not prime number

Output 2:
Enter a number
53
53 is prime number

Logic: Method 3

Please read the logic for method 1 above before proceeding.
In this method, we apply square root to the user entered number and store it inside variable inum. This reduces the number of iterations of for loop even further.

If num = 41;
inum = sqrt(num);
inum = sqrt(41);
inum = 6;

So its enough if we iterate through the while loop 5( sqrt(num) ) times to check if number 41 is perfectly divisible by any number from 2 to 6.

Table of all prime numbers up to 1,000:

prime number or not

Note: We are not using curly braces around if and else because we only have 1 line of code after if and else – so curly braces are optional. If we have multiple lines of code, then we must use curly braces to wrap around the block of code.

You can also watch video for C Program To Find Prime Number or Not using While Loop

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Convert Radian To Degree

Lets write a C program to convert angle from Radian to Degree.

Formula To Convert Radian To Degree

degree = radian x (180.0 / M_PI);

where M_PI is a constant present in header file / library file math.h and its approximately equal to 3.14;

Related Read:
Keywords, Constants, Variables: C
Basic Arithmetic Operations In C
Print All Trigonometric Ratios: C Program
C Program To Convert Degree To Radian

Video Tutorial: C Program To Convert Radian To Degree


[youtube https://www.youtube.com/watch?v=U9y2bnDY4kE]

YouTube Link: https://www.youtube.com/watch?v=U9y2bnDY4kE [Watch the Video In Full Screen.]

Source Code: C Program To Convert Radian To Degree

#include<stdio.h>
#include<math.h>

int main()
{
    float radian, degree;

    printf("Enter angle in Radian\n");
    scanf("%f", &radian);

    degree = radian * ( 180.0 / M_PI );

    printf("Angle in Degree is %f\n", degree);

    return 0;
}

Output 1:
Enter angle in Radian
1
Angle in Degree is 57.295780

Output 2:
Enter angle in Radian
5
Angle in Degree is 286.478912

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert