Can anyone tell me why this program runs? [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
New to c programming. Here is a question from an assignment. Can anyone tell me why this code still outputs two columns 5 and 2 even though i is less than j.
#include <stdio.h>
int main(void) {
int i = 0, j = 5;
for (i > j; i + j == 5; j < 2) {
printf("Two columns\n");
i = 5;
j = 2;
}
printf(" %d %d\n", i, j);
return 0;
}

Here are the steps executed in order:
int i = 0, j = 5; local variables i and j are defined and initialized to 0 and 5 respectively
for (i > j; i + j == 5; j < 2) {:
first executes the initial expression i > j which evaluates to false (0) and has no side effect, the result is ignored, hence probably completely omitted by the compiler.
second executes the test expression i + j == 5 which evaluates to true (1) so the body of the for loop executes.
printf("Two columns\n"); outputs Two columns and a newline.
i = 5; sets i to 5.
j = 2; sets j to 2.
} the increment expression is then evaluated: j < 2, which evaluates to false but has no side effect, the result is ignored.
the loop then evaluates the test expression again: i + j == 5 which now evaluates to false (0) since 5 + 2 is different from 5.
the loop exits.
printf(" %d %d\n", i, j); outputs the numbers 5 and 2 and a newline as you observe.
return 0; main returns the value 0 which is a successful exit status.
This code is very silly and purposely misleading as it has test expressions in all 3 parts of the for statement header. Only the middle one is the test expression, the first and last expressions are only used for side effects, such as initializing and incrementing a loop counter.

for (i > j; i + j == 5; j < 2)
In for loop initialization part i > j no make sense
Then i + j == 5 condition become true and executed for loop body where assigned new values to i and j respectively 5 and 2.
Then control goes to for loop increment part where j < 2 become false. this is also no make sense.
Then again control goes to condition part where i+j == 5 becomes false because i is a 5 and and j is a 2. So, 7 == 5 becomes false.
So, output of your code is 5 and 2.

Related

Nesting For loop in c , at i = 4 ; j will be 2 how does it satisfy the condition? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
{
for (int i = 0; i <= 5; i++)
{
for (int j = 5; j >= i; j--)
{
printf("+");
}
printf("\n");
}
}
At i = 4; j will be 2 how does it satisfy the condition of j>=i?
You seem to be thinking that "j will be 2" because you see two "+" in output in that line.
But that only means that the inner loop is executed twice. Which is because (quoting Barmars comment):
When i == 4, the inner loop will only loop twice, with j == 5 and j == 4.
You analysed the detailed behaviour of your code based on output, which is good. But if something puzzles you then you either need more output on exactly the detail which puzzles you; e.g. by actually outputting the value in question for verifying your assumptions. Or you could use a debugger.
For example. I changed your code in a way which probably makes things very obvious:
#include <stdio.h>
int main(void)
{
for (int i = 0; i <= 5; i++)
{
printf("%d: ", i);
for (int j = 5; j >= i; j--)
{
printf("%d", j);
}
printf("\n");
}
}
It gets you an output (e.g. here https://www.onlinegdb.com/online_c_compiler ) of:
0: 543210
1: 54321
2: 5432
3: 543
4: 54
5: 5
Where the line 4: 54 indicates two inner loop iterations, with values for j of 5 and 4, while i is 4.

what the function does? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
#define SIZE 10
void fun(int arr[]){
int i,k,j,n = SIZE;
k = 0;
for (i = 1 ; i < SIZE; i++) {
j = k;
while (j > 0 && arr[j] != arr[i])
j = j - 1;
if( j == 0){
k = k + 1;
arr[k] = arr[i];
}
else
n--;
}
}
This function was in my test today.
My question is: does someone know what it does?
What does the variable n represent at the end of the function?
At the end of the function, the variable n will have counted how many times each i-th array value in the range [0, SIZE) was unique among the first i array elements..
In addition, the first n elements of the array will contain exactly those elements that were found to be unique in the above sense. All other array entries will remain unchanged.
The other variables will have the following values:
i == SIZE
j == some value between [0, SIZE)
k == n-1
Some inline comments may help understand the code better.
#define SIZE 10
void fun(int arr[]){
int i,k,j,n = SIZE;
k = 0;
// walk through the array up until its 10th element, skipping
// the first entry and hoping that the array actually contains
// at least 10 entries
for (i = 1 ; i < SIZE; i++) {
// similar to i, the variable k also walks up towards 10.
// However it starts at 0, not at 1, and it does not
// necessarily get incremented in every loop iteration. More
// on that below.
// Here, we set the variable j to start out as the same value
// as the current k, but j will walk the opposite direction, i.e.,
// toward 0, not toward 10.
j = k;
// find the largest j in the open interval [0,k) for which
// the array entry arr[j] differs from the current arr[i]
while (j > 0 && arr[j] != arr[i])
j = j - 1;
// if no value in [0, k) was equal to arr[i], we'll end up \
// with j == 0
if( j == 0){
// then we increment k -- that is, k counts how many times
// we encountered a value arr[i] during the for-loop that was
// unique among the first i array entries. But since the
// for loop starts at 1 instead of 0, k will count one
// element too few.
k = k + 1;
// well, so much for 'unique': here, we actually copy the current
// value arr[i] into arr[k]
arr[k] = arr[i];
}
else
// this part in effect assures that the expression
// (n-k) gets decremented in every iteration of the loop,
// no matter if j == 0 is true or false.
// Since we start out with (n-k) = SIZE, and
// the loop body gets executed SIZE-1 times, (n-k) will
// be equal to 1 after the for-loop has terminated.
n--;
}
}

Logic of for loop in C

****
***
**
*
/*code for this pattern*/
#include<stdio.h>
int main()
{
int i, j;
for (i = 4 ; i >= 1 ; --i) {
for (j = 1 ; j <= i; ++j) { /*why does j<=i?*/
printf("*");
}
printf("\n");
}
}
So why does j <= i? the first for loop is responsible for the rows. While the second for loop in responsible for the number of stars in each row. again, i don't understand the logic of the condition- j <= i.
EDIT: C is the first language I have ever tried to really learn. The question is pretty clear, i think. I don't understand the condition component of the for loop. Thats all. Some people understood what I was asking though. thanks
EDIT2: seems like i wasn't clear with my question. I want to to know why does j has to be less or equal to i. why can i be less or equal than j? I am having trouble seeing the relationship between i, the number of rows and j, the number of stars in each row.
Thanks
As you said, the outer for loop is for the number of rows. The inner for loop is to print the * n times, where n is the number of times the character has to be printed in that row.
i.e) In the first iteration : i = 4, so, j = 1;j<=4 executes 4 times so you print 4 *.
In the second iteration : i = 3, so j = 1;j<=3 executes thrice, so you print 3 *
i starts high and decrements while i is >= 1. j starts low at 1, and increments while j is <= i.
This means that while i is a greater value, j will be incremented more times, which means we want to start off with printing a greater amount of ''s from the start, and after each newline character, slowly narrow that strand of ''s.
The inner loop is essentially there to execute that printf() call exactly i times. So you end up with 4 '*'s for the first iteration, 3 for the next, 2, then 1. Each on a new line.
The number of stars on each row, and the number of rows remaining to print (including the current row) are both equal to i. So i is being used both to countdown the number of rows left to print, and also as the number of stars to print on each row. On the first row i == 4, so you want to print four stars, so you have a loop:
for(j = 1; j<=4; ++j) {
printf("*")
}
next time i will be 3, so the inner loop will be:
for(j = 1; j<=3; ++j) {
printf("*")
}
and so on.
You asked:
for(j = 1; j<=i; ++j){ /*why does j<=i?*/
When i is equal to 4, you want to print four *s.
When i is equal to 3, you want to print three *s.
The check j <= i makes sure of that.
For each loop, you should think about how many times it is iterated.
As you said, in the first for loop,
for(i = 4; i >=1; --i){ ...
This for loop iterates while i >= 1, meaning i changes to 4 -> 3 -> 2 -> 1 (i.e. 4 times = number of rows).
For each row, you want to print i number of *'s, which means you want to repeat the printing process i times for each row. In the nested loop,
for(j = 1; j <= i; ++j){ ...
j iterates while j <= i, meaning 1 -> 2 -> ... -> i (i.e. i times for each row). It is by the way practically the same as
for(j = 0; j < i; ++j) {...
which iterates i times as well.

Why does this second loop have no initialization? And why does it print five stars?

This program produces this output:
*******
*****
***
*
Here's the code:
#include <stdio.h>
int main(void)
{
int i, j;
for (i = 1; i <= 5; i++)
{
for (j = 1; j < i;j++)
printf(" ");
for (; j <= 8 - i;j++)
printf("*");
printf("\n");
}
return 0;
}
What's the meaning of for (; j <= 8 - i;j++)? There is no initialization step and also don't understand why there is only five * on the second line.
For loops don't actually need to have an initialization statement. Many loops choose to include one, but it's not strictly necessary. Consequently, you can think of that loop as saying "we don't need to do anything special here for initialization."
As for why there are five stars on the second line, let's look at this part of the code:
for (j = 1; j < i;j++)
printf(" ");
for (; j <= 8 - i;j++)
printf("*");
On the second iteration, i is equal to 2. When the first loop runs, it will print out a single space character. The loop stops running when j < i is no longer true, so when it finishes running, the value of j will be 2. Therefore, the second loop will run for j =2, 3, 4, 5, 6, stopping when j = 7. That's why you see five stars.
Hope this helps!
What's the meaning of for (; j <= 8 - i;j++)?
That for takes the last (known) value of j used in the program
for (; j <= 8 - i;j++)
printf("*");
Here there is no need for initialization of j as value of j comes from previous for loop.
First case i=1 and j=1 but condition in loop is false and j increments to 2. And this value goes in innermost loop which runs till j=7.
That loop is using the j variable from the for loop directly above it. Each iteration of it is shorter by 2; one from the beginning, and one from the end. That is how it maintains the text centrally on the screen.
So, the first iteration at i=1 will not print any " ". It will then print 7 *, from j values of 1-7.
The second iteration at i=2 will print one " ", followed by 5 *, from j values of 2-6.
Each iteration subsequently follows this pattern.
Okay, j is initialized in the outer most block with respect to the for loops so now j is accessible from all the for loop (or any other loop).
it uses the last modified(incremented) value by the outermost for loop.
i think you can figure it now .
just figure out it by using copy pen and create a matrix for the for loop variables.
it will surely improve your programming skills.
Happy Coding.
you can try this:
variations in for loop in C
#include <stdio.h>
int main(void)
{
int i, j;
for (i = 1; i <= 5; i++) **1**
{
for (j = 1; j < i;j++) **2**
printf(" ");
for (; j <= 8 - i;j++) **3**
printf("*");
printf("\n");
}
return 0;
}
You will find that the variable j does not need to be initialized in loop 3 as it has been initialized in loop 2, and it is within the scope of the local block (j exists within loop 1, and need'nt to be initialised after loop 2).
With regard to your second query,
consider the second iteration of loop1 where i=2. When loop2 completes its execution at this point, j=2. Now consider loop3, where j is 2 (as previously established) and it executes until j is less than or equal to 8-i(8-i=8-2= 6).
So it prints a star for j = 2,3,4,5,6 = 5 stars.
Replace
printf("*");
by
printf("%d", j)
and look how the value of j is changing. This could explain how it works.

Why is this not a infinite loop?

int main() {
int i,j=6;
for(;i=j;j-=2)
printf("%d",j);
return 0;
}
This piece of code gives output 642
please explain me why this loop doesn't run infinitely and stops when j is non-positive
When j becomes 0 the expression i=j evaluates to 0. Hence, the loop terminates.
Note that if j were to start as negative number ( e.g. -1 )or as an odd number (e.g. 5), then the condition will never evaluate to 0 and will result in an infinite loop.
In C 0 is evaluated as false and non-zero as true. The controlling expression i = j becomes false when j = 0 and the loop will terminate.
The loop will go infinite if you change your program to
int i, j = 6;
i = j;
for(; i == j; j -= 2, i = j)
printf("%d",j);
for(;i=j;j-=2)
This is a for loop with no initial code, which on every iteration will assign j to i as the condition check, then at the end decrement j by 2. Note that the value of an assignment expression is the value assigned, hence your i = j expression will yield the value of j.
So, what will happen cycle by cycle is as follows:
Assign i = 6, j = 6
Nothing for the initial for loop statement
i = j (6)
Print j (6)
j -= 2
i = j (4)
Print j (4)
j -= 2
i = j (2)
Print j (2)
j -= 2
i = j (0)
The above expression evaluated to 0, hence false, hence the loop terminates.

Resources