Variable Number of for loops with code in between [closed] - c

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 6 years ago.
Improve this question
So the problem I have is that I want to implement N for loops in the following way (where N is a variable):
for i0=0:MAX
cOR[0] = initial + move[i0];
for i1=0:MAX
cOR[1] = cOR[0] + move[i1];
....
some other stuff inside the final loop
(cOR is a vector of length equal to the number of for loops)
So I found this solution that works when you just have the nested loops (https://stackoverflow.com/a/20577981/3932908) but have been struggling to modify it for my particular case which requires code in between the for loops. Is there a simple way to implement this or is a different approach needed?

The general approach is to
Write a recursive function.
If recursion is not for some reason appropriate for your code (e.g. very long recursion depth, or the ability to suspend the execution is required), then convert the recursive version to an iterative one by explicitly modeling the stack.
Doing №1 is easy:
void f(int depth, int initial, int *cOR)
{
if(your termination condition)
{
// some other stuff inside the final loop, and...
return;
}
for(int i = 0; i < MAX; ++i)
{
cOR[depth] = initial + move[i];
f(depth+1, cOR[depth]);
}
}
And call it like so:
f(0, initial, cOR);
Now we head to №2, i.e. converting to a non-recursive version. The extra state we need is what was stored on the stack before: the values of the i variables. So here we go:
int i[max_depth];
int depth = 0;
for(;;)
{
if(your termination condition)
{
// some other stuff inside the final loop, and...
do {
if(--depth < 0)
return;
} while(++i[depth] >= MAX);
}
else
i[depth] = 0;
cOR[depth] = (depth > 0 ? cOR[depth-1] : initial) + move[i[depth]];
++depth;
}
If you can't estimate max_depth a priori then you can switch to a dynamically allocated array that grows as you need.

Related

C - struggling to understand how to use int function within if/ while loops [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 2 years ago.
Improve this question
So I'm doing CS50 and struggling with an error that occurs when I include the following two lines:
if (int i < (number -1))
if (int i =< number)
when compiling, 'error: expected expression' comes under 'int'. Am I using it incorrectly within while if statements?
No you can not declare variable in an if statement. But if you want your variable in a local scope you can create a block and declare your variable, initialize it and use. We have to use <= for checking less than or equal to instead of =<
example:
{
int i =5,number=10;
if(i < number-1)
{
//Add your code
}
if(i <= number)
{
//Add your code
}
}
int i; is a variable declaration/definition.
That confuses your compiler when it tries to understand your if condition.
I have to guess a little, but am confident. You probably want
if (i < (number -1)){ /* assuming code here */ }
if (i <= number) { /* assuming code here */ }
Note that is also changed =< to <=.

Why not use a while loop for FIZZBUZZ in C? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
Only been coding in C for about a month, but wondered why the while loop wasn't used more often for FIZZBUZZ. Is it not as clean or some other reason? Here's what I came up with:
int main()
{
int num=1;
while(num<=100)
{
if (num%3==0 && num%5==0)
{
printf("FIZZBUZZ!!!\n");
}
else if (num%3==0)
{
printf("FIZZ!!!\n");
}
else if (num%5==0)
{
printf("BUZZ!!!\n");
}
else
{
printf("%d\n", num);
}
num++;
}
return 0;
}
Your loop can be neatly folded into a for loop:
for(int num = 1; num <= 100; ++num)
There are two advantages here:
num is scoped inside the loop, when before it was bleeding into whatever scope followed the while. Restricting variables to the minimum possible scope is a good rule of thumb, because it minimizes the amount of variables to think about at any given point.
The range over which your program will operate is now summarized in a single place: you can see the bounds (1 to 100) and the step (1) inside the for. That kind of ranges is pretty well balanced to be read and memorized quickly before reading the body of the loop. For example, if you now wanted to only check odd numbers, it would be immediately clear from reading the num += 2 in the for header, rather than stumbling upon it at the very end of the loop's body.

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).

Language c slowing down loop [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 7 years ago.
Improve this question
I have for loop which makes falling effect in matrix. I am generating numbers in the first row of matrix and the fall.
#include <stdio.h>
#include <stdbool.h>
#include <Windows.h>
void hra(){
.....
do {
for(int i = V; i > 0; i--) {
for(int j = 0; j < S; j++) {
mat1[i][j] = mat1[i - 1][j];
}
}....}
}
But now its too quick. When i use Sleep() it will slow down everything (user input etc..)
Is there a way to slow down only this loop (and gradually make it quicker)?
//
I am sorry I should have mentioned that the user sees the falling numbers and have to interact with them (the numbers fall at the bottom of the matrix where they get stored or they get erased by user). So I want them to "fall" slowly so the user can see them and decide which ones he want or dont. And V is 10 and S 4.
The solution you are looking for is multi-threading. Have the main thread do the calculations, have another thread do the graphics and a third thread handle to user input.
usleep() takes a time in microseconds as parameter, you could put a variable as value and then decrement it. Per example if you want to slow down this for:
for(int i = V; i > 0; i--)
you could add:
usleep(x * i);
in it. (Where x is whatever you want.) Feel free to use any equation you want to choose the way it will slow down.

Why a for loop isn't considered 'stylish' by my teachers? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I had to write a piece of code which would search a given value in an array.
I made this piece of code, which works:
#include <stdio.h>
int index_van(int searchedValue, int array[], int lengthArray)
{
int i ;
for (i = 0; i < lengthArray; i++)
{
if (array[i] == searchedValue)
{
return i;
}
}
return -1;
}
int main()
{
int array2 [] = {0, 1, 3, 4, 5, 2};
printf("%i", index_van(2, array2, 6));
}
With the correction (the teacher put up online) of this exercise the notes of my teacher were:
You have to quit the moment you have found your value ,so you can't search through the entire table if you have found your value already. A for-loop therefore isn't tolerated.
Even if the for-loop has an extra built-in condition, THIS ISN'T STYLISH!
// One small note ,she was talking in general . She hasn't seen my version of the exercise.
So my question to you guys is, is my code really 'not done' towards professionalism and 'style' ?
I think she's implying that you should use a while loop because you don't know how many iterations it will take to get you what you're looking for. It may be an issue of her wanting you to understand the difference of when to use for and while loops.
"...Even if the for-loop has an extra built-in condition..."
I think this right here explains her intentions. A for loop would need a built-in condition to exit once it's found what it's looking for. a while loop already is required to have the condition.
There is nothing wrong with your code. I have no idea if using a for loop is less stylish than using another, but stylish is a very subjective attribute.
That being said, don't go to your teacher and tell her this. Do what she says, a matter like this is not worth contradicting your teacher for. Most likely this is just a way to teach you how while loops work.
After accept answer:
I've posted this to point out sometimes there is so much discussion of "style", that when a classic algorithmic improvement is at hand, it is ignored.
Normally a search should work with a const array and proceed as OP suggest using some loop that stops on 2 conditions: if the value was found or the entire array was searched.
int index_van(int searchedValue, const int array[], int lengthArray)
But if OP can get by with a non-const array, as posted, then the loop is very simple and faster.
#include <stdlib.h>
int index_van(int searchedValue, int array[], int lengthArray) {
if (lengthArray <= 0) {
return -1;
}
int OldEnd = array[lengthArray - 1];
// Set last value to match
array[lengthArray - 1] = searchedValue;
int i = 0;
while (array[i] != searchedValue) i++;
// Restore last value
array[lengthArray - 1] = OldEnd;
// If last value matched, was it due to the original array value?
if (i == (lengthArray - 1)) {
if (OldEnd != searchedValue) {
return -1;
}
}
return i;
}
BTW: Consider using size_t for lengthArray.

Resources