Skip to main content

C Programming Decision Making and Loops Examples(PART 2)



The factorial of a positive number n is given by:

factorial of n (n!) = 1*2*3*4....n
The factorial of a negative number doesn't exist. And, the factorial of 0 is 1, 0! = 1

Example: Factorial of a Number

#include <stdio.h>

int main()

{

    int n, i;

    unsigned long long factorial = 1;


    printf("Enter an integer: ");

    scanf("%d",&n);


    // show error if the user enters a negative integer

    if (n < 0)

        printf("Error! Factorial of a negative number doesn't exist.");


    else

    {

        for(i=1; i<=n; ++i)

        {

            factorial *= i;              // factorial = factorial*i;

        }

        printf("Factorial of %d = %llu", n, factorial);

    }


    return 0;

}


Output

Enter an integer: 10
Factorial of 10 = 3628800
This program takes a positive integer from the user and computes factorial using for loop.



Since the factorial of a number may be very large, the type of factorial variable is declared as unsigned long long.

If the user enters negative number, the program displays error message.











The program takes an integer input from the user and generates the multiplication table up to 10.

Example #1: Multiplication Table Up to 10

#include <stdio.h>

int main()

{

    int n, i;


    printf("Enter an integer: ");

    scanf("%d",&n);


    for(i=1; i<=10; ++i)

    {

        printf("%d * %d = %d \n", n, i, n*i);

    }

    

    return 0;

}


Output

Enter an integer: 9
9 * 1 = 9
9 * 2 = 18
9 * 3 = 27
9 * 4 = 36
9 * 5 = 45
9 * 6 = 54
9 * 7 = 63
9 * 8 = 72
9 * 9 = 81
9 * 10 = 90Here's a little modification of the above program to generate the multiplication table up to a range (where range is also a positive integer entered by the user).
Example #2: Multiplication Table Up to a range (entered by the user)

#include <stdio.h>

int main()

{

    int n, i, range;


    printf("Enter an integer: ");

    scanf("%d",&n);


    printf("Enter the range: ");

    scanf("%d", &range);


    for(i=1; i <= range; ++i)

    {

        printf("%d * %d = %d \n", n, i, n*i);

    }


    return 0;

}


Output

Enter an integer: 12
Enter the range: 8
12 * 1 = 12 
12 * 2 = 24 
12 * 3 = 36 
12 * 4 = 48 
12 * 5 = 60 
12 * 6 = 72 
12 * 7 = 84 
12 * 8 = 96 




Example on how to display the Fibonacci sequence of first n numbers (entered by the user) using loop. Also in different example, you learn to generate the Fibonacci sequence up to a certain number.







The Fibonacci sequence is a series where the next term is the sum of pervious two terms. The first two terms of the Fibonacci sequence is 0 followed by 1.

The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21


Example #1: Fibonacci Series up to n number of terms

#include <stdio.h>

int main()

{

    int i, n, t1 = 0, t2 = 1, nextTerm;


    printf("Enter the number of terms: ");

    scanf("%d", &n);


    printf("Fibonacci Series: ");


    for (i = 1; i <= n; ++i)

    {

        printf("%d, ", t1);

        nextTerm = t1 + t2;

        t1 = t2;

        t2 = nextTerm;

    }

    return 0;

}




Output Enter the number of terms: 10
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 
Example #2: Fibonacci Sequence Up to a Certain Number

#include <stdio.h>

int main()

{

    int t1 = 0, t2 = 1, nextTerm = 0, n;


    printf("Enter a positive number: ");

    scanf("%d", &n);


    // displays the first two terms which is always 0 and 1

    printf("Fibonacci Series: %d, %d, ", t1, t2);


    nextTerm = t1 + t2;


    while(nextTerm <= n)

    {

        printf("%d, ",nextTerm);

        t1 = t2;

        t2 = nextTerm;

        nextTerm = t1 + t2;

    }

    

    return 0;

}


Output

Enter a positive integer: 100
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 






C Program to Count Number of Digits in an Integer
Example to count the number of digits in an integer entered by the user. The while loop is used to solve this program.



This program takes an integer from the user and calculates the number of digits. For example: If the user enters 2319, the output of the program will be 4.

Example #1: Program to Count Number of Digits in an Integer

#include <stdio.h>

int main()

{

    long long n;

    int count = 0;


    printf("Enter an integer: ");

    scanf("%lld", &n);


    while(n != 0)

    {

        // n = n/10

        n /= 10;

        ++count;

    }


    printf("Number of digits: %d", count);

}


Output

Enter an integer: 3452
Number of digits: 4


The integer entered by the user is stored in variable n. Then the  while loop is iterated until the test expression n != 0 is evaluated to 0 (false).

After first iteration, the value of n will be 345 and the count is incremented to 1.
After second iteration, the value of n will be 34 and the count is incremented to 2.
After third iteration, the value of n will be 3 and the count is incremented to 3.
After fourth iteration, the value of n will be 0 and the count is incremented to 4.
Then the test expression is evaluated to false and the loop terminates.




