I’m just a beginner to C programming, and i got 2 different outputs for the following 2 code blocks.
Code 1**
#include <stdio.h>
int main(void)
{
int i=0;
while (i<5)
{
int j=1;
while (j<=2*i+1)
{
printf("*");
j++;
}
i++;
printf("n");
}
}
Code 2*
#include <stdio.h>
int main(void)
{
int i=0;
int j=1;
while (i<5)
{
while (j<=2*i+1)
{
printf("*");
j++;
}
i++;
printf("n");
}
}
Please can anybody explain the reason for that?
Thanks for spending time reading my question. Your help will be highly appriciated.
The first code block returns :
*
***
*****
*******
*********
The 2nd code block returns:
*
**
**
**
**
Jayavi Chathusara is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
In the first program the variable j
is initialized to 1
every iteration of the outer loop.
In the second program the variable j
is initialized only once, at the start of the program.
For the two programs to be equivalent the second program should be changed to:
#include <stdio.h>
int main(void)
{
int i=0;
int j=1;
while (i<5)
{
j = 1; // Change here, resetting the variable j
while (j<=2*i+1)
{
printf("*");
j++;
}
i++;
printf("n");
}
}