Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I am doing a past exam question where i am asked to describe what the following c code implements and re write it with meaningful variables names and good programming practices.
The code is as follows:
void h(int ** a, int b){
for(int x=1; x<=b; x++)
for(y=1; y<=b; y++)
a[x-1][y-1]= (i/j)*(j/i);
}
I dont understand how this code works as:
1) y is never declared in the for loop.
2) the arithmetic of i and j doesn't make sense to me either if i and j are not declared.
I originally thought this was a intake and that i and j are just x and y. But if that was the case the question would have been very easy compared to any other i have already completed.
The code is probably intended to create an identity matrix with 1's on the leading diagonal and 0's elsewhere.
The Fortran equivalent of that code is used as the first example of bad code in the classic Elements of Programming Style by Kernighan and Plauger.
Working from memory, the Fortran code was roughly:
DO 10 I = 1, N
DO 10 J = 1, N
10 A(I,J) = (I/J)*(J/I)
(There might have been two labels, 10 and 20 say, and one or two continue statements, but I think it was like that. At the time, columns 1-5 were reserved for numeric labels, column 6 was a continuation indicator, and the program occupied columns 7-72, with columns 73-80 being an optional statement sequence number.)
Since y is used but not declared, if it compiles, y must be an external variable (either a global variable or a variable with file scope: extern int y; or int y; or static int y; outside the function).
Since i and j are used but not declared, if it compiles, they too must be external variables. And given that neither i nor j is changed, the same value (either 0 or 1, depending on whether i != j) is in fact assigned to each element of a.
The more nearly 'correct' code implementing the same (bad) algorithm should be:
void h(int **a, int b)
{
for (int x = 1; x <= b; x++)
for (int y = 1; y <= b; y++)
a[x-1][y-1] = (x/y)*(y/x);
}
Of course, this is not very C-like, but it does avoid divide-by-zero problems. However, cleaner and simpler code can be written:
void h(int **a, int b)
{
for (int x = 0; x < b; x++)
{
for (int y = 0; y < b; y++)
a[x][y] = 0;
a[x][x] = 1;
}
}
The function should be renamed to something more meaningful.
To complete the answer given above, all the undeclared variables should been understood to have been declared in a larger scope. If you are sure that it is indeed i and j (and both are int) then it will be a zero matrix or a martix of ones(if i = j ).
Related
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 8 days ago.
This post was edited and submitted for review 7 days ago.
Improve this question
I am writing a program where several functions are performed within a while loop. When I run the program, nothing inside is done, though. Only the things written before the while loop were performed. Here is the code:
int main() {
int x;
int y;
int a = 1;
for (x = 0; x < 9; x++) {
for (y = 0; y < 9; y++)
board[x][y] = '\0';
}
displayBoard();
while (cWhoWon == '\0') {
printf("\n%c\n", cWhoWon);
if (iCurrentPlayer == 1 || iCurrentPlayer == 0) {
printf("\nPLAYER X\n");
and so on with nested loops until this if loop ends. (it's indented properly in the real code, i appreciate your patience) No malloc was used, nor struct - I am only a beginner with knowledge of arrays, loops, booleans, and basic functions like isdigit.
I tried to add another condition, a = 1, to the while loop with the 'and' boolean operator (&&) and ';' but the same thing happens. I thought that this would make the while loop iterate, at least, but it doesn't. Is it my compiler? I'm using "OnlineGDB.com" C compiler.
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
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
Hy, I want to understand why variable b don't change and when I print it always be as I defined (zero). What's wrong with my code??
With this code I want to find the max integer number (b) that is 10^b <= n (with n given and integer as well).
This is my code (It's written in c):
#include <stdio.h>
#include <math.h>
int lg (int n);
int main() {
int a = 0;
scanf("%d", &a);
printf ("\nN=%d e M=%d\n", a, lg(a));
return 0;
}
int lg (int n) {
double b = 0.0;
for (int i=0; i==n; i++) {
if (pow(10, i) <= n) {
double b = i;
} else {
}
}
return (int)b;
}
You're declaring a new variable named b inside your loop and setting it equal to i. Since that's a different scope, it's not the same variable as the b declared before the loop. Change the line
double b = i;
to
b = i;
Your loop condition is also set to i==n;. That means your loop will only run once if your input is 0. That should probably be i < n;.
There are two variables named b. One whose scope is the function lg, and one whose scope is restricted to the if clause of the for loop. You modify the latter, but return the former. Using the keyword 'double' declares a new varaible. This is a common source of error, and simply turning up the warnings on your compiler should alert you to the problem.
You are declaring "b" variable twice.The "b" variable initialized with 0.0 have scope within the function "lg". And the "b" declared inside if codition have limited scope to that condition only.
Also check the second parameter of for loop i.e "i==n". This is statement would be always true i.e "1" if the value of input ("n") is not zero.
Error 1: i==n: if you compare i==n in a for loop, that loop will only run a time.You must fix it into i<n
Error 2: You repeated a double type. You mustn't declare a variable b in a for loop because the variable b in that loop will disappear from the loop when it stop repeating.Thus, the value of the variable b in the for loop won't assign.
You must delete the double keyword in the for loop, the variable b will change.
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 6 years ago.
Improve this question
I declared a two dimensional array as row and col and I left the value empty, but when I check the value in each array position, some of the indexes contain some weird number.
You are looking at uninitilized memory. It can have whatever which value to it. You should never trust the value of a variable you haven't initialized.
Access of an uninitialized value is undefined behavior. You can solve your problem quite simply by initializing the array to all zero to begin with, e.g.
int seatNo[5][5] = {{0}};
Now any subsequent access to any of the elements of seatNo will succeed because each element has been initialized to zero. As a rule, especially when you are learning C, you will save yourself grief if you simply initialize ALL your variables.
(you will also want to turn warnings on, e.g. -Wall -Wextra, at minimum, so your compiler will warn you when a variable may be uninitialized)
#include <stdio.h>
int main (void) {
int seatNo[5][5] = {{0}};
for (int i = 0; i < 5; i++)
for (int j = 0; j < 5; j++)
printf (" seatNo[%d][%d] = %d\n", i, j, seatNo[i][j]);
return 0;
}
Example
$ ./bin/initarray
seatNo[0][0] = 0
seatNo[0][1] = 0
seatNo[0][2] = 0
seatNo[0][3] = 0
seatNo[0][4] = 0
seatNo[1][0] = 0
seatNo[1][1] = 0
<snip>
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
Using a local variable in its own initialization usually has no effect but doing it with recursion causes strange values. Why is there undefined behavior in the recursion but not outside of it?
#include <stdio.h>
void recurse(int count);
int main()
{
int j = j + 1; // a weird thing to do but its just 1
printf("%d\n", j);
j = j + 1;
printf("%d\n", j);
j = j + 1;
printf("%d\n", j);
recurse(1);
printf("\n");
}
void recurse(int count){
int i = i + 1; // the really weird part
printf("%d ", i);
if(count < 10)
recurse(count + 1);
return;
}
Output:
1
2
3
32737 1 32737 1 1 1 1 1 1 1
The large numbers are not always the same for each execution.
This is an example of undefined behavior.
Because the value can't be known before it is assigned, you can't predict what will happen. Running the same code on a different machine, or compiled with different settings, can yield different results.
Local variables (not initialized) have indeterminate value in C.
Reading them prior to assigning a value results in undefined behavior.
Nice quote from wikipedia article
In computing, an uninitialized variable is a variable that is declared
but is not set to a definite known value before it is used. It will
have some value, but not a predictable one. As such, it is a
programming error and a common source of bugs in software.
However, it is important to mention that in C, static and global variables not initialized will have the value = 0.