Example to reverse an integer entered by the user. This problem is solved using while loop in this example.





Example: Reverse an Integer

#include <stdio.h>

int main()

{

    int n, reversedNumber = 0, remainder;


    printf("Enter an integer: ");

    scanf("%d", &n);


    while(n != 0)

    {

        remainder = n%10;

        reversedNumber = reversedNumber*10 + remainder;

        n /= 10;

    }


    printf("Reversed Number = %d", reversedNumber);


    return 0;

}


Output

Enter an integer: 2345
Reversed Number = 5432
This program takes an integer input from the user. Then the while loop is used until n != 0is false.



In each iteration of while loop, the remainder when n is divided by 10 is calculated and the value of n is reduced by times. 



Example on how to calculate the power of a number if the exponent is an integer. Also, you will learn to compute the power using pow() function.





The program below takes two integers from the user (a base number and an exponent) and calculates the power.

For example: In case of 23

2 is the base number
3 is the exponent
And, the power is equal to 2*2*2
Example #1: Power of a Number Using while Loop

#include <stdio.h>

int main()

{

    int base, exponent;


    long long result = 1;


    printf("Enter a base number: ");

    scanf("%d", &base);


    printf("Enter an exponent: ");

    scanf("%d", &exponent);


    while (exponent != 0)

    {

        result *= base;

        --exponent;

    }


    printf("Answer = %lld", result);


    return 0;

}


Output

Enter a base number: 3
Enter an exponent: 4
Answer = 81


The above technique works only if the exponent is a positive integer.



Example #2: Power Using pow() Function

#include <stdio.h>

#include <math.h>


int main()

{

    double base, exponent, result;


    printf("Enter a base number: ");

    scanf("%lf", &base);


    printf("Enter an exponent: ");

    scanf("%lf", &exponent);


    // calculates the power

    result = pow(base, exponent);


    printf("%.1lf^%.1lf = %.2lf", base, exponent, result);


    return 0;

}


Output

Enter a base number: 2.3
Enter an exponent: 4.5
2.3^4.5 = 42.44


This program reverses an integer (entered by the user) using while loop. Then, if statement is used to check whether the reversed number is equal to the original number or not.





An integer is a palindrome if the reverse of that number is equal to the original number.

Example: Program to Check Palindrome

#include <stdio.h>

int main()

{

    int n, reversedInteger = 0, remainder, originalInteger;


    printf("Enter an integer: ");

    scanf("%d", &n);


    originalInteger = n;


    // reversed integer is stored in variable 

    while( n!=0 )

    {

        remainder = n%10;

        reversedInteger = reversedInteger*10 + remainder;

        n /= 10;

    }


    // palindrome if orignalInteger and reversedInteger are equal

    if (originalInteger == reversedInteger)

        printf("%d is a palindrome.", originalInteger);

    else

        printf("%d is not a palindrome.", originalInteger);

    

    return 0;

}


Output

Enter an integer: 1001
1001 is a palindrome.
Example to check whether an integer (entered by the user) is a prime number or not using for loop and if...else statement.





A prime number is a positive integer which is divisible only by 1 and itself. For example: 2, 3, 5, 7, 11, 13

Example: Program to Check Prime Number

#include <stdio.h>

int main()

{

    int n, i, flag = 0;


    printf("Enter a positive integer: ");

    scanf("%d", &n);


    for(i = 2; i <= n/2; ++i)

    {

        // condition for nonprime number

        if(n%i == 0)

        {

            flag = 1;

            break;

        }

    }


    if (n == 1) 

    {

      printf("1 is neither a prime nor a composite number.");

    }

    else 

    {

        if (flag == 0)

          printf("%d is a prime number.", n);

        else

          printf("%d is not a prime number.", n);

    }

    

    return 0;

}


Output

Enter a positive integer: 29
29 is a prime number.


Example to print all prime numbers between two numbers (entered by the user). This problem is solved using nested for loop and if...else statement.





Example #1: Display Prime Numbers Between two Intervals

#include <stdio.h>

int main()

{

    int low, high, i, flag;

    printf("Enter two numbers(intervals): ");

    scanf("%d %d", &low, &high);


    printf("Prime numbers between %d and %d are: ", low, high);


    while (low < high)

    {

        flag = 0;


        for(i = 2; i <= low/2; ++i)

        {

            if(low % i == 0)

            {

                flag = 1;

                break;

            }

        }


        if (flag == 0)

            printf("%d ", low);


        ++low;

    }


    return 0;

}


Output

Enter two numbers(intervals): 20 
50
Prime numbers between 20 and 50 are: 23 29 31 37 41 43 47
In this program, the while loop is iterated (high - low - 1) times.

In each iteration, whether low is a prime number or not is checked and the value of low is incremented by 1 until low is equal to high.

