The logic of nested loops in C [closed] - c

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am new to programming and I'm following the CS50 course. I'm trying to fully understand the logic behind nested loops in C. I think I've got it, but I'd like to be sure before I move on to the next set of problems. Here's the code (provided by the course). It creates a cube made of hashes. My explanations are below the code.
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n, j++)
{
printf("#");
}
printf("\n");
}
The first loop starts: It creates a new variable called i and sets it to 0. The command checks the new variable: If it is lesser than n (true), run it, starting the inside loop.
The inside loop also creates a new variable, j, sets it to 0, checks it and, if it is true (j < n), runs the code below and print a hash. Afterwards, the inside loop is incremented and this process occurs again until the inside loop condition is not met anymore. This will create a ROW of hashes if n is greater than 2.
The outer loop creates a new line, increments and the process starts all over again. It will run until the condition is false (i > n).
The next times the inside loop is accessed, the variable j is set to 0 again, that's why it is possible to print various rows in this program.
Is that correct? Thank you very much in advance!

Yes, your explanation is spot on.
With a minor mistake:
It will run until the condition is false (i > n).
The condition is false when i >= n.
And what I assume it's a typo:
for (int j = 0; j < n, j++);
// ^
// |
remove the ;

Related

In C, what happens when the condition for a for loop aren't met at the beginning? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
For example, what happens if I say:
for(i = 2; i < 2; i++)
Obviously, this is a useless for loop, but maybe i = a, and a is set by something else. So what happens in this case?
Neither iteration of the loop will be executed.
In fact this loop (provided that the condition has no side effects)
for(i = 2; i < 2; i++) { /* ... */ }
is equivalent to this statement
i = 2;
The condition of a for loop is checked before every iteration, including the first one; so your loop's body will never be executed.
The way for loop works is it checks for condition (in your case i < 2) and executes whatever is between { } or whatever code on following lines
As you are initializing i to 2 the condition fails immediately and nothing executes.
Essentially whatever code that is inside of for loop never executes.
In a for loop, the condition is evaluated before the first iteration. This means that in your example, the content of the loop would not be executed because i is already greater than or equal to 2.
Example code path:
Set i = 2.
Check if i < 2.
Exit loop because step 2 evaluated to false.
i would still be modified, however, as the variable initialization (i.e. i = 2) still occurs before the condition is checked.

for loop in c not outputting full array [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
this is a simple question as i'm a new-comer to C. I am trying to write a script for outputting an array of the tangents of radians, of multiples of 5 from 0-60. but for some reason the for loop i have written only does this for the first element, and all other elements in the resulting array are 0.00, and it wont print them for each loop. i'm sure i've done something simple wrong with my loop, but i just can't see it.
#include <stdio.h>
#include <math.h>
float rad(float degree){
return degree*M_PI/180;
}
int main(void){
int i, j, dim=13;
float Tan[dim];
for(i=0; i<13; i++);{
j+=5;
Tan[i]=tan(rad(j));
printf("%f\n", Tan[i]);
}
return 0;
}
First of all, in your code
j+=5;
is undefined behavior, as the intial value of j is indeterminate. To elaborate, j is an automatic local variable and not initialized explicitly, so the content is indeterminate.
Then, the for loop is also buggy.
for(i=0; i<13; i++);
should be
for(i=0; i<13; i++) // no ; here
to have a meaningful loop body to be executed.
1. You have inserted a semi-colon which you shouldn't have. Change your loop to :
for(i = 0; i < 13; i++){ //erase the ; after the parenthesis
j+=5;
Tan[i] = tan(rad(j));
printf("%f\n", Tan[i]);
}
2. Initialize variable j before trying to increase it with the statement j+=5, as this will lead to undefined behaviour.
There are two problems in your code :-
1) You haven't initialized j here int i, j, dim=13;
2) The way you used for loop is as per your requirement.Remove semicolon from the for loop statement.

