When you run the C code below, you get a different results almost everytime(None of them are altogether correct).
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i,j;
int s[10][4]={{202201,90,13,21},{202202,32,24,12},{202203,23,53,76},{202204,21,43,64},{202205,12,45,89},{202206,98,99,100},{202207,12,0,0},{202208,0,0,0},{202209,98,12,34},{202210,23,65,34}};
int ave[10],sum[10];
printf("No. MA EN CN\n");
for(i=0;i<10;i++)
{
for(j=0;j<4;j++)
printf("%4d",s[i][j]);
printf("\n");
}
for(i=0;i<10;i++)
{
for(j=1;j<4;j++)
sum[i]=s[i][j]+sum[i];
printf("%d\n",sum[i]);
}
return 0;
}
What's happening? What's the mechanics behind it? How can I fix it?
Both sum and ave are uninitialized arrays. That means that when you cumulative add to s[i] your first add to an uninitialized value which invokes Undefined Behaviour. Here you were just getting a random but valid value.
You need to ensure that s[i][j] is initialized to 0 before it is first used:
int ave[10],sum[10] = {0}; // initialize the full sum array to 0
or:
for(i=0;i<10;i++)
{
sum[i] = 0; // ensure an initial value of 0
for(j=1;j<4;j++)
sum[i]=s[i][j]+sum[i];
printf("%d\n",sum[i]);
}
The issue most likely is in this statement.
sum[i]=s[i][j]+sum[i];
The "sum" integer array hasn't been initialized prior to this statement, so the value "sum[i]" on the right-hand side of the statement probably holds undefined data. Either initialize your sum array or revise the statement if some other type of evaluation should occur.
Related
I couldn't zero down where i have missed in the input statement. I have build it to acquire four values as input but it goes one more.
manipulating the array entries to check if the fifth value is stored. Basic things
#include <stdio.h>
int main()
{
int i,j,a[2][2];
for(i=1;i<=2;i++)
{
for(j=1;j<=2;j++)
scanf("%d\t",&a[i][j]);
}
printf("\n%d\t%d\n%d\t%d", a[1][1],a[1][2],a[2][1],a[2][2]);
}
You have declared this
int a[2][2];
which has four items, a[0][0], a[0][1], a[1][0] and a[1][1].
However, you are starting your indexing at 1 and going up to 2, so are stepping out of bounds which is undefined behaviour.
Anything can then happen.
Change your loops i.e.:
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
// as you were
to index from 0.
You also need to consider your printf statement, since that oversteps too.
#include <stdio.h>
int main()
{
int i,j,a[2][2];
for(i=0;i<2;i++) /*go through rows - arrays in c go [0- (n-1)]*/
{
for(j=0;j<2;j++)/*go through col */
scanf("%d",&a[i][j]); /*remove \t- now will scan 4 values only */
}
printf("\n%d\t%d\n%d\t%d", a[0][0],a[0][1],a[1][0],a[1][1]);
return 0;
}
I am trying to get the average number of an array but the output is way to high for it to be correct. What am I doing wrong?
int count(int arr[]){
int sum;
//Average
for(int i=0;i<100; i++)
sum = sum + arr[i];
printf("Average:%f \n", sum/100);
}
int main()
{
int array[100]; //RANDOM NUMBERS 0-900
count(array);
return 0;
}
You need to initialize sum to zero before using it. C or C++ does not do this automatically for you in case of variables with automatic storage duration. It takes "time", and in C or C++ you don't pay for what you don't need. Otherwise you get a junk value (whatever its stored at that memory address, and technically it is undefined behaviour to use un-initialized variables except in assignments).
You also need to initialize the array, like
int arr[100]{}; // C++11 or later
or
int arr[100] = {0}; // C++98 or good old C
then fill it up with values. Do not consider the junk values as "random numbers", since again you are encountering undefined behaviour and the program is not altogether safe.
Undefined behaviour(UB):
sum = sum + arr[i];
You have used sum above and it was not initialized. It is UB to read values of uninitialized variables in C and C++.
Actually given your code it is even once again UB because neither array values arr[i] are initialized.
sum contains garbage value. Do initialize variable sumenter code here.
To verify you can print before updating sum.
Try the following:
int count(int arr[]){
int sum = 0; // <==================== initialize to zero
//Average
for(int i=0;i<100; i++)
sum = sum + arr[i];
printf("Average:%f \n", sum/100);
}
int main()
{
int array[100]; //RANDOM NUMBERS 0-900
count(array);
return 0;
}
Without this initialization, the local variable sum can have any arbitrary initial value. And you will end up with arbitrarily large sum. Which will throw off the average.
The reason for this is that local variables are NOT initialized to zero automatically (unlike global variables).
I have made a dynamic array of integers in C, here is my code
#include <stdio.h>
int main(){
int count=0, i, input;
int *myarr;
myarr=(int*)malloc(4*sizeof(int));
while(1){
scanf("%d", &input);
myarr[count]=input;
count++;
if (input == -1) break;
}
for (i=0; i<count; i++){
printf("%d ", myarr[i]);
}
return 0;
}
From the code, I thought i clearly made an array of 4 integers only i.e myarr[0] up to myarr[3], how come when i insert even 10 integers, it still prints all of them, it doesn't print garbage as i thought it would after the fourth integer... Maybe i didn't understand the point of dynamic creating an array?? Make me straight please!
You should only access myarr[0] up to and including myarr[3].
Accessing any other index is undefined behaviour: it might work, it might not.
Also, myarr[count]==input looks like a typo. Did you mean myarr[count] = input? The way you have it is testing if myarr[count] equals input. Technically the way you have it is undefined behaviour for any element of myarr since you are making use of uninitialised data.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int prime(long long int);
long long int *arr; //array to hold n prime numbers
int main()
{
int i,count=4;;
long long int n;
scanf("%lli",&n);
arr=malloc(sizeof(long long int)*n);
arr[0]=2;
arr[1]=3;
arr[2]=5;
arr[3]=7;
if (n==1) printf("%lli",arr[0]);
else{ if (n==2) printf("%lli",arr[1]);
else{ if (n==3) printf("%lli",arr[2]);
else{ if (n==4) printf("%lli",arr[3]);
else
{
for(i=2;count<n;i++)
{
if(prime(6*i-1)) { /*As prime nos are always 6k+1 or
arr[count]=6*i-1; 6k-1fork>=2 I checked only for those*/
count++; }
if(prime(6*i+1)&&count<=n) {
arr[count]=6*i+1;
count++; }
}
printf("%lli",arr[count]);
}}}}
//free(arr);
return 0;
}
int prime(long long int x)
{
int j=1,flag=1;
while(arr[j]<=sqrt(x))
{
if (x%arr[j]==0)
{
flag=0;
break;
}
j++;
}
return flag;
}
The code is working only for n=1,2,3,4, i.e i=0,1,2,3 for which the values are explicitly given. For n=5 onwards it is giving 0 as O/P
There is some glitch related to the global dynamic array as free(arr) is giving core dump error.
Q: Is this the right way to declare a global dynamic array? What could be the problem in this code?
Thank You in advance.
If that is your actual code you have 4 bugs:
2 line comment scopes out a line of your code
the second if should check count < n not count <= n as if count == n you cannot write to arr[count]
You cannot print arr[count] only arr[count-1] which is probably what you mean
In the case where n is less than 4 you still set arr[1], arr[2] and arr[3] which may be out of bounds
It is of course also inefficient to call sqrt(x) in every loop iteration, potentially you should call it outside and there may be a potential rounding issue bug due to the way square roots are calculated, so you might prefer:
while( arr[j] * arr[j] < x )
It would be preferable not to make this global and to pass it into your function.
It would also be preferable to move the main loop logic of your program outside of main().
I'm surprised you say you program works for n=1, 2 and 3 as it looks like you are setting out of bounds.
Your counter goes beyond the size of the array. Specifically both conditions (6i-1 and 6i+1) are met for i=2, and therefore counter is incremented twice, resulting in using arr[5] where you only allocated 5 places in the array. This is because you check counter<=n and not counter
Not sure this could be also be the reason for free creating a core dump, but it is possible (because once corrupting the memory, free may access corrupted data).
What em trying to do is pass the array to a function which will add all the array elements and return the output. Please help me. i dont know what i am doing wrong in this :/
#include <stdio.h>
#define MAX 5
int arraySum(int *dArr,int lim);
int main()
{
int array[MAX] = {9,7,4,2,10};
printf("%d", arraySum(array, MAX));
return 0;
}
int arraySum(int *dArr,int lim)
{
int Ans;
if(lim>0)
Ans = dArr[lim] + arraySum(*dArr, lim--);
return Ans;
}
There are several problems with your code:
You're accessing array[MAX], which is undefined behaviour.
Your function returns the uninitialized Ans when lim is zero.
The first argument to arraySum in the recursive call is wrong.
The use of lim-- is wrong.
Since this looks like homework, I'll let you figure out how to fix these problems. If this isn't homework, you might want to consider whether recursion is the right tool for the job.
You run into undefined behavior on dArr[lim], because lim is 5 and the array has elements 0...4.
You also get undefined behavior when lim==0, because you return an un-initialized Ans. When you declare it, initialize it to dArr[0].
After you fix this, you'll want to pass dArr itself further in the recursion, as dArr only returns an int.
Remember that computers treat 0 as the first number, so your array will number from element[0] to element[4]. your code starts from five and counts down to one, which means elements[5] in this case will return garbage, because the index does not exist. pass Lim - 1 into the function or manually changed the value in your function.
ArraySum(Array, MAX - 1);
OR
ArraySum(//....)
{
lim--;
//code here....
}
EDIT: you also need to initialize ans to some value, so if an array of zero elements is passed the function wont return an uninitialized variable.
int arraySum(int *dArr,int lim)
{
int Ans;
if(lim>=0) // note the change here
Ans = dArr[lim] + arraySum(dArr, --lim); // note the --lim change here
return Ans;
}
You should invoke this with lim as 4 and not 5. Because the array has 5 integers starting from index 0 to index 4. 5th index is out of bounds.
--lim instead of lim-- because lim-- is post decrement. That means the value is first passed and then decremented. Hence everytime your arraySum function gets the value as 4 instead of 3, 2, 1 and 0 (as per your expectation). --lim is pre-decrement.
Change MAX to 4 and change the if(lim>0) condition as if(lim>=0)
This will make your recursion to add as dArr[4]+dArr[3]+dArr[2]+dArr[1]+dArr[0] i.e. all 5 elements of the array.
EDIT: Corrected program:
int main()
{
int array[MAX] = {9,7,4,2,10};
printf("%d", arraySum(array, MAX-1));
return 0;
}
int Ans = 0;
int arraySum(int *dArr,int lim)
{
if(lim>=0){
Ans = dArr[lim] + arraySum(dArr, lim-1);
}
return Ans;
}