If the user enters larger number first, this program doesn't work as intended. You can solve this issue by swaping number if the user enters larger number first.

Example #2: Display Prime Numbers Between two Intervals When Larger Number is Entered first

#include <stdio.h>

int main()

{

    int low, high, i, flag, temp;

    printf("Enter two numbers(intevals): ");

    scanf("%d %d", &low, &high);


    //swapping numbers if low is greater than high

    if (low > high) {

        temp = low;

        low = high;

        high = temp;

    }


    printf("Prime numbers between %d and %d are: ", low, high);


    while (low < high)

    {

        flag = 0;


        for(i = 2; i <= low/2; ++i)

        {

            if(low % i == 0)

            {

                flag = 1;

                break;

            }

        }


        if (flag == 0)

            printf("%d ", low);




Example to check whether an integer (entered by the user) is an Armstrong number or not using while loop and if...else statement.





A positive integer is called an Armstrong number of order n if

abcd... = an + bn + cn + dn + ...
In case of an Armstrong number of 3 digits, the sum of cubes of each digits is equal to the number itself. For example:

153 = 1*1*1 + 5*5*5 + 3*3*3  // 153 is an Armstrong number.
Example #1: Check Armstrong Number of three digits

#include <stdio.h>

int main()

{

    int number, originalNumber, remainder, result = 0;


    printf("Enter a three digit integer: ");

    scanf("%d", &number);


    originalNumber = number;


    while (originalNumber != 0)

    {

        remainder = originalNumber%10;

        result += remainder*remainder*remainder;

        originalNumber /= 10;

    }


    if(result == number)

        printf("%d is an Armstrong number.",number);

    else

        printf("%d is not an Armstrong number.",number);


    return 0;

}


Output

Enter a three digit integer: 371
371 is an Armstrong number.
Example #2: Check Armstrong Number of n digits


#include <stdio.h>

#include <math.h>


int main()

{

    int number, originalNumber, remainder, result = 0, n = 0 ;


    printf("Enter an integer: ");

    scanf("%d", &number);


     originalNumber = number;

    

    while (originalNumber != 0)

    {

        originalNumber /= 10;

        ++n;

    }


    originalNumber = number;


    while (originalNumber != 0)

    {

        remainder = originalNumber%10;

        result += pow(remainder, n);

        originalNumber /= 10;

    }


    if(result == number)

        printf("%d is an Armstrong number.", number);

    else

        printf("%d is not an Armstrong number.", number);


    return 0;

}




Output

Enter an integer: 1634
1634 is an Armstrong number.
Example to find all factors of an integer (entered by the user) using for loop and if statement.


Example: Factors of a Positive Integer


#include <stdio.h>

int main()

{

    int number, i;


    printf("Enter a positive integer: ");

    scanf("%d",&number);


    printf("Factors of %d are: ", number);

    for(i=1; i <= number; ++i)

    {

        if (number%i == 0)

        {

            printf("%d ",i);

        }

    }


    return 0;

}


Output

Enter a positive integer: 60
Factors of 60 are: 1 2 3 4 5 6 10 12 15 20 30 60
=====================================================================

In the program, a positive integer entered by the user is stored in variable number.

The for loop is iterated until i <= number is false. In each iteration, whether number is exactly divisible by i is checked (condition for i to be the factor of number) and the value of i is incremented by 1.

================================================================================================================================================



Comments

Popular posts from this blog

short key of c programming

short key of c programming Shortcut Keys(Hot Keys)     Operation    Alt + F  -            Open file Alt + F3 -           Close Alt + F + N  -    New file Alt + X  -           Exit turbo c Alt + F5 -          Output Screen Alt + F + L  -    Check programme load or not. Alt + ENTER  - Full screen Shift + Del -       Cut Shift + Insert -   Paste Ctr + Insert -    Copy Alt+F9 -           Compile a program Ctr + F8           Bbreak point Ctrl+F9 -          To run a program Ctrl+s -...

C LANGUAGE - OVERVIEW C - VARIABLES

C LANGUAGE - OVERVIEW Advertisements C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972. In 1978, Brian Kernighan and Dennis Ritchie produced the first publicly available description of C, now known as the K&R standard. The UNIX operating system, the C compiler, and essentially all UNIX application programs have been written in C. C has now become a widely used professional language for various reasons − Easy to learn Structured language It produces efficient programs It can handle low-level activities It can be compiled on a variety of computer platforms Facts about C C was invented to write an operating system called UNIX. C is a successor of B language which was introduced around the early 1970s. The language was formalized in 1988 by the American National Standard Institute  A N S I A N S ...

environment

It looks like you meant "environment." The environment refers to the surroundings or conditions in which a person, animal, or plant lives or operates. It encompasses various elements, including natural resources, ecosystems, climate, and human-made structures. Protecting and preserving the environment is crucial for the well-being of all living organisms on Earth. Is there anything specific you'd like to discuss or learn about regarding the environment?