What is the complexity of the following simple program? [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 6 years ago.
Improve this question
I am having trouble finding understanding complexity. Could someone help me understand what the complexity of the code below is and why.
for (int i = 1; i < n; i++) { // (n is a number chosen by the user)
for (int j = i - 1; j >= 0; j--) {
printf("i=%d, j=%d", i, j);
}
}
An explanation would be great.
Assuming i starts at 0, the complexity would be constant. The complexity is always expressed relative to a variable defining the number of executions, which is not the case here.
If one term should be used to describe this behavior, it is "constant". There will be a number of executions, but this number will never change
Original Question: Because i's initial value is undefined, the behavior of the code is unpredictable. There is no way to usefully answer the question other than that the complexity is undefined. There is no way to know how many operations the code will perform.
Updated Question: It's O(1). The code will always do precisely the same amount of work.
You can compute the time complexity of this code fragment by evaluating the number of operations, namely the number of calls to printf() which for simplicity's sake we shall assume to be equivalent:
Assuming i starts at 1 (you initially forgot to initialize it), the outer loop runs 99 times, for each iteration, the inner loop runs i times. Gauss was supposedly 9 years old when he computed the resulting number of iterations to be 99 * (99 + 1) / 2.
The complexity of the original piece of code was O(1) since it did not depend on any variable, but since instead you updated the code as:
void fun(int n) {
for (int i = 1; i < n; i++) {
for (int j = i - 1; j >= 0; j--) {
printf("i=%d, j=%d", i, j);
}
}
}
The time complexity would come out as O(n2).

For looping in C confused [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 6 years ago.
Improve this question
What problem if I use strlen() in the condtion of for loop.
char s[i];
for (int i = 0; strlen(s); i++)
So if I use upper code there took a lot of time.
But if I store the value of strlen of s it took little time inspect to upper code.
What difference between these?
You should not use i < strlen(s) as a condition because the length of the string in s gets recomputed for each iteration of the loop. It is better to use a separate variable and compute the length in the initialization part:
for (size_t i = 0, len = strlen(s); i < len; i++) {
...
}
Note that your definition of s looks like a typo: char s[i];. What variable i are you referring to? what would be its value before the beginning of the for loop that defines a new i variable?
EDIT
After reformatting your code, I realized there is even more confusion:
for (int i = 0; strlen(s); i++)
This for loops iterates as long as string s is not empty. Is this your intent? Do you modify s inside the loop? s is uninitialized, the test invokes undefined behavior. Do you initialize s in code you did not post between the definition and the for loop? If you do, it would still be more efficient to write such a loop this way:
for (int i = 0; *s != '\0'; i++)
The condition is evaluated before every iteration of the loop.
C strings are just an array of characters, then a NULL. So to work out the length you have to start at the start and inspect every character from there until you find the NULL.
So in complexity terms, strlen is O(n). Your for is also O(n). If you check the strlen every time then your implementation is O(n*n). If you work it out once in adavance then yours os O(n). Try it with longer ss to see a much bigger difference.

Stumped: for loop to build an array not working, initial condition ignored? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
This one has me stumped. Here is my code to build an array, b[i] of doubles, from 0 to N where N = 126.
int N = 126;
double b[N];
int i;
for(i = 0; i < N; i++);
{
b[i] = (double)i;
printf("b[%lf] = %d\n",b[i], i);
}
For some reason, this is what I get:
b[126.000000] = 126
and nothing else. The initial condition of i being at 0 is ignored, and for some reason it sets i to be the value of N. Strange!
I'm a bit of a c novice so I must be missing something obvious. Any help greatly appreciated!
Andy.
The mistake is at you using the ; at the end of the for loop statement. That is why the program is simply executing the remaining statements as if they are in no loop, and at that time i has become 126.
Remove the ; on the end of the for loop, it is running through the loop without doing anything then executing the body for the last value of i(which is N = 126)

Resources