For Loop in C does not work as Expected - c

I don't understand the flow of the following for loop: it becomes an infinite loop. I am using ubuntu 12.04. Am I doing anything wrong here?
#include <stdio.h>
main()
{
int k,a[10];
for(k=0; k<=10; k++)
{
a[k]=1;
printf("k = %d\n",k);
}
}
Once k == 9, it automatically changes to 1. I don't know why it behaves like this. What am I doing wrong?

for(k=0; k<=10; k++)
This access out of bound index . a[10](indexing start with 0 therefore valid index 0-9) is out of bound and invoke undefined behaviour.
loop should be this -
for(k=0; k<10; k++)

Your operating system doesn't affect the way the loop is processed. What you need is a way to handle the integer variable "k" and inside the loop, you need to make "k" greater than 10 for the loop to exit properly. So I made K increment so that each element of the integer array "a" contains the value 1.
#include <stdio.h>
int main()
{
int k,a[11];
for(k=0; k<=10; k++)
{
a[k]=1;
printf("k = %d\n",k);
k++;
}
return 0;
}

Actually array index starts from 0. So if you have an array "a" with 10 members in it, then the members will be
1st member - a[0];
2nd member - a[1]; 3rd member - a[2]; ... ... ... 10th member - a[9]
So, you can't have a member a[10]. But in your for loop you started k from 0 and incremented it to 10. But a[10] was not present in the array and this caused the infinite loop. To solve this problem, just use "k<10" as your loop condition. Your code should look like this now:
#include <stdio.h>
main()
{
int k,a[10];
for(k=0; k<10; k++)
{
a[k]=1;
printf("k = %d\n",k);
}
}
The reason k is becoming 1 after 9 is that for some reason k is situated right after the memory range of a. So, when you change a[10] to 1, it actually changes the value of k. So, you get 1 as the value of k.

Related

Enter unknown number of array values in C/C++ has strange behaviour

I need to populate an array of integers with an unknown number of elements. I am using a while loop to input values and exit the loop as a non integer value is entered. Outside the loop an integer j is initialized at 0 and used to address array elements inside the loop. At each round of the loop I check the value of j before and after the input value is assigned to array element v[j], then j is incremented.
Depending on the size chosen for the array in the declaration, (in the example below v[8]), index j is unexpectedly affected by the assignment itself: in the example below when j equals 11 before the assignment it becomes 2 after the assignment, thereafter messing it all up. As a result the code fails to assign the correct input values to the array.
I am surely lacking some deeper knowledge about C/C++ array management... anyone can help to to fill the gap explaining the apparently strange behaviour of my code?
#include <stdio.h>
int main()
{
int j = 0, m, v[8];
printf("Enter an integer: to finish enter x\n");
while (scanf("%d", &m))
{
printf("j before assignment:%d - ", j);
v[j] = m;
printf("j after assignment:%d - ", j);
printf("v[j] after assignment:%d\n", v[j]);
j++;
}
return 0;
}
You write beyond the array boundaries of v. To avoid this, check j in a for loop, e.g. replace while (...) with
for (j = 0; j < 8 && scanf("%d", &m) == 1; ++j) {
// ...
}
This way, the loop stops after the end of the array (v[7]) is reached.
To comment the "strange" behaviour, read about stack and stack layout, e.g. Does stack grow upward or downward?
As always, check the C tag wiki and the books list The Definitive C Book Guide and List

Trying to make a function which squares all values in an array. Getting strange number on the last value

