Microcontroller Embedded C Programming lecture 124| ‘for’ loop exercise

  • Post author:
  • Post category:Blog

 

‘for’ loop exercise

 

 

In this comprehensive guide, we will delve deep into ‘for’ loops, one of the fundamental control structures in programming. We will not only explain the syntax but also provide a practical exercise to solidify your understanding. So, let’s get started!

 

Exercise:

           Write the program for printing even numbers using a ‘for’ loop.

 

‘for’ loop syntax:

The ‘for’ loop is a powerful construct used for repetitive tasks in programming. Its syntax is as follows:

 for( block 1; block 2; block3)
 {
          // body of for loop
 }

First, you have to use a ‘for‘ keyword, open the parenthesis, and create the body. In the parenthesis, you have to create 3 blocks by using two semicolons. 

Initialization (block 1): This block is executed only once at the beginning of the loop. It’s where you can initialize variables or perform any necessary setup. You can even include complex expressions.

Evaluation (block 2): This block is responsible for evaluating a condition. If the condition is true, the loop continues; otherwise, it terminates.

Update (block 3): The code in this block executes after each iteration of the loop body. It’s commonly used for incrementing or decrementing variables to control the loop.

 

Practical Exercise: Printing Even Numbers

Let’s apply our knowledge of ‘for’ loops to a practical exercise. We’ll write a program in C that prints even numbers within a given range.

How to use a for loop here?

The code is shown below.

You know that the first block is for some initialization or you can put any expression you want here, which will be executed only one time.  So, you can put anything you want in block 1.

For example, I can even put this printf statement in block 1. So, don’t give the semicolon, and by giving a comma, I can even give even =0 statement. All these are legal activities. Because, this is executed only one time, that is for the very first time. 

 

The second block is for evaluation. 

Here, our evaluation is, we want to check whether start_num <= end_num. That’s why I would use start_num <= end_num for evaluation( in block 2). 

And after that, I would just use the same logic that is if( start_num % 2). So, if it is 0, then I would print this statement, that is printf(“%4d\t”, start_num). The logic is the same. And after that, I’m going to increment even++ here. This is a body of the for loop.

Here you have to increment the start_num. So, that you can place it in block 3, start_num++. Because start_num++ is executed after the body is executed.

You can also keep start_ num++ in after the body also, in that case, you can leave the block 3 space empty. No problem with that. 

#include<stdio.h>
#include<stdint.h>

void wait_for_user_input(void);

int main(void)
{
    int32_t start_num , end_num;
    uint32_t even;
    printf("Enter starting and ending numbers(give space between 2 nos):");
    scanf("%d %d",&start_num,&end_num);

    if(end_num < start_num){
      //error
         printf("ending number should be > starting number\n");
         wait_for_user_input();
         return 0;
     }

    for(printf("Even numbers are :\n"), even=0; start_num <= end_num ; start_num++ )
      {  
       if( ! (start_num % 2 ) ){
              printf("%4d\t",start_num);
              even++;
          }
       }
       printf("\nTotal even numbers : %u\n",even);
       wait_for_user_input();
      }


void wait_for_user_input(void)
{
      printf("Press enter key to exit this application");

   while(getchar() != '\n')
   {
          //just read the input buffer and do nothing
   }
   getchar();
}

 

Let me again explain this ‘for’ loop. 

How it executes? 

To comprehend how the ‘for’ loop works in our exercise:

  • In block 1, we initialize the even variable to 0.
  • In block 2, we check if start_num is less than or equal to end_num. If true, we proceed; otherwise, the loop terminates.
  • In the loop body, we check if start_num is even (using the modulus operator %). If it is, we print it and increment the even count.
  • In block 3, we increment start_num after each iteration.

That’s about the for loop and we use for loop in the place of the while loop when we do iterations as I said before. Like iterations over an array, or when we do iterations over variables, etc. When we cover arrays, we’ll explore more about how to do those iterations using for loop. 

 

Get the Full course on Microcontroller Embedded C Programming Here.

FastBit Embedded Brain Academy Courses

Click here: https://fastbitlab.com/course1

 

FastBitLab

The FastBit Embedded Brain Academy uses the power of internet to bring the online courses related to the field of embedded system programming, Real time operating system, Embedded Linux systems, etc at your finger tip with very low cost. Backed with strong experience of industry, we have produced lots of courses with the customer enrolment over 3000+ across 100+ countries.

Leave a Reply