Counting
Counting is a fundamental concept in programming that involves iterating over a sequence of elements and performing operations on each element. In the context of counting up to a certain number, it simply means displaying each number from 1 up to a given number n.
Objective :
The objective is to count from 1 up to a specified number 𝑛n and display each number.
Steps
- Input: Get the number 𝑛n up to which we need to count.
- Loop: Use a loop to iterate from 1 to 𝑛n.
- Output: Print each number during each iteration of the loop.
Algorithm in Pseudo-Code
C Implementation
Here’s a simple C program to count from 1 to a user-specified number n.
Explanation of the C Program
- Include Standard I/O Library:
- #include <stdio.h>: This line includes the standard input-output library needed for functions like printf and scanf.
- Main Function:
- int main(): The main function is the entry point of the program.
- Variable Declaration:
- int n;: This declares an integer variable n that will hold the number up to which we need to count.
- Input from User:
- printf(“Enter the number up to which to count: “);: This line prompts the user to enter a number.
- scanf(“%d”, &n);: This line reads the integer input from the user and stores it in the variable n.
- For Loop for Counting:
- for (int i = 1; i <= n; i++): This loop starts with i initialized to 1 and increments i by 1 in each iteration until i is greater than n.
- printf(“%d\n”, i);: Inside the loop, this line prints the current value of i followed by a newline.
- Return Statement:
- return 0;: This indicates that the program finished successfully.
Sample Output
If the user inputs 5, the program will output:
The program reads the input 5 and then counts from 1 to 5, printing each number on a new line.
Summary
The counting algorithm is a simple but essential concept in programming. It demonstrates how to use loops to perform repetitive tasks, how to handle user input, and how to output results to the screen. This forms the basis for more complex algorithms and operations in programming.