Mastering Loops and Conditional Statements in C Programming with 5 Examples for You

C Programming – For those who are new to programming, one of the essential languages is C. Since they are the foundation of most programs, understanding loops and conditional statements is essential. This blog post will discuss some standard loop and condition techniques in C programming that all newcomers should be familiar with.

Introduction to Conditional Statements and Loops in C Programming

Certain code blocks can be executed based on conditions thanks to conditional statements. If a condition is true, the if statement assesses it and then runs a block of code. You can check multiple criteria with the else if statement, and it also gives a default action in the event that none of the circumstances are met.

1. Positive number program

We use conditional statements such as if, else if, and else to verify the value of num. If num exceeds zero, it prints “Number is positive.” If num equals zero, it outputs “Number is zero.” If num is less than zero, it displays “Number is negative.

C
1.	#include <stdio.h>
2.	
3.	int main() {
4.	    int num = 10;
5.	
6.	    if (num > 0) {
7.	        printf("Number is positive.\n");
8.	    } else if (num < 0) {
9.	        printf("Number is negative.\n");
10.	    } else {
11.	        printf("Number is zero.\n");
12.	    }
13.	    return 0;
14.	}

In this example, the program determines whether the value of num is positive, negative, or zero and prints the appropriate message based on it.

Let’s learn the code step by step:

  1. <stdio.h>:Use of functions such as printf() requires the standard input/output library
  2. int: This is the return type of the function. The main() function in C and C++ usually returns an integer result. Return values of 0 by convention indicate that the program has executed successfully, but values that are not zero usually denote an error or an unusual termination.
  3. Main(): The main() function is a essential component in C and C++ programs. It serves as the entry point for the program’s execution. The operating system usually starts a C or C++ program’s execution from the main() function.
  4. A variable num is declared and initialized with the value 10.
  5. An “if statement” is used to check whether num is greater than 0. If it is, the message “Number is positive.” is printed using printf().
  6. So, in this perticular example, since var num has value 10 and it is greater than 0, thus the message “Number is positive.” will be printed.

2. Reversing a Number

In C, “reversing a number” means the process of rearranging the digits of a given number in reverse order. For example, reversing a number that starts at 123 would result in 321.

C
#include <stdio.h>

int RevNum(int num) {
    int R = 0;
    
    // Reversing the number
    while (num != 0) {
        int remainder = num % 10;
        R = R * 10 + remainder;
        num /= 10;
    }    
    return R;
}
int main() {
    int num;
    printf("Enter a number: ");
    scanf("%d", &num);
    printf("Reversed number: %d\n", RevNum(num));
    return 0;
}

  • An integer is entered into the RevNum() function, which outputs the reversed number.
  • We initializing RevNum to 0 within the function.
  • Through a while loop, each digit of the input integer (num) is iterated over.
  • In each iteration, we shift the digits one place to the left and use the modulus operator % to extract the final digit of num, adding it to RevNum.
  • Lastly, we eliminate the final digit from num to update it.
  • After num equals 0, the loop resumes, and the reversed number is then put  RevNum function.

3. Fibonacci Series

Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. The sequence goes as 0, 1, 1, 2, 3, 5, 8, 13, and so forth. Understanding how to generate the Fibonacci series is crucial in programming, as it’s a common problem encountered in various contexts. In this blog post, we’ll explore Fibonacci series in detail and demonstrate how to implement it in C programming.

The Fibonacci Sequence

The Fibonacci sequence starts with two initial numbers: 0 and 1. Each subsequent number in the sequence is the sum of the two preceding numbers. The sequence can be defined recursively as follows:

F(0) = 0

F(1) = 1

F(n) = F(n-1) + F(n-2) for n > 1

The Fibonacci sequence can also be represented visually as follows:

0, 1, 1, 2, 3, 5, 8, 13, 21, …

 3(i). Iterative Approach

C
#include <stdio.h>

