Hello Friends Today, through this tutorial, I will tell you How Can I Generate a Sequence of Numbers in c Program?
There are several ways to generate a sequence of numbers in C, depending on your specific requirements:
Using a for loop:-
#include <stdio.h> int main() { int start, end, step; // Get user input for start, end, and step values printf("Enter starting number: "); scanf("%d", &start); printf("Enter ending number: "); scanf("%d", &end); printf("Enter step size (1 for incrementing, -1 for decrementing): "); scanf("%d", &step); // Validate input and handle negative step size if (step == 0) { printf("Error: Step size cannot be zero.\n"); return 1; // Exit with an error code } // Print the sequence for (int i = start; step > 0 ? i <= end : i >= end; i += step) { printf("%d ", i); } printf("\n"); return 0; }
Explanation:-
1. This code allows users to specify the starting number, ending number, and step size (positive for incrementing, negative for decrementing).
2. It performs basic input validation to prevent a zero step size.
3. The `for` loop iterates from the starting number to the ending number with the specified step size, printing each number within the loop.