Why different behaviour of same code by different compilers? [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
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.

Related

Instead of random, it generates sequence of numbers [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
I want to generate x number of random numbers and everything works except it gives me sequenced numbers, not random numbers.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
int x;
printf("How many elements do you want?\n");
scanf("%d", &x);
int *array = (int *)malloc(x * sizeof(int));
srand(time(NULL));
for(int y = 0; y < x; y++){
*(array + y) = 2 + rand() % 99;
}
for(int y = 0; y <x; y++){
printf("Array element %d: %d\n", y, (*array+ y));
}
return 0;}
It gives the numbers like: 27 28 29 30 31, only the first number is random in each execution, others are sequential.
Most likely you're printing a wrong value.
You need to change (*array+ y) to *(array+ y) in printf() statement, otherwise, you end up printing the value of the first random number, plus the iteration counter (which explains the output you get).
Just to add some opinionated view: The array indexing operator [] is there, some chose to prefer using it to avoid mistakes just like this. Your statements can be easily re-written to make use of that, like
for(int y = 0; y < x; y++){
array[y] = 2 + rand() % 99;
}
for(int y = 0; y <x; y++){
printf("Array element %d: %d\n", y, array[y]);
}
That said,
Please see do I cast the result of malloc?
Always check for the success of the called function before using the return value. Check against NULL return of the malloc() call, otherwise you may end up dereferencing NULL, which invokes undefined behavior

Loading an array with the squares of it's subscripts 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 4 years ago.
Improve this question
#define N 500
int subscriptSquares[N];
void loadArray(int nums[], int size)
{
for(int i = 0; i <= (size - 1); i++)
{
nums[i] = i * i;
printf("%i\n", nums[i]);
}
}
What I'm trying to do more specifically is load an array of size 500 with its subscript squares (so subscriptSquares = {0, 1, 4, 9, 16, 25, ...250000}). My problem is somewhere along the line the values are shortened. The last value in the array actually becomes 249001 instead of 250000 and so on so forth. I thought it had something to with the data type so I switched it to double but ended up with same values with the obvious annoyance of decimals. int subscriptSquares[N] is inside the main function. If you need more information let me know
In your code you have defined an array of size 500. It will contain indices from 0 to 499.
So, the last result of your calculation will be 499*499 = 249001.
If you want to get the result of 500*500 then you have to declare an array of 501 locations. The below code shows how.
#define N 501
int subscriptSquares[N];
void loadArray(int nums[], int size)
{
for(int i = 0; i <= (size - 1); i++)
{
nums[i] = i * i;
printf("%i\n", nums[i]);
}
}

Fill a array with numbers from 0-100 [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 5 years ago.
Improve this question
I'm trying to fill an array with integers 0-100.
Here's my code:
int main()
{
int a[100];
for(int i = 0; i < a; i++)
{
a[i] = i;
printf("\n%d\n", a[i]);
}
}
I get this error:
comparison between pointer and integer (int and int) over the for line.
I can't figure it out. Any thoughts?
The cancel condition in your for loop is wrong. i<a You are comparing an int i variable with the pointer a that points to the memory location of the array. You would need to calculate the length of the array:
for(int i=0; i<sizeof(a)/sizeof(int); i++) {
But you could have found this solution in this 9 year old answer
Yes you are comparing pointer with an integer. This is why the error.
for(size_t i=0; i<sizeof(a)/sizeof(a[0]); i++) {
is what you wanted it to be and can be done in C language. Remember that sizeof operator results in value in size_t.
If you are not aware what that sizeof is doing - it is basically total number of bytes that the array object has - divided by each element's size - resulting in number of elements.
In case you are thinking from where did that pointer come?
Note one thing here a is converted into pointer (array decaying)to the first element - so it is nothing other than a pointer to the first element.
This should work for you,
int main()
{
int a[100];
int n = sizeof(a) / sizeof(a[0]); //Get the size of the array
for(int i=0; i<n; i++) { // loop through each elements of the array
a[i] = i;
printf("\n%d\n", a[i]);
}
}

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

Unable to use variable value outside for loop in C program [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 am following a introductory C programming course and the first assignment is to find number of perfect squares in a given range.
I am trying to get the first perfect square root, but when I try to assign the first square root to a variable, i am unable to do so and it always shows 0.
This is the program that I have written:
#include<stdio.h>
void main()
{
float y= 0;
float k = 1.0;
float n;
int i=0;
int first_sqrt;
first_sqrt = 0;
printf("enter number: \n");
scanf("%f",&n);
// finding the first perfect square
for(y = 0; y<=10000; y++)
{
while((k*k - n)>0.0001 || (n - k*k)> 0.0001)
{
k = (k + n/k) / 2;
//printf("%f\n", k);
}
i = (int)k;
if(i*i == n)
{
printf("perfect squareroot: %d\n", i);
i = first_sqrt;
y = 10001;
//break;
}
else
{
printf("not perfect square: %f\n", n);
n = n+1;
}
}
printf("first perfect square root: %d\n", first_sqrt);
}
I am sorry for posting the whole program, but I have no idea where the problem might be. This is the first assignment of the first week so I don't have understanding of a lot functions in C yet and I can't use math function for this assignment.
Any help would be appreciated. Have been searching all day about this but couldn't understand much.
A basic direction towards the problem would be most appreciated. Thanks.
The expression i = first_sqrt; assigns first_sqrtto i and not i to first_sqrt. Change it to first_sqrt = i;. Apart from this you can remove the comment from //break;.
Reverse this line
i = first_sqrt;
to first_sqrt = i;
You mixed up an assignment. This:
i = first_sqrt;
Should be:
first_sqrt = i;

Resources