void fibonacciIterative(int n) {
    int i, first = 0, second = 1, next;

    printf("Fibonacci Series up to %d terms:\n", n);

    for (i = 0; i < n; i++) {
        if (i <= 1)
            next = i;
        else {
            next = first + second;
            first = second;
            second = next;
        }
        printf("%d, ", next);
    }
}

int main() {
    int terms;

    printf("Enter the number of terms: ");
    scanf("%d", &terms);

    fibonacciIterative(terms);

    return 0;
}

3(ii).Recursive Approach

C
#include <stdio.h>

int fibonacciRecursive(int n) {
    if (n <= 1)
        return n;
    else
        return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2);
}

void printFibonacciSeries(int terms) {
    int i;

    printf("Fibonacci Series up to %d terms:\n", terms);

    for (i = 0; i < terms; i++) {
        printf("%d, ", fibonacciRecursive(i));
    }
}

int main() {
    int terms;

    printf("Enter the number of terms: ");
    scanf("%d", &terms);

    printFibonacciSeries(terms);

    return 0;
}

Summery

For every programmer, it is imperative to comprehend the Fibonacci series and learn how to construct it in C. The Fibonacci sequence was defined, and two methods for generating it—recursive and iterative—were shown in this blog post. In the context of programming, both approaches are crucial to comprehend as they each have benefits and application cases. To reinforce your comprehension, try varying the value of ‘n’ and see how the Fibonacci series changes. You can also experiment applying this concept to your own projects.

4. Armstrong Number

An Armstrong number is a number that is equal to the sum of its own digits raised to the power of the number of digits. It is also referred to as a narcissistic number, plenary number, or pluperfect number. Michael F. Armstrong is honored to have introduced these numbers in 1969.

Understanding Armstrong Numbers

To understand Armstrong numbers, let’s consider an example: 153.

The number of digits in 153 is 3.

Each digit of 153 raised to the power of 3 and then summed gives us:

1 3 +5 3 +3 3 = 1+125+27 = 153.

Since the sum of the cubes of its digits equals the number itself, 153 is an Armstrong number.

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

// Function to calculate the number of digits in a number
int countDigits(int num) {
    int count = 0;
    while (num != 0) {
        num /= 10;
        ++count;
    }
    return count;
}

// Function to check if a number is an Armstrong number
int isArmstrong(int num) {
    int No, remainder, result = 0, n = 0, power;
    
    No = num;

    // Count number of digits
    n = countDigits(num);

    // Calculate result
    while (No != 0) {
        remainder = No % 10;

        // Power of remainder with respect to the number of digits
        power = round(pow(remainder, n));
        result += power;
        No /= 10;
    }

    // Check if num is an Armstrong number
    if (result == num)
        return 1; // Armstrong number
    else
        return 0; // Not an Armstrong number
}


int main() {
    int num;

    printf("Enter a number: ");
    scanf("%d", &num);

    if (isArmstrong(num))
        printf("%d is an Armstrong number  =  ", num);
    else
        printf("%d is not an Armstrong number  =  ", num);

    return 0;
}

We define a function countDigits() to count the number of digits in a given number.

The isArmstrong() function checks if a number is an Armstrong number.

Inside isArmstrong(), we first find the number of digits in the given number.

Then, we calculate the sum of each digit raised to the power of the number of digits.

If the result equals the original number, then it’s an Armstrong number.

In the main() function, we prompt the user to input a number and then call isArmstrong() to check if it’s an Armstrong number or not.

There are  0, 1, 153, 370, 371 and 407 are the Armstrong numbers.

Let’s discuss each of them:

0 :

Since 0 raised to any power is still 0, 0 satisfies the Armstrong number condition trivially.

1 :

Similar to 0, 1 raised to any power is still 1, making 1 another trivial Armstrong number.

153 :

As previously explained, 153 is a three-digit Armstrong number.

13+53+33=1+125+27=153

370 :

33+73+03=27+343+0=370

371 :

33+73+13=27+343+1=371

407 :

43+03+73=64+0+343=407

5. Palindrome number

A number that remains the same after its digits are switched is called a palindrome.

