Why does my summation program behaves weird? [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 4 years ago.
Improve this question
Yesterday, I had to do a math introduction test, where I had to calculate the cardinality of a summation. I was lazy to write it out and I thought I'd just write a small C program to solve it. I felt confident that'll work, since I did much more complex programs, but I just can't get it to work.
#include <stdio.h>
int main(){
int i = 1;
int n = 2 * i + 1;
while(n <= 36){
printf("%d\n", n);
i++;
}
return 0;
}
In theory, there should have been the sequence "3, 5, 7, 9, ...", but all I get is "3, 3, 3, 3, ...". It's only not working if I'm using the variable n, if I replace it with i within while everything works as I would expect.
What am I missing?

This:
int n = 2 * i + 1;
Is not a formula for n which gets calculated every time n is used. It sets n to the value of 2 * i + 1 == 2 * 1 + 1 == 2 + 1 == 3 at the time the statement is encountered and that's it. So n never changes inside of the loop and you end up with an infinite loop.
Move the assignment to inside the loop:
while(n <= 36){
printf("%d\n", n);
i++;
n = 2 * i + 1;
}

There is no change of value n in the while loop and so it never fail the condition n <= 36. Maybe you want to do this way
while(n <= 36){
printf("%d\n", n);
i++;
n = 2 * i + 1;
}

It always gives 3 as a result because you do not update n at each iteration. n is calculated once at the beginning. You should calculate n again each time i is incremented.

Related

Why different behaviour of same code by different compilers? [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 2 years ago.
Improve this question
This is code written by me where I have to print a single integer denoting the minimum possible capacity of a tram (0 is allowed). It's a problem from codeforces. The answer in CodeBlocks is showing 6 (the right answer) but in codeforces compiler I'm getting another output.
Why is this happening?
#include <stdio.h>
int main() {
int n, i, j, max = 0, sum = 0;
int pssnger_left;
scanf("%d", &n);
int a[n][2];
for (i = 0; i < n; i++) {
for (j = 0; j < 2; j++) {
scanf("%d", &a[i][j]); // declaring the value of array
}
}
pssnger_left = a[0][0] + a[0][1];
for (i = 1; i < n; i++) {
sum = pssnger_left - a[i][0];
sum = sum + a[i][i];
pssnger_left = sum;
if (max < sum)
max = sum;
}
printf("%d", max);
}
Input:
4
0 3
2 5
4 2
4 0
Output:
4221555
Answer:
6
Checker Log
wrong answer expected 6, found 4221555
Here is the link of the problem: https://codeforces.com/problemset/problem/116/A
Different compiler, different answer, 99% of the cases is explained by Undefined Behaviour, UB.
In the shown code here it is a[i][i];.
For any i > 1 that is not what you want it to be
and for most high i it illegally accesses beyond a.
-> Undefined Behaviour.
A hint on how I spotted this:
Whenever I see [i][i], actually whenever I see [same][same],
I think "diagonal in a square". And in your code I immediatly thought "What square?", because when seeing int a[n][2]; I thought "Long narrow table." and got a conflict of shapes there.
The problem is not basically with the compiler.
You are doing
sum = sum + a[i][i];
but you have declared a 2D array of n x 2 i.e. int a[n][2]
see in some compilers it shows out of bound because you are accessing an element which is not there in the array
and in compilers it just loops in the already existing array for ex if your array has 5 elements and you are trying to access 6th element then it will go back to 1st index,
so this might be whats happening here.

2D array grid in C with different characters for each coordinate [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 4 years ago.
Improve this question
int attack_grid[10][10] = { {0} };
void drawAttackGrid()
{
int i, j, x = 0, y = 0;
for (i = 0; i <= 10 - 1; i++) {
for (j = 0; j <= 10 - 1; j++) {
if (attack_grid[x][y] > 0)
printf(" * ");
else if (attack_grid[x][y] < 0)
printf(" ~ ");
else
printf(" ? ");
y++;
}
printf("\n");
x++;
}
}
So I am trying to fill this 10x10 array with different characters based on the value of the coordinate in other 10x10 array which is filled with zeros only(I'm gonna change those values later so that's why I need it to be general). According to my code it should print only " ? ", but there are some " * " in the output too. Can someone explain me why do i get those " * " there, please?
Your program has undefined behavior due to the value of y.
y gets incremented in the inner loop but never gets reset to 0 when the outer loop is repeated.
In the second run of the outer loop, the value of y will start at 10 instead of starting at 0.
In the third run of the outer loop, the value of y will start at 20 instead of starting at 0.
That goes on for the remaining iterations of the outer loop.
You can remove the redundant indices x and y. Use attack_grid[i][j] instead of attack_grid[x][y]

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

Replacing even numbers with zero - Infinite loop issue in C [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
I've did a program for replacing even numbers with 0 and putting them at the end of the array.
Input: 1 2 3 4 5 6
Output: 1 3 5 0 0 0
The constrains are to use only one loop and two variables apart from the array. I've did it with a while loop but for some unknown reason it loops infinitely. Could someone please clarify?
#include<stdio.h>
#include<stdlib.h>
int main(){
int arr[] = {1,2,3,4,5,6};
int i=0,j=5;
while(i<6){
//Loops till the zero is swapped to the end of the array
if(j!=5){
arr[j] = arr[j] + arr[j+1];
arr[j+1] = arr[j] - arr[j+1];
arr[j] = arr[j] - arr[j+1];
j++; continue;
}
//Checks for even number
if(arr[i]%2==0 && arr[i]!=0){
arr[i]==0;
j=i;
continue;
}
printf("%d ",arr[i]);
i++;
}
return 0;
}
What is causing the infinite loop is this line:
arr[i]==0;
This doesn't update the value of arr[i] when i = 1, so arr[1] is always 2, and this produces that i is stuck always with the value 1. Should be an assignment no a comparison expression:
arr[i]=0;
Note: If you enable the warnings when compiling, the line in question should produce one.

Function that's calculating a log - Unused variable error [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 8 years ago.
Improve this question
I'm writing a function that tries to get the square of a root.
I guess it's easier with an example:
I want to give a number to that function, say 1024 and the function should tell me 12. So always looking for the x here: 1024 = 2^x.
If I gave 255 to the function it should return 7.
Now I guess my maths is pretty okay, but I get an Error saying I didn't use a Variable in Line 6. Could you have a look?
int log_base2(int num)
{
int x = 2;
int count = 0;
for(; x <= num; x * 2 )
{
count++;
}
return count;
}
Error is in line 6 ( for(....))
for(; x <= num; x * 2 )
Here x * 2 calculates its value, and then throws the result out. What you want is probably:
for(; x <= num; x *= 2 )
The error message is perhaps because the compiler optimizes the variable x away as it's useless.
You are not modifying x anywhere. If you want x to become 2 * x in the next iteration you have to change this
for(; x <= num; x * 2 )
to
for(; x <= num; x = 2 * x )

Resources