Microcontroller Embedded C Programming Lecture 121| while loop exercise

  • Post author:
  • Post category:Blog

 

while loop exercise

 

 

Exercise:

  • Write a program to print all even numbers between 0 to 100 (including the boundary numbers). 
  • Also, count and print how many even numbers you find. 
    • Use ‘while’ loop, or ‘for’ loop, or ‘do while’ loop. 
    • Later change the program to accept boundary numbers from the user.

 

Code:

#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);

    printf("Even numbers are :\n");
    even=0;
    while(start_num <= end_num){
         if(!(start_num % 2) ){
              printf("%d\t",start_num);
              even++;
          }
          start_num++;
    }//end of while loop

    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();

}

 

First, accept two numbers starting and ending numbers.

I created the variables start_num and end_num, and the variable is of type signed int. It is signed int because the user is allowed to enter the signed number.

And another variable is even. This must be unsigned because the count cannot be negative.

Then write a printf statement. 

printf(“Enter starting and ending numbers(give space between 2 numbers):”); 

 

After that, let’s scan the numbers. 

scanf(“%d %d”, &start_num, &end_num);

Let’s read the input so scanf, I would use %d space %d and the first one is start_num and the second one is end_num.

 

After that, you have to use a loop. 

while(start_num <= end_num)

You should start from the start number, check whether it is even or odd, and then proceed to the next number until that number is less than or equal to the end number. That’s a logic.

 

First, let’s check whether a start_num is even or odd. For that, we use the modulus(%) operator. 

if(!(start_num % 2)) 

If that expression is 0, then it’s an even number. I can use not operator(!) for this expression. 

If start_num is really an even number, so (start_num % 2) expression will be 0. That is, the even number modulus of 2 is 0. It is always 0. That’s why 0 means false. So, not of(!) false is true. That means a number is an even number. 

If it is an even number I will print that. 

printf(“%d\t”, start_num);

I would give \t instead of \n because I want to print horizontally by giving a tab between two numbers. And here I would print start_num. 

And after that, I will increment the even. This counts how many even numbers are detected.

But you must initialize even before incrementing, so I would do that here even = 0 (18th line). Let’s start with 0.

 

After that, you have to keep incrementing start_num. So, start_num++. This is the end of the while loop. 

So, start_num will be incremented, and again it will be looped back, and again it will be checked against the end number.

Here, I can just print one message “Even numbers are: \n”.

And when that loop ends I’m going to print the total number of even numbers counted.  

printf(“Total even numbers: %u\n”, even);  

Take even as unsigned, because the count cannot be negative. So, I would use data type uint32 for that. 

 

Output

Enter the starting and ending numbers, let’s try -2 to -8.

It is not working, because the ending number has to be greater than the starting number. So, that condition you have to check here.

Figure 2. Output
Figure 1. Output

 

Here, the ending number is less than the starting number, which is not allowed. That gives an error. So, the ending number has to be greater than or equal to the starting number. 

if(end_num < start_num)

If the end_num is less than start_num, then print that “ending number should be greater than starting number”. Then you have to exit. So, let’s wait_for_user_input and return. The code is shown below.

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;
}

    printf("Even numbers are :\n");
    even=0;
    while(start_num <= end_num){
          if(!(start_num % 2) ){
               printf("%d\t",start_num);
               even++;
           }
     start_num++;
     }//end of while loop

   printf("\nTotal even numbers : %u\n",even);

wait_for_user_input();
}

 

 

I enter starting and ending numbers are -2 to -8.

while loop exercise
Figure 2. Output

 

It prints the ending number should be greater than starting number. That’s good. 

 

Let’s try -233 to 90. It prints the Even numbers, as shown in Figure 3.

while loop exercise- Print Even Numbers
Figure 3. Output

 

But take a look at the columns, they are not arranged properly. We can arrange it the proper way. 

Here, let’s take -232. It actually consumes 4 spaces. There is one space for a negative sign, 2 is second place, 3 is third place, and 2 in fourth place. So, we have to print each number in that format. 

And take 8, it consumes only one space. So, we have to force every digit to consume 4 places here. If you do that, it looks good. 

 

So, we can go to our printf where we are printing that(28th line). 

Here, instead of %d give %4d, as shown in Figure 6. That means, now each output number consumes 4 spaces in the display. Now you are able to distinguish the output.

while loop exercise- Print Even Numbers
Figure 4. Code

 

Let’s run once again and try once again -233 to 90.

Now you can see that it is arranged properly. 8 has aligned to the right. That means here 3 dummy spaces have been inserted. 

The total number of even numbers is 162. So, that works well. 

while loop exercise- Print Even Numbers
Figure 5. Output

 

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