int squaring_function (int *array, int i);
int main()
{
int array[5];
int i;
for(i=0; (i <= 5) ; i++)
{
array[i] = i;
printf("\nArray value %d is %d",i,array[i]);
}
for(i=0; (i <= 5) ; i++)
{
array[i] = (squaring_function(array, i));
printf("\nSquared array value %d is %d",i,array[i]);
}
return 0;
}
int squaring_function (int *array, int i)
{
return pow((array[i]),2);
}
I'm trying to use this squaring_function to square each value in turn in my array (containing integers 0 to 5). It seems to work however the last value (which should be 5)^2 is not coming up as 25. cmd window
I have tried reducing the array size to 5 (so the last value is 4) however this prints an incorrect number also.
I'm quite new to C and don't understand why this last value is failing.
I'm aware I could do this without a separate function however I'd quite like to learn why this isn't working.
Any help would be much appreciated.
Thanks,
Dan.
There are 2 bugs in your code. First is that you're accessing array out of bounds. The memory rule is that with n elements the indices must be smaller than n, hence < 5, not <= 5. And if you want to count up to 5, then you must declare
int array[6];
The other problem is that your code calculates pow(5, 2) as 24.99999999 which gets truncated to 24. The number 24 went to the memory location immediately after array overwriting i; which then lead to array[i] evaluating to array[24] which happened to be all zeroes.
Use array[i] * array[i] instead of pow to ensure that the calculation is done with integers.
The code
int array[5];
for(int i=0; (i <= 5) ; i++)
exceeds array bounds and introduces undefined behaviour. Note that 0..5 are actually 6 values, not 5. If you though see some "meaningful" output, well - good or bad luck - it's just the result of undefined behaviour, which can be everything (including sometimes meaningful values).
Your array isn't big enough to hold all the values.
An array of size 5 has indexes from 0 - 4. So array[5] is off the end of the array. Reading or writing past the end of an array invokes undefined behavior.
Increase the size of the array to 6 to fit the values you want.
int array[6];
The other answers show the flaws in the posted code.
If your goal is to square each element of an array, you can either write a function which square a value
void square(int *x)
{
*x *= *x;
}
and apply it to every element of an array or write a function which takes an entire array as an input and perform that transformation:
void square_array(int size, int arr[size])
{
for (int i = 0; i < size; ++i)
{
arr[i] *= arr[i];
}
}
// ... where given an array like
int nums[5] = {1, 2, 3, 4, 5};
// you can call it like this
square_array(5, nums); // -> {1, 4, 9, 16, 25}

Bubble Sort in C wrong code! [Deitel C 6th Ed]

int main(void)
{
int a[5] = {36,24,10,6,12};
int pass;
int i;
int hold;
/* bubble sort */
/* loop to control number of passes */
for(pass=1; pass<5; pass++){
/* loop to control number of comparisons per pass */
for(i=0; i<5; i++){
if(a[i] > a[i+1]){
hold = a[i];
a[i] = a[i+1];
a[i+1] = hold;
}
}
}
return 0;
}
In this bubble sort program the if statement comparing adjacent element’s value.
If counter I becomes 4 then if statement would be if a[4] > a[4+1] so my question is there’s no a[5] element in the array so how program is comparing and doing work?
I don’t understood for(pass=1; pass<5; pass++) loop. What this loop work for? And why the loop starts from 1 and continues 4 times instead of 5.
Anybody please demonstrate how this bubble sort program is working? Cheers!
Well, everyone answered this in the comments, but noone took the time to write an actual answer, so I'd take the role.
1st thing first, the code you pasted has a Bug in it:
while the array int a[5] has 5 members [0..4],
when executing the inner loop for(i=0; i<5; i++) given i=4,
a[i+1] is accessing a[5] which is out of bounds of the array and it's value is probably unexpected.
Worth Noting: because the example values int a[5] = {36,24,10,6,12}; are very small, there is a high chance (36 / 2^32) that the code will work anyway because the a[5] will have the maximum value, and won't be overridden or moved.
but if you'd try changing the values to, lets say, int a[5] = {36,0xFFFFFFFF,10,6,12};, the program will surely fail miserably!
2nd to your other question:
with each iteration (pass), the maximum value is bubbled to it's place, and therefore will be in place...
for 5 numbers, after placing 4 in their place, the last one is given implicitly.
and that's why there is no need for the 5th iteration.
also, it is common in the 2nd to last iterations to exclude the last elements from the inner loop, as they are known to be in place.
int main(void)
{
int a[5] = {36,24,10,6,12};
int pass;
int i;
int hold;
/* bubble sort */
/* loop to control number of passes */
for(pass=4; pass > 0; pass--){ /* pass counts down 4 iterations */
/* loop to control number of comparisons per pass */
/* 0..4, then 0..3 > 0..2, and lastly 0..1 */
for(i=0; i<pass; i++){
if(a[i] > a[i+1]){
hold = a[i];
a[i] = a[i+1];
a[i+1] = hold;
}
}
}
return 0;
}

