#include <stdio.h>
main()
{
int a[2][5], i,j; //2d array declaration
for(i=0;i<=1;i++) //first loop for 1st dimension
{
for(j=0;j<=4;j++) //nested loop for 2nd dimention
{
printf("Value for a[%d][%d] is : ", i,j);
scanf("%d", &a[i][j]); //asks for value
}
}
}
In this program, when the loop is executing, in the first run, i=0, and inside that j=0,1,2,3,4.
When this is done and it comes to the 2nd dimension where i=1, why does it run the nested loop again when the condition is already false (j<=4)?
Where are all these constant values saved? Does it restart the value of j when the nested loop is run again?
A for loop has three components (expressions) in the form for (A;B;C):
A - Pre-Iteration, run once at the start
B - Loop Condition, tested before each iteration, including the first
C - Post-Iteration, executed after each iteration
You're asking to initialize j=0 each time the loop starts, then testing j <= 4 which will be true. When the loop repeats it does j++, then tests again.
It's worth noting that these are all optional and for (;;) is valid, but is an infinite loop unless you break it.
With minor improvements:
int main(void) //added int and void to main
{
int a[2][5], i,j; //2d array declaration
for(i=0;i<2;i++) //first loop for 1st dimension
{
for(j=0;j<5;j++) //nested loop for 2nd dimention
{
scanf("%d", &a[i][j]); //asks for value [note, before printf]
printf("Value for a[%d][%d] is %d\n: ", i,j, a[i][j]);
}
}
return 0;//int main(void) requires a return statement
//Note also, 'main()' is really not a proper signature for
//the main function
}
This code intends to assign values to each member of the 2D array by using prompted input values using scanf, but because of some syntax and logic errors, the original would not work as intended. To help, the order of the two lines in the nested for loops has been switched to prevent the array from being accessed before being initialized.
The nested for loop indexes have been modified in this version to use the same values for limit, as those used to size the array in its declaration:
int a[2][5];
for(i=0;i<2;i++)
for(i=0;j<5;i++)
scanf() is the method used for user input. Each call prompts for a value, which is placed into the corresponding row-column index indicated by i and j, and written to stdout. Note the actual value in the original code is not printed out, but it is in this slightly modified version.
The value of j is initialized to 0 each time you run the nested loop because you set the initialize expression of the for statement to "j=0"
That expression will be run for each execution of the outer loop
Related
in learning quick union algorithm, i have met these two statements
for(i=p; i!=id[i]; i=id[i]);
for(j=q; j!=id[j]; j=id[j]);
since I only learned for loop to be something like
for(i=0; i<100; i++)
I don't know the difference between the two statements and the following statements
i=p; i=id[i];
j=q; j=id[j];
i have no idea why the results are different?
thanks
I want to ask why
#include <stdio.h>
#define N 10000
int main()
{
int i, j, p, q, id[N];
for(i=0; i<N; i++) id[i]=i;
while(scanf("%d %d\n", &p, &q)==2)
{
for(i=p; i!=id[i]; i=id[i]);
for(j=q; j!=id[j]; j=id[j]);
if(i==j) continue;
id[i]=j;
printf(" %d %d\n", p, q);
}
}
is different from
#include <stdio.h>
#define N 10000
int main()
{
int i, j, p, q, id[N];
for(i=0; i<N; i++) id[i]=i;
while(scanf("%d %d\n", &p, &q)==2)
{
i=p; i=id[i];
j=q; j=id[j];
if(i==j) continue;
id[i]=j;
printf(" %d %d\n", p, q);
}
}
I have tested the results, that's why I am confused
i=p;
Sets i to the value of a variable p (defined and initialized elsewhere in the program)
i=id[i]
Sets i to the value of the i th element of the array id (defined and initialized elsewhere in the program)
for(i=p; i!=id[i]; i=id[i]);
Loop initializes i to the value of p, executes the statements inside the for loop once if i is not equal to the i'th value of the array id, and then stops.
Further explaination:
assuming some values for the variables:
int p = 4;
int i;
int id[5] = {1,2,3,4,5};
for(i=p; i!=id[i]; i=id[i]) {
printf("Loop executed!\n");
}
Output:
Loop executed!
And then a segmentation fault.
What happens:
i is set to 4, then compared to id[4]. This is unequal, thus the loop is triggered. After that it sets i to 5. Now it tries to compare id[5] to i. This is disallowed because id only has space for 5 elements and indexes start at 0.
When looking at non-standard for "loops" like this, it helps to convert your for loops into while loops. (that is all they really are)
To do that, remember that a for loops consists of three parts separated by semicolons. The initialization part, the conditional part, and the update or increment part:
for(initialize statement; boolean loop conditional; update/increment statement);
The initialize statement is executed before your loop, the loop conditional is evaluated to determine whether the loop continues, and the update/increment statement is executed as the end of the loop.
Your first example:
for(i=p; i!=id[i]; i=id[i]);
As a while loop, looks like..
i = p
while(i!=id[i]) {
i = id[i];
}
Your second example:
for(j=q; j!=id[j]; j=id[j]);
As a while loop, looks like..
j = q
while(j!=id[j]) {
j = id[j];
}
Once they're written like this, it's easier to tell what's going on.
We're initializing the loop variable to one of two values, p or q.
Then, we're looking into the array "id" at the location specified by the loop variable and updating the loop variable with it. This has the effect of looking up in the array the next loop variable. In other words, each slot in the array contains the next value to jump to.
The conditional checks to see whether the destination is the same as the current location. That is to say, if we are "told" to jump to the location we're already in.
The difference between you two loops is only the initialization value. The first one initializes to p where the second initializes to q.
It may be helpful to manually jump through a simple cases such as..
p=0
q=1
id = {1,2,2}
p=2
q=1
id = {0,0,2}
#include<stdio.h>
int main(void) {
int arr[7];
int i;
int copy[7];
int j;
int *ptr_copy;
int *ptr_arr;
ptr_arr=&arr[0];
ptr_copy=©[0];
printf("Enter 7 Element In the Array");
for(i=0;i<7;i++)
scanf("%d",&ptr_arr[i]);
printf("\n");
for(i=7,j=0;i>=0;i--,j++)
ptr_copy[j]=ptr_arr[i];
for(i=0;i<7;i++)
ptr_copy[i]=ptr_copy[i]*-1;
printf("%d",ptr_copy[i]);
}
In the last loop I thought if I multiply the loop by -1 all the numbers' signs will change, is that correct? And in the last loop I'm not sure if it's correct. Could you help me and tell me where is the mistake?
You have undefined behaviour in this code . As you access index out of bound here -
for(i=7,j=0;i>=0;i--,j++)
ptr_copy[j]=ptr_arr[i];
ptr_array[7] isn't there . Array is till index 6. ptr_arr[7] contains garbage or whatever.
Change this loop to this (start from i=6)-
for(i=6,j=0;i>=0;i--,j++)
ptr_copy[j]=ptr_arr[i];
Also need a {} here -
for(i=0;i<7;i++){
ptr_copy[i]=ptr_copy[i]*-1;
printf("%d",ptr_copy[i]);
}
The problem is that you didn't put { } around the body of the last loop. So the printf is not part of the loop, it's run when the loop is done. And when the loop is done the value of i is 7, which is outside the bounds of the array.
This became obvious once I used my editor's indent command to reformat the code.
It should be:
for(i=0;i<7;i++) {
ptr_copy[i]=ptr_copy[i]*-1;
printf("%d",ptr_copy[i]);
}
I recommend you always put braces around the bodies of your if, while, for, etc. even if they only have one line.
See Why is it considered a bad practice to omit curly braces?
I'm trying to write code for the gas station problem, where you have a fixed number of cities(linear) and you want to get from one end to the other with as few stops as possible, stopping wherever necessary to refill your gas tank. This is my main function; the function for calculation I've left out for now.
I keep segfaulting saying unable to access tank and arr during the call to solver(the function I'm using to solve).
int main(void)
{
int tank;
int cities;
int ans;
scanf("%d %d",&cities, &tank);
int *arr;
arr=(int *)calloc(cities,sizeof(int));
int *arr2;
arr2=(int *)calloc(cities,sizeof(int));
int i;
for(i=0;i<cities;++i)
scanf("%d",&arr[i]);
arr2[i]=0;
for(i=1;i<cities;++i)
arr2[i]=arr[i]-arr[i-1];
for(i=0;i<cities;++i)
printf(" %d ",arr2[i]);
ans=solver(tank, arr2,cities);
printf("\n ans is %d",ans);
return 0;
}
Can I get some pointers here(terrible pun)?
I'm using the input as:
6 3
0
1
3
4
7
10
Arr holds [0,1,3,4,7,10]
Arr2 holds the differences.
Your loop statement is the problem because of missing encolsing {}:
for(i=0;i<cities;++i) // loop
scanf("%d",&arr[i]); // but there is no enclosing braces. so this is the only statement that loops
arr2[i]=0; //<<<<<< this is executed when loop is finished, i.e i==cities
In other words, you assign arr2[cities], which is out of bouds as it's indexed from 0 to cities-1. This causes the segfault.
Looking at the rest of the code, I guess you inteded to to:
...
for(i=0;i<cities;++i) { // loop, but for the block
scanf("%d",&arr[i]);
arr2[i]=0;
}
...
I've noticed that a counter(avariable) of the for loop, doesn't works well.
Indeed, the counter doesn't decrements correctly; I know this question seems stupid , but I can't understand why the a variable does this.
#include <stdio.h>
int main() {
int a,i,b,matrice[2][2];
printf("Put inside the matrix some numbers..\n");
for (a=2;a>=0;a--) {
for (b=2;b>=0;b--) {
matrice[a][b]=scanf("%d",&i);
}
}
return 0;
}
You are going out of bounds when you read into your array.
for (a=2;a>=0;a--) {
Array has only two elements, yet you try to read into the third on the first iteration.
matrice[2]
Is the third element. This happens for both dimensions.
scanf() call is not correct. It reads the value into i, but it returns the number of read items, not the value of i.
if you are trying to read the numbers into the matrix, then this is what you are supposed to do..
for (a=1;a>=0;a--) {
for (b=1;b>=0;b--) {
scanf("%d",&matrice[a][b]);
}
As the array matrice[2][2] has 2*2 elements, the valid indices are 0 and 1.
Thats why the for loop should start from 1 and not 2
1) The array index start from 0, as per your code it will access matrice[2][2] which will cause undefined behavior.
2) matrice[a][b]=scanf("%d",&i); will store the return value of scanf in matrice[a][b].
#include <stdio.h>
int main() {
int a,b,matrice[2][2];
printf("Put inside the matrix some numbers..\n");
for (a=1;a>=0;a--)
{
for (b=1;b>=0;b--)
{
scanf("%d",&matrice[a][b]);
}
}
//Then print or do other operations on matrice
return 0;
}
You are starting out of bounds.
For an array of size n you iterate from 0 to n-1
So what you want is
for (a=1;a>=0;a--){
for (b=1;b>=0;b--){
}
}
But one word of warning with running backwards with for loops. As is you are fine because you are using integers but if you were to do something like this
for (auto i = some_vector.size()-1;i>=0;i--){
}
You would be in a lot of trouble since i would not be able to take negative values as some_vector.size() is of type unsigned so the loop would never exit. I tend to always increment in a loop for this reason unless the logic dictates otherwise.
Your matrix has a size of [2][2] but you are using a loop that runs from 2 to 0 (inclusive). In an array of size 2 the maximum permissible index is 1.
I guess that you are just learning basic stuff.. so try to run this slightly version of your code:
#include <stdio.h>
int main() {
int a,i,b,matrice[2][2];
printf("Put inside the matrix some numbers..\n");
for (a=1;a>=0;a--) {
printf("a->%d\n", a);
for (b=1;b>=0;b--) {
printf(" b->%d\n", b);
scanf("%d",&matrice[a][b]);
}
}
printf("Check:\n");
for (a=1;a>=0;a--) {
for (b=1;b>=0;b--) {
printf(" [%d][%d]:%d\n", a, b, matrice[a][b]);
}
}
return 0;
}
In the first loop, the modified code run through the correct indices that for a 2x2 array are (0,0),(0,1),(1,0) and (1,1).
Please note that I have also modified the scanf part using the correct syntax: link.
The second loop is a simple test that what you've coded the data insertion correctly, by outputting the content of the matrix.
In this program:
#include<stdio.h>
int a[5],c=0;
int main()
{
printf("Enter no\n");
scanf("%d",&a);
for(int i=0;a[i];i=+2) {
printf("%d ",a[i]);
}
return 0;
}
I want to input 12345 and get the output 1 3 5, but the program never terminates. How can i do this?
Honestly, your code is just all over the place, it looks as if you're just wildly guessing:
You can't pass an int array to scanf(), ask it to read one int, and expect it to put all the digits of a multi-digit number into the individual elements all by itself like that. You either need to read in a string, or read in a single int and extract the digits yourself.
The variable c is unused.
Your for loop makes no sense at all. Even if you had filled all the elements of your array a, it still wouldn't make sense, and you haven't.
Here's a sensible version of your code, reading into a string:
#include<stdio.h>
int main(void) {
char a[6];
printf("Enter no\n");
fgets(a, 6, stdin);
for (int i = 0; i < 5; i += 2) {
printf("%c ", a[i]);
}
putchar('\n');
return 0;
}
with output:
paul#local:~/Documents/src/sandbox$ ./num
Enter no
12345
1 3 5
paul#local:~/Documents/src/sandbox$
Note that this does nothing to check whether the user actually did enter five characters, which your program should do.
the for loop is defined in this way
for(initialization ; condition check ; variable update)
in your code
for(int i=0;a[i];i+2)
{
printf("%d ",a[i]);
}
the condition part of the for loop is set to a[i], which is probably never false. so the loop runs infinitely. the variable update is also incorrect. i value should be updated.
try
for(int i=0; i<5; i+=2)
{
printf("%d ",a[i]);
}
The code is running infinitely because nothing changes inside the loop that would cause the loop to terminate. No variable's value is changed anywhere inside the loop. If a[i] is true for the first iteration, it will remain true forever since i's value never changes.