Explanation
The program demonstrates the use of a nested for
loop by printing a right-angled triangle pattern.
Header
The code begins with including the standard input-output header file using #include <stdio.h>
.
Variable Declaration
The main()
function is defined, and three integer variables d
, m
, and j
are declared:
int d
: Stores the total number of rows for the triangle.int m
: Used as an outer loop counter.int j
: Used as an inner loop counter.
Program Description
The program prints a description message for the user to understand its functionality.
User Input
The user is prompted to enter the total number of rows for the triangle. The input is read using scanf("%d", &d);
.
Nested Loop for Triangle Pattern
The program uses nested for
loops to print the triangle pattern:
for (m = 1; m <= d; m++)
: Outer loop to iterate over each row.for (j = 1; j <= m; j++)
: Inner loop to print the numbers in each row.printf("%d ", j);
: Prints the current numberj
followed by a space.printf("\n");
: Prints a new line after each row is complete.
Program End
The program ends with printf("\n\n");
to print a new line and return 0;
to indicate successful execution.
Code
/*
* -----------------------------------------------------------
* Logic Building with Computer Programming (CSU1128)
* Instructor: Dr. Pankaj Vaidya | Author: Divya Mohan
*
* This code is a part of the educational initiative by dmj.one
* with aim of empowering and inspiring learners in the field of
* Computer Science and Engineering through the respective courses.
*
* (c) 2022, Divya Mohan for dmj.one. All rights reserved.
* -----------------------------------------------------------
*/
#include <stdio.h>
int main()
{
int d, m, j;
printf("\n\n Program to demonstrate the nested for loop by printing a right angled triangle. \n\n");
printf("Enter total number of times you want the loop to repeat - (Example: 5) - and press enter: ");
scanf("%d", &d);
for (m = 1; m <= d; m++)
{
for (j = 1; j <= m; j++)
{
printf("%d ", j);
}
printf("\n");
}
printf("\n\n");
return 0;
}
Output
Program to demonstrate the nested for loop by printing a right angled triangle.
Enter total number of times you want the loop to repeat - (Example: 5) - and press enter: 5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5