Why is this code outOfBound?

Here is a problem I met the other day in a interview, would someone tell me the "truth" behind this "simple" code?
#include<stdio.h>
int main()
{
int a[]={1,2,3};
for(int i=0; i<=3; i++){
a[i]=0;
printf("%d\n", i);
}
return 0;
}
Everything will be right if <= is replaced by < as it is causing array out of bound index error and will print value
0
1
2
3
although the value of the array content will be 0 every time
The loop variable i takes on values 0, 1, 2, and 3. Unfortunately, 3 is an out-of-bounds index for array a, which only has length 3 (legal indices 0, 1, and 2). To avoid an out-of-bounds array access, the loop control should be
for(int i=0; i<3; i++){
Note the use of < instead of <=. As an interview question, the goal was to test whether you noticed this very common kind of off-by-one error.

In C, how to initialise an array with a certain pattern?

I want to initialise an array in C following a pattern.
For example, here are two arrays with 10 elements. Each array have following elements: {0,0,2,3,0,7,0,1,9,0}
And here is my code: Note: example above and code below are not related, just to elaborate the definition of "pattern" in my case.
void CreateArray()
{
int i = ArraySize();
int j;
int k = Rand_Gen();
printf("%d\n",i);
int array[i];
for (j=0;j<i;j++)
{
if (k>0 && k<=30)
{
array[j]=4;
array[j+2]=23;
array[j+5]=900;
printf("%d",array[j]);
}
else if (k>30 && k<=60)
{
array[j]=2;
array[j+3]=54;
array[j+5]=870;
printf("%d",array[j]);
}
else
{
array[j]=0;
printf("%d",array[j]);
}
}
}
However, after running this program, I can only get an array with the same element. In this case, half of the time I get an array filled with 4 only, and half of the time I get 2.
I have done Googling but I could not find a possible solution to my problem. Or, maybe my method to print elements of the array is not correct?
Thanks first.
Follow up:
I have tried adding "int k = Rand_Gen()" within loop, but I still can only get one number. Here is the update segment of code:
void CreateArray()
{
int i = ArraySize();
int j;
printf("%d\n",i);
int array[i];
for (j=0;j<i;j++)
{
int k = Rand_Gen();
//some if statements here.
}
}
You use :
int k = Rand_Gen();
outside your for loop. This means that k will only be created once. Consequently, your for loop will be executed i times with the same value of k and therefore it will be entering the same part of your if-else statement. You need to generate k inside your loop.
Another issue is that your index 'j' gets out of your array bounds. In particular, your loop runs as following :
for (j=0;j<i;j++)
At some point, j will reach value i-1 (which will be the last iteration). At this point, your if and your else if parts try to access the positions array[j+2], array[j+3] and array[j+5].
However, you have declared array to be of size i so the statements :
array[j+2] = ... ;
array[j+3] = ... ;
array[j+5] = ... ;
with j being i-1 will be equivalent to :
array[i+1] = ... ;
array[i+2] = ... ;
array[i+4] = ... ;
which is definetely indexing out of bounds.
Move k = Rand_Gen(); inside for loop.
Currently you are generating 'k' value only once.
Also accessing j+2 index make out of bound access.

Resources