Initializing a matrix with 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 1 year ago.
Improve this question
I can't imagine a simpler case of matrix initialization, and yet it goes horribly wrong, with the program getting into an endless loop. WHY????
#include <stdio.h>
int main ( void )
{
int M [ 5 ] [5] = {{}} ;
int i , j ;
for ( i = 1 ; i <= 5 ; i ++ )
{
for ( j = 1 ; j <= 5 ; j ++ ) M [ i ] [ j ] = 1 ;
}
return 0 ;
}

Indexes in arrays start from zero.
So the code should be
#include <stdio.h>
int main(void)
{
int M[5][5] = {{}} ;
int i, j ;
for (i = 0; i < 5; i ++ )
{
for (j = 0 ; j < 5 ;j ++ ) M[i][j] = 1 ;
}
return 0 ;
}

Not only, at stated above, indexes start with 0, not 1, which would lead you to write
for (i=0; i<5; i++)
… instead of :
for (i=1; i<=5; i++)
… (note the < sign instead of <=) but if you do it anyway, nothing will prevent you from doing. Since the machine code produced by your C compiler sticks to adding the index to the base pointer, you'll exceed the end of your array, thus leading to a buffer overflow.
And what lies after the array you declared are your index variables i and j. Since you fill your array with ones only, you'll write 1 into your index variables each time you run out of your array, hence resetting it to this particular value, and that's why your loop will never end.

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.

Two similar for-loops give different results [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 3 years ago.
Improve this question
just playing around with for loops, and wanted to see what the results are.
I'm assuming both produce the same results, but I'm wrong.
int sum ,sum2 , i , j;
for( sum = 0, i = 1 ; i <= 5 ; sum+=i , i++ )
printf("%d\t",sum);
printf("\n");
for( sum2 = 0, j = 1 ; j <= 5 ; j++ ) {
sum2 +=j;
printf("%d\t",sum2); }
0 1 3 6 10
1 3 6 10 15
In the first loop sum is incremented at the end of the iteration, so after the call to printf, while in the second loop sum2 is incremented before the call to printf.
If you follow the execution pointer carefully, in the first loop sum += i occurs before i is incremented.
In the second loop, sum2 += j occurs after j has been incremented.

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 reason why isn't this code running properly 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 5 years ago.
Improve this question
I am trying to learn C but my code is not running properly.It always gives fatal error.I think there is a problem in for loop.How can i fix it?
#include<stdio.h>
int main( void )
{
int a ;
int b = 1 ;
int i = 0 ;
printf("Enter a number:");
scanf("%d",&a);
if(a=0)
printf("Factorial=1");
else if (a > 0){
for(i=1 ; i<=a ;i++){
b = 1;
b *= i;
}
printf("Factorial=%d",b);
}
else
printf("FATAL ERROR");
return 0;
}
if(a==0) Not assignment use comparison.
You wanted to use the comparison but you ended up using assignment.
if(a=0) is same as if(0) so else part is executed.1
But that part also looks for a>0 which is not the case.
So it prints FATAL ERROR.
1. This happens because the result of an assignment expression is the value of the expression
What do I need to do to calculate factorial?
fact(0)=1
fact(1)=1
fact(n)=n*fact(n-1);
so you will do something like
for(int i=1;i<=a;i++)
b*=i;
You don't need that b=1 part because it is making everything 1. So your calculated value is not retained.
So the complete corrected code will be
#include<stdio.h>
int main()
{
int a;
int b = 1 ;
int i = 0 ;
printf("Enter a number:");
scanf("%d",&a);
if(a=0)
printf("Factorial=1");
else if (a > 0){
for(i=1 ; i<=a ;i++){
b *= i; // don't overwrite value of b with 1
}
printf("Factorial=%d",b);
}
else
printf("FATAL ERROR");
return 0;
}
There are two major issues.
First being your use of if(a=0) which results in assignment in place of comparison which is achieved by if(a==0).
Secondly
for(i=1 ; i<=a ;i++)
{
b = 1;
b *= i;
}
This piece of code is faulty too. You are making b=1 after every iteration which overwrites the intermediate results Hence resulting in incorrect answer. As you have already initialized b to 1 in your code, you do not need this line at all.
for(i=1 ; i<=a ;i++)
{
b *= i;
}
Also it is worth mentioning that the reason you are always getting fatal error is because of what you are doing in the if condition. Due to if(a=0), variable a is assigned value 0 . Hence not satisfying both if and else if conditions and resulting in the execution of else block every time.

Using arrays in C (error in the output) [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 had this task :
Given the following array, write a program that reverses all array elements then prints them.
int x[] = {1,2,3,4,5,6,7,8,9,10};
then i wrote that code :
int main() {
int x[] = {1,2,3,4,5,6,7,8,9,10};
int y[10] ;
int i;
i=0 ;
for(i=0 ; i<10 ; i++) {
x[i]=y[9-i] ;
}
printf("\r\n The reversed array is : \r\n{ ") ;
i=0 ;
for(i=0 ; i<10 ; i++) {
printf("%d \t ,",y[i] ) ;
}
printf("}") ;
return(0) ;
}
and the output was this
what is wrong with the code ?
The problem is in this line:
x[i]=y[9-i] ;
You are assigning to x; however, x is your input data. The y array is uninitialized, so when you assign values from it to x, you get garbage data. This is why generic variable names like x and y are generally discouraged; it's easy to mix them up and make mistakes like this.
Anyway, if you switch that around, and assign the values from x to y instead, it should fix your problem.

Resources