I need to calculate average with the size of span and which is moving by one element and outputting the average of elements till the end.
#include <stdio.h>
#include <stdlib.h>
void moving_average (int size, double a[], int span)
{
int k;
double sum;
int n;
int count;
double output;
n=size-span;
for(count=0;count <= n;count++)
{
for(k=count; k<(count+span); k++)
sum+=a[k];
output=sum/span;
printf("%lf", output);
}
}
int main(void)
{
double array[]={10,9,15,6,7};
moving_average(5,array[], 2);
return 0;
}
Increase the warning level of your compiler!
There's a syntax error in the call to moving_average() which your compiler should have caught.
And sum is not initialized which your compiler should warn you about if it is properly setup.
Remove the brackets after array in the call to moving_average
Set sum = 0 before for(k=count; k<(count+span); k++)
add a \n in your printf
Related
Basically I have a function called MinSubTab that is supposed to calculate the sum of the array passed and also to change the value passed in the first argument from inside the function without using return. This is done with pointers. Anyway, I think it'd be easier if I just showed you the code so here it is:
maintab.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "tab.h"
int main(){
int *reftab;
int min;
reftab = (int *)malloc(sizeof(int) * NMAX);
InitTab(reftab,NMAX);
printf("\n Total: %d et min: %d", MinSumTab(&min, reftab, NMAX), min);
free(reftab);
return 0;
}
tab.c
void InitTab(int *tab, int size){
srand(time(NULL));
for (int i=0; i<size; i++){
*(tab+i) = rand() % 10;
}
}
int MinSumTab(int *min, int *tab, int size){
int total=0;
int minimum = NMAX;
int temp = *min;
for (int i=0; i<size; i++){
total += *(tab+i);
}
for (int i=0; i<size; i++){
if(*(tab+i)<minimum){
minimum = *(tab+i);
}
}
*min = minimum;
return total;
}
So the expected result here is that the sum is printed (which it is) and the minimum value of the array is printed (which it is not). Every single time the min variable equals 8 and I've no idea how to actually change the value of min from within that function.
Please help as my brain has no more capacity for rational thought, it's been 1.5 hrs and no solution in sight. Thanks
Looks like a small mistake:
You initialize minimum with NMAX, which I assume is 8 (the size of the array). 99.9% of the random numbers will be bigger. So 8 is chosen as the minimum.
What you really want is to initialize it with RAND_MAX – the maximum value rand() can return.
In C order of evaluation and argument passing is undefined.
You can of course the order yourself but it only to feed your curiosity.
#include <stdio.h>
volatile char *message[] = {
"fisrt", "second", "third", "fourth"
};
int print(size_t x)
{
printf("%s\n", message[x]);
return x;
}
int main()
{
printf("%d %d %d %d\n", print(0), print(1), print(2), print(3));
return 0;
}
Note. There is one exception from this rule.
Logical operators are evaluated form the left to the right.
if( x != NULL && *x == 5)is safe because x will not be dereferenced if it is NULL
The code runs until it reaches the statement:
printf("%d", sumOccur(input));
The code:
#include <stdio.h>
#include <stdlib.h>
int sumOccur(int A[]);
int main(){
int input[6] = {1,1,1,2,2,3};
printf("%d", sumOccur(input));
return 0;
}
int sumOccur(int A[]) {
int sum, i;
while(A[i]!='\0'){
sum += A[i];
i++;
}
return sum;
}
If I have made any silly mistakes please oblige.
It's not the printf() crashing. It's sumOccur(). Your array has no \0 value in it, so your while() never terminates and you end up in a near-infinite loop and run off the end of the array.
The array is an array of numbers, not a string, so there is no reason whatsoever to think there there would be a null-terminator on the values. null terminators are for strings, not arrays of numbers.
In your function int sumOccur you have two problems-
1. sum and i are not initialized just declared. Initialize both to 0 .
2. Also while(A[i]!='\0') ain't going to work as expected as your array doesn't have that value in it.
Your code invokes undefined behaviour: you access A[6] and subsequent inexistent entries in sumOccur trying to find a final 0 in the array, but you do not put one in the definition of input in the main function.
-------- cut here if you are not interested in gory implementation details --------
The array is allocated on the stack, very near the top since it is instantiated in the main function. Reading beyond the end until you find a 0 likely tries to read beyond the end of the stack pages and causes a segmentation fault.
Note that you are dealing with an int array,which means it normally won't contain '\0' character.To iterate over the array you need to specify number of elements.Here is the correct way :
#include <stdio.h>
#include <stdlib.h>
int sumOccur(int A[],size_t number_of_elemets);
int main(){
int input[6] = {1,1,1,2,2,3};
//Get the number of elements
size_t n = sizeof(input) / sizeof(int);
printf("%d", sumOccur(input,n));
return 0;
}
int sumOccur(int A[],size_t number_of_elements) {
int sum = 0;
size_t i = 0;
while( i < number_of_elements )
{
sum += A[i];
i++;
}
return sum;
}
You are iterating while A[i] != '\0' but there is no '\0' in the array and also you never initialize sum which is unlikely the cause for a crash but it could be.
You need to pass the number of elements in the array, like this
#include <stdio.h>
#include <stdlib.h>
int sumOccur(size_t count, const int *A);
int sumOccurCHQrlieWay(const int *A, size_t count);
int main()
{
int input[] = {1, 1, 1, 2, 2, 3};
printf("%d", sumOccur(sizeof(input) / sizeof(*input), input));
return 0;
}
int sumOccur(size_t count, const int *A)
{
int sum;
sum = 0;
for (size_t i = 0 ; i < count ; ++i)
sum += A[i];
return sum;
}
int sumOccurCHQrlieWay(const int *A, size_t count)
{
return sumOccur(count, A);
}
I'm writing a simple program taking a double alpha and integer deg that prints a matrix mat as computed by create_basis. Below is the code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX 30
void create_basis(uint64_t mat[][MAX],double alpha, int deg);
void create_basis(uint64_t mat[][MAX],double alpha,int deg){
int i;
int j;
for(i=0;i<deg+1;i++){
for(j=0;j<deg+2;j++)
mat[i][j]=0;
}
for(i=0;i<deg+1;i++){
mat[i][deg+1]=floor(pow(alpha,i)*pow(10,16));
mat[i][i]=1;
}
}
int main(){
int deg;
double alpha;
int i;
int j;
printf("Enter number:\n");
scanf("%lf",&alpha);
printf("Enter degree:\n");
scanf("%d",°);
uint64_t mat[deg+1][deg+2];
create_basis(mat,alpha,deg);
printf("Matrix basis=\n\n");
for(i=0;i<deg+1;i++){
for(j=0;j<deg+2;j++){
if(j==0)
printf("[%llu ",mat[i][j]);
if(j==deg+1)
printf("%llu]",mat[i][j]);
else
printf("%llu ",mat[i][j]);
}
printf("\n");
}
return 0;
}
However, when I run, there seems to be an issue when I call create_basis in main because it is giving an abort trap 6 error, which I presume to mean I'm trying to access memory I don't have. However, the dimensions of mat seem to agree with what I'm trying to access. Am I calling create_basis incorrectly? Any ideas are greatly appreciated!
void create_basis(uint64_t mat[][MAX],double alpha,int deg){
change to
void create_basis(int deg, uint64_t mat[deg+1][deg+2],double alpha){
As reasons already explained #SteveSummit is
Two-dimensional array does not have to match.
could everyone please help me what is wrong with my code or what is missing from my code...
We have this activity where we have to find the highest number using another function..
#include <stdio.h>
#include <stdlib.h>
#define p printf
#define s scanf
int high (int n1);
int main(int argc, char *argv[])
{
int i, num[10];
p("Input 10 numbers\n");
for (i=0; i<10; i++)
{
p("Enter Number: ");
s("%d",&num[i]);
}
p("Highest Number: %d",high(num[i]));
getch();
}
int high (int n1)
{
int l;
for (l=0; l<n1; l++)
{
if (n1 > l)
return n1;
}
}
When I input any number I always got 37..
int high (int n1); should be
int high (int *arr, int sz); /* You need to pass an array */
p("Highest Number: %d",high(num[i])); should be
p("Highest Number: %d",high(num, 10)); /* Passing array now, not one element */
int high() should be re-written as:
int high (int *arr, int sz)
{
int l, mx = INT_MIN;
for (l=0; l<sz; l++)
{
if (mx < arr[l])
{
/* Left as an excercise */
}
}
return mx;
}
As this is tagged c++, I would suggest using available C++ to find max in a range:
const int max = *std::max_element(&num[0], &num[10]); // #include <algorithm>
Well, I don't know if you still need an answer, but I corrected your code. Here are the mistakes I found
int high (int n1)
{
int l;
for (l=0; l<n1; l++)
{
if (n1 > l)
return n1;
}
}
In this for-loop, there is the condition l<n1 and inside the for loop you have the statement if(n1 > l) which will never be attained because of l<n1. You said you were getting 37 each time, but I was getting 10 instead. This shows it was undefined behavior because no real value was returned. ( This code part really didn't mean any sense either as this function doesn't even try to find the largest number ).
Another issue I found is you have used getch() without including <conio.h> ( Also pointing out that <conio.h> is not standard in C++ )
Well, even though this question is tagged C++, since the code is completely c, I have made a fixed code in c. I've removed getch() in the code. So here is the code
#include<limits.h>
#include <stdio.h>
#include <stdlib.h>
#define p printf
#define s scanf
int high (int *n1,int lar); // now I have used *n1 to get the address of the array.
int main(int argc, char *argv[])
{
int i, num[10],lar=INT_MIN; // the variable lar is given the minimum value that can be held by an int
p("Input 10 numbers\n");
for (i=0; i<10; i++)
{
p("Enter Number: ");
s("%d",&num[i]);
}
p("Highest Number: %d",high(num,lar)); // sending the entire array to the function by sending its address
}
int high (int *n1,int lar)
{
int l;
for (l=0; l<10; l++) // since the size you have taken for your array is 10, I have used 10 here. But if you don't know the size beforehand, pass the size as an argument to the function
{
if (n1[l] >lar ) // Well, this is the simple part
lar=n1[l]; // Simply assigning the largest value to lar
}
return lar; // Finally returning the value lar.
}
Well, hope this helps you.
I've got a function thats able to produces 2 arrays, one when the index 'i' is even and one when the index 'i' is odd, so I end up with two arrays. The even 'i' array is called W_e and made of N elements, the odd 'i' array is called W_o and also made of N elements.
I now need to be merge these two arrays into another array Wn (which has 2*N elements) such that it looks like Wn=[W_e[0],W_o[0],W_e[1],W_o[1],...,W_e[N-1],W_o[N-1]] but I'm not sure how to do it. I tried to use nested loops but it didn't work. The arrays W_e and W_o are produced correctly according to my calculations, I'm just unable to combine the entries into one array.
This is what I have so far. I have not done anything in the main function except call the function which is giving me trouble "double *MakeWpowers(int N);". Please keep in mind this works for N>2, I have not yet dealt with N=1 or N=2.
Any help will be greatly appreciated. Thank you!!
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <complex.h>
#define pi 4*atan(1)
double *MakeWpowers(int N);
void print_vector(double *x,int N);
double *make_vector(double *x,int N);
int main(void)
{ int N;
double *Wn;
printf("\n Please enter the size of the NxN matrix:\n");
scanf("%d",&N);
Wn=MakeWpowers(N);
//print_vector(Wn,N);
free(Wn);
return(0);
}
double *MakeWpowers(int N)
{
double *Wn,*W_e,*W_o;
int i,j;
Wn=make_vector(Wn, 2*N);
W_e=make_vector(W_e, N);
W_o=make_vector(W_o, N);
for(i=0;i<=N-1;i++)
{
if(i%2==0)
{
W_e[i]=cos((2*i*pi)/N);
}
else
{
W_o[i]=sin((2*i*pi)/N);
}
}
printf("\nThis is the even vector W_e:\n");
print_vector(W_e, N);
printf("\nThis is the odd vector W_o:\n");
print_vector(W_o, N);
for(j=0;j<2*N;j++)
{
if(j%2==0)
{Wn[j]=W_e[i];}
//++i;}
else
{Wn[j]=W_o[i];}
//++i;}
printf("\nthis is Wn:\n\n");
print_vector(Wn, 2*N);
//Wn[j]=W_o[i];
//j++;
}
return(Wn);
}
void print_vector(double *x,int N)
{
int i;
for (i=0; i<N; i++)
{
printf ("%9.4f \n", x[i]);
}
printf("\n");
}
double *make_vector(double *x,int N)
{ int i;
double xi;
x=(double *)malloc((N)*sizeof(double));
for(i=0;i<N;i++)
{
x[i]=(double)xi;
}
return(x);
}
Here's the general logic to it:
LET a, b, merge BE ARRAYS
FOR k IN 0..length(a)
merge[2*k] = a[i]
merge[2*k+1] = b[i]
RETURN merge
a makes the even entries (2k), b the odd ones (2k+1).
This is probably wrong
double *make_vector(double *x,int N)
{ int i;
double xi;
You have to initialize variable xi same thing goes for *Wn,*W_e,*W_o