Monday, April 28, 2025

C Tutorial - 10 - For Loop with User Input

Basic for loop in C:

#include <stdio.h>

int main()
{
    int x;

    for (x = 0; x <= 5; x++)
    {
        printf("X in this moment of loop: %d \n", x);
    }

    return 0;
}

Result:

X in this moment of loop: 0
X in this moment of loop: 1
X in this moment of loop: 2
X in this moment of loop: 3
X in this moment of loop: 4
X in this moment of loop: 5

Process returned 0 (0x0)   execution time : 0.030 s
Press any key to continue.

This C code demonstrates the use of a "for loop" to print the value of the variable "x" from 0 to 5. Here is what each line of the code does:

  • #include <stdio.h>: This line includes the standard input/output library in the program, which provides the necessary functions for input and output operations.
  • int main(): This line declares the main function, which is the entry point of the program.
  • int x;: This line declares an integer variable "x" without initializing it.
  • for (x = 0; x <= 5; x++): This line starts a "for loop" that initializes "x" to 0, continues as long as "x" is less than or equal to 5, and increments "x" by 1 after each iteration of the loop.
  • {: This brace starts the block of code that will be executed in the loop.
  • printf("X in this moment of loop: %d \n", x);: This line uses the printf function to print the current value of "x" in each iteration of the loop.
  • }: This brace ends the block of code that will be executed in the loop.
  • return 0;: This line indicates that the program has finished executing and returns a value of 0 to the operating system, which indicates that the program executed successfully.

 

For loop in C with User Input

#include <stdio.h>

int main()
{
    int x;
    int y;

    printf("Enter x: \n");
    scanf("%d", &x);

    printf("Enter y: \n");
    scanf("%d", &y);

    for (x; x < y; x++)
    {
        printf("X in this moment of loop: %d \n", x);
    }
    return 0;
}

Result:

Enter x:
0
Enter y:
5
X in this moment of loop: 0
X in this moment of loop: 1
X in this moment of loop: 2
X in this moment of loop: 3
X in this moment of loop: 4

Process returned 0 (0x0)   execution time : 2.490 s
Press any key to continue.

This code prompts the user to enter two integers x and y and then loops through all the integers between x and y (excluding y), printing the current value of x at each iteration.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...