C
#include <stdio.h>
// Function to check if a number is palindrome or not
int P(int num) {
    int i = 0, no = num;
        // Reversing the number
    while (num != 0) {
        int remainder = num % 10;
        i = i * 10 + remainder;
        num /= 10;
    }    
    // Checking if the reversed number is equal to the original number
    if (no == i)
        return 1; // Palindrome no
    else
        return 0; // Not a palindrome
   end if
}
int main() 
{
    int num;
    printf("Enter a number: ");
    scanf("%d", &num);
    if (P(num))
        printf("%d palindrome no.\n", num);
    else
        printf("%d is not a palindrome no .\n", num);
 end if
    return 0;
}

When an integer is entered, the function isPalindrome(), which is defined in this program, returns 1 if the number is a palindrome and 0 otherwise. The main() function uses the isPalindrome() function to check if the user-inputted integer is a palindrome before outputting the correct outcome.

6. Find the Grater Number in Four Numbers

C
// find the grater no in four no
#include <stdio.h>

int main()
{
   int a,b,c,d;
    int big;

    printf("Enter four numbers  : ");
    scanf("%d %d %d %d",&a,&b,&c,&d);
    
     if (a>=b && a>=c && a>=d) 
            { printf("'A' is Greater");
                }
                else if (b>=a && b>=c && b>=d)
                {
                  printf("'B' is Greater");
                }
                else if(c>=a && c>=b && c>=d)
                {
                    printf("'C' is Greater");
                }
           
             else
             {
                 printf("'D' is Greater");
             }
 
}

  • int a, b, c, d; declares four variables to store the input numbers.

    The program uses nested if-else if statements to compare a, b, c, and d to determine which is the largest:
  • if (a >= b && a >= c && a >= d) checks if a is greater than or equal to b, c, and d.
  • else if (b >= a && b >= c && b >= d) checks if b is greater than or equal to a, c, and d.
  • else if (c >= a && c >= b && c >= d) checks if c is greater than or equal to a, b, and d.
  • If none of these conditions are true (else), then d must be the greatest.

Conclusion

These programs are crucial for novices to comprehend as they illustrate basic C programming ideas. Effective understanding of these ideas will be aided by practice and experimenting with these examples.

Writing efficient and well-structured C programs necessitates a firm grasp of loops and conditional expressions. By mastering these basic techniques, beginners can build a solid foundation for progressively more complicated programming concepts. Try out multiple examples and practice often to strengthen your C programming skills. Enjoy yourself while learning to code!

Mastering Pattern Programs in C Programming: Explore 11 Examples

C programming

Recent Blogs

Mastering Local Storage in Web Development: 8 Practical Examples, From Novice to Expert! #3

Local storage is a useful web development tool that enables developers to save data within the user’s browser. In this article, we’ll look at different features of local storage, starting with beginner-level examples and continuing to more complex techniques. By the end of this guide, you will have a basic understanding of how to successfully […]

CSSHTMLJavascriptWeb Storage

Mastering the Art of CSS Translate Property: A Comprehensive Guide with 6 examples

What is Translate Property in CSS? CSS translate property moves an element along the X and Y axes. Unlike other positioning attributes, such as position, translate does not disrupt the document’s natural flow, making it excellent for producing smooth animations and transitions. What is Transform property in CSS Visually appealing and dynamic user interfaces have […]

CSSHTMLJavascriptWeb design

What is the JavaScript Fetch API and How Can You Use It?

Introduction The Fetch API marks a substantial shift in the way web applications conduct network queries. Fetch, introduced in current browsers as a more powerful and flexible alternative to XMLHttpRequest (XHR), makes it easier to communicate with servers and retrieve content over the network. This API is critical in the building of modern online applications, […]

CSSFetch APIHTMLJavascript

Understanding JavaScript Operators: A Comprehensive Guide #3

Introduction to JavaScript Operators In JavaScript, as in other programming languages, operators are special symbols or keywords that execute operations on operands (variables, constants, or values). Simply said, an operator accepts one or more operands, manipulates them in a certain way, and produces a result. For example, in the phrase 3 + 4, the + […]

CSSHTMLJavascript