Using While Loop to Find Even Numbers

CCBeginner
Practice Now

Introduction

In this lab, you will learn how to use a while loop to find even numbers from a list of integers.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/ControlFlowGroup(["`Control Flow`"]) c(("`C`")) -.-> c/CompoundTypesGroup(["`Compound Types`"]) c(("`C`")) -.-> c/FunctionsGroup(["`Functions`"]) c/UserInteractionGroup -.-> c/output("`Output`") c/BasicsGroup -.-> c/variables("`Variables`") c/BasicsGroup -.-> c/data_types("`Data Types`") c/BasicsGroup -.-> c/operators("`Operators`") c/ControlFlowGroup -.-> c/if_else("`If...Else`") c/ControlFlowGroup -.-> c/while_loop("`While Loop`") c/CompoundTypesGroup -.-> c/arrays("`Arrays`") c/FunctionsGroup -.-> c/function_parameters("`Function Parameters`") c/FunctionsGroup -.-> c/function_declaration("`Function Declaration`") subgraph Lab Skills c/output -.-> lab-136083{{"`Using While Loop to Find Even Numbers`"}} c/variables -.-> lab-136083{{"`Using While Loop to Find Even Numbers`"}} c/data_types -.-> lab-136083{{"`Using While Loop to Find Even Numbers`"}} c/operators -.-> lab-136083{{"`Using While Loop to Find Even Numbers`"}} c/if_else -.-> lab-136083{{"`Using While Loop to Find Even Numbers`"}} c/while_loop -.-> lab-136083{{"`Using While Loop to Find Even Numbers`"}} c/arrays -.-> lab-136083{{"`Using While Loop to Find Even Numbers`"}} c/function_parameters -.-> lab-136083{{"`Using While Loop to Find Even Numbers`"}} c/function_declaration -.-> lab-136083{{"`Using While Loop to Find Even Numbers`"}} end

Find Even Numbers From a List Using While Loop

In this lab, you will learn how to find even numbers from a list using a while loop.

  1. Create a file called even_numbers.c and open it in WebIDE.

  2. Copy and paste the following code into the even_numbers.c file:

    #include <stdio.h>
    
    int main() {
      int numbers[] = { 21, 78, 62, 90, 55, 10, 85, 45, 11, 2 };
      int size = sizeof(numbers) / sizeof(numbers[0]);
      int i = 0;
    
      printf("The even numbers from the list are:\n\n");
    
      while (i < size) {
        if (numbers[i] % 2 == 0) {
          printf("EVEN: %d\n", numbers[i]);
        }
        i++;
      }
    
      return 0;
    }
  3. Save the file.

  4. Open a terminal and navigate to the directory where the even_numbers.c file is saved.

  5. Compile the code using the command gcc even_numbers.c -o even_numbers.

  6. Run the program by entering ./even_numbers in the terminal.

Summary

After completing this lab, you will be able to use a while loop to find even numbers from a list of integers. The program will output the even numbers from the list on the terminal.

Other C Tutorials you may like