c program, passing array to function, terminates early - c

#include <stdio.h>
#include <math.h>
void abs_table (double x[], int size);
int main (void) {
int size, index;
printf("Enter number of elements: ");
scanf("%d", &size);
double x[size], element;
for (index = 0; index < size; index++) {
printf("Enter x[%d]: ", index);
scanf("%lf", &element);
x[index] = element;
}
void abs_table (double x[], int size);
return 0;
}
void abs_table (double x[], int size) {
int index;
double y[size];
for (index = 0; index < size; index++) {
y[index] = fabs(x[index]);
printf("%lf\t%lf\n", x, y);
}
}
program to read in array values and display the absolute value of each element using a void function.
program terminates after storing values into array x. void function does not display.

Call abs_table() instead of declaring it in main().
Index x and y in abs_table() print statement. As you don't use y other than to print the current value eliminate it.
(minor) Move main() after function so you don't need the declaration.
(minor) Minimize scope of variables.
(minor, not fixed) If your size argument is before x, then you can document their relationship void abs_table(int size, double x[size]).
(minor. not fixed) prefer unsigned variables (index, size etc).
(not fixed) check if scanf() returns 1 in your code otherwise the values size and x[index] may be undefined.
#include <stdio.h>
#include <math.h>
void abs_table (double x[], int size) {
for (int index = 0; index < size; index++) {
printf("%lf\t%lf\n", x[index], fabs(x[index]));
}
}
int main (void) {
int size;
printf("Enter number of elements: ");
scanf("%d", &size);
double x[size];
for (int index = 0; index < size; index++) {
printf("Enter x[%d]: ", index);
scanf("%lf", &x[index]);
}
abs_table(x, size);
return 0;
}
Here is an example run;
Enter number of elements: 3
Enter x[0]: -1.2
Enter x[1]: 1.3
Enter x[2]: -100
-1.200000 1.200000
1.300000 1.300000
-100.000000 100.000000

Related

Function in C not returning correct data after I include another function

I am writing a program that creates an array of ten integers. I have to define max 10 constant and use functions.getdata(ask user for numbers),displaydata(display)
displaylargest,smallest,average,range,and median.
I am stuck on average because soon as I added that function my largest displays a weird number but if I comment out the average function my largest displays correct answer. Can someone tell me where I went wrong?
#include <stdio.h>
#define MAX 10
int getdata(int array[]);
int displaylargest(int array[]);
int displaysmallest(int array[]);
int displayaverage(int array[]);
void displaydata(int array[]);
int main () {
int array[MAX];
int largest;
int smallest;
int average;
printf("\nEnter ten numbers \n\n");
getdata(array);
displaydata(array );
largest=displaylargest( array);
printf("\nThe largest %d\n", largest);
smallest=displaysmallest( array);
printf("\nThe smallest is %d\n", smallest);
average=displayaverage(array);
printf("\nThe average is %d\n", average);
return 0;
}
int getdata(int array[]) {
int x;
printf ("Enter a number\n ",x+1);
for(x=0;x<MAX;x++)
scanf ("%d",&array[x]);
}
int displaylargest(int array[]) {
int x, largest=array[x];
for (x=0; x<MAX; x++) {
if (array[x]>largest)
largest=array[x];
}
return(largest);
}
int displaysmallest(int array[]) {
int x, smallest=array[x];
for (x=0; x<MAX; x++) {
if (array[x]<smallest)
smallest=array[x];
}
return(smallest);
}
int displayaverage(int array[]) {
int x;
int sum=0;
int average;
for (x=0; x<MAX; x++) {
sum+=array[x];
}
{
average=sum/MAX;
}
return(average);
}
void displaydata(int array[]) {
int x;
for(x=0; x<MAX; x++) {
printf("%d, ",array[x]);
}
}
You need to initialize local variables in your functions especially when you are using that to access your array. Without that local variable can contain any value ,if you use that as index to your array, you might be accessing valid memory.
#include <stdio.h>
#define MAX 10
void getdata(int array[]);
int displaylargest(int array[]);
int displaysmallest(int array[]);
int displayaverage(int array[]);
void displaydata(int array[]);
int main() {
int array[MAX];
int largest;
int smallest;
int average;
printf("\nEnter ten numbers \n\n");
getdata(array);
displaydata(array);
largest = displaylargest(array);
printf("\nThe largest %d\n", largest);
smallest = displaysmallest(array);
printf("\nThe smallest is %d\n", smallest);
average = displayaverage(array);
printf("\nThe average is %d\n", average);
return 0;
}
void getdata(int array[]) {
int x;
printf("Enter a number\n " );
for (x = 0; x<MAX; x++) {
scanf("%d", &array[x]);
}
}
int displaylargest(int array[]) {
int x, largest = array[0];
for (x = 0; x<MAX; x++) {
if (array[x]>largest)
largest = array[x];
}
return(largest);
}
int displaysmallest(int array[]) {
int x, smallest = array[0];
for (x = 0; x<MAX; x++) {
if (array[x]<smallest)
smallest = array[x];
}
return(smallest);
}
int displayaverage(int array[]) {
int x;
int sum = 0;
int average;
for (x = 0; x<MAX; x++) {
sum += array[x];
}
{
average = sum / MAX;
}
return(average);
}
void displaydata(int array[]) {
int x;
for (x = 0; x<MAX; x++) {
printf("%d, ", array[x]);
}
}
In c if we have local variable without initialization ,then it will have some garbage value. And in many of the functions u are intializing somevalue = array(x) it is not correct. The location you are accessing on the array is not valid.Make those chages it will work correctlu
Local variables need to be used here. While defining
largest=array[x];
make sure that x=0, else x may contain garbage value and the array may try to access invalid memory locations, leading to either the conditions known as underflow or overflow.
Also, I see that you've declared getdata() of type int, though it is not returning any value. Please make it of type void, as is just used to insert the asked values into the array. Hope this helps!

Sum of array in C

I'm working on a small program for school and can't get my array of doubles to sum properly. The specific error I'm getting is
warning C4244: 'return': conversion from 'double' to 'int', possible loss of data
on the line where sum is returned. And the sum displayed is gibberish.
The code is intended to:
fill an array of doubles with user input,
print the doubles on the screen in a column,
add up all the doubles in the array, and
print the sum onto the screen.
Code
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#define MAX_SIZE 15
void FillArray(double a[], int *i);
void PrintArray(double a[], int i);
SumArray(double a[], int *i);
int main()
{
double input[15];
int input_size;
double sum;
FillArray(input, &input_size);
PrintArray(input, input_size);
sum = SumArray(input, &input_size);
printf("The sum is %f\n", sum);
return 0;
}
void FillArray(double a[], int *i)
{
int k;
printf("Filling an array of doubles\n");
printf("How many doubles do you want to enter (<15)\n");
scanf(" %d", i);
for (k = 0; k <*i; k++)
{
printf("Enter double:\n");
scanf("%lf", &a[k]);
}
}
void PrintArray(double a[], int i)
{
int k;
printf("Printing an array of integers:\n");
for (k = 0; k<i; k++)
{
printf("%f\n", a[k]);
}
printf("\n");
}
SumArray(double a[], int *i)
{
int k;
double sum = 0;
for (k = 0; k<*i; k++);
{
sum +=a[k];
}
return (sum) ;
}
You need to specify double SumArray(...) instead of merely SumArray(...) where you declare and define the function. If you do not specify a return type, int is assumed. Specifically:
void FillArray(double a[], int *i);
void PrintArray(double a[], int i);
double SumArray(double a[], int *i);
/*^^^^^^-- add return type*/
int main()
and
double SumArray(double a[], const int numElements)
/*^^^^^^- same deal*/ /* also ^^^^^ ^^^^^^^^^^^ */
{
int k;
double sum = 0.0; /* Edit 3: 0.0 rather than 0 for clarity */
for (k = 0; k < numElements; ++k) /* no ; here! --- Edit 3: ++k for speed and good practice */
{ /* ^^^^^^^^^^^ */
sum +=a[k];
}
return (sum) ;
}
Edit Also, you can use const int numElements instead of int *i in SumArray. You don't need to modify the value inside SumArray, so you don't need the * and you can specify const. And it's a good practice to give your variables descriptive names, e.g., numElements instead of i. That will help you understand your own code when you have to maintain it later! (Ask me how I know. ;) )
To use this, you also need to change the call in main to remove the &:
sum = SumArray(input, input_size);
/* ^ no & here */
Edit 2 As #BLUEPIXY pointed out, the trailing ; on the for loop was misplaced. As a result, the {} block ran once, after the loop had completed. That would be a significant cause of the "gibberish" you saw: the effect was to set k=numElements and then set sum=a[numElements], which was a non-existent element. So the sum was being set to whatever random memory contents happened to be after a.

Recursive function calculating average from int array three by three elements

Calculating average three by three elements and replacing those elements with the average result.
Example array [1,2,7,-2,5,0, 2,8]
After transformation [3,3,3,1,1,1,5,5]
Something is wrong, I can't get it to work.
#include <stdio.h>
int main ( ) {
int n, c[n];
int *avg;
int pom=0;
printf("Enter lenght of array\n");
scanf("%d",&n);
printf("Enter elements");
for(i = 0;i < n; i++)
scanf("%d",c[i]);
avg=Average(c , n, pom);
for(i = 0; i < n; i++)
printf("Avg elements= %d",*(avg+i))
return 0;
}
int Average(int arr[], int size, int z)
{
int k, l, m, Asum;
if (size < 0) {
return arr;
} else {
k=arr[z];
l=arr[z+1];
m=arr[z+2];
Asum=(k + l + m)/3;
arr[z]=Asum;
arr[z+1]=Asum;
arr[z+2]=Asum;
}
return Average(arr,size--,z++);
}
int n, c[n]; is a problem. n is uninitialized so the size of the array is who-knows-what? This is undefined behavior.
Instead
int main(void) {
int n;
int *avg;
int pom=0;
printf("Enter length of array\n");
if (scanf("%d",&n) != 1) return -1;
int c[n];
for(i = 0;i < n; i++)
// scanf("%d",c[i]);
scanf("%d",&c[i]); // pass the address of an `int`
Likely other issues too.
Try simple input first, imagine what happens when you enter only 1 number, what will the Average function do? Don't run the code but try to execute it in your head or with pencil and paper. If you think the program only has to work with three or more numbers, try three.
A serious program would explicitly reject invalid input.

C programming : functions with arrays

I'm trying to write a function which finds the largest value in a 2d array with row of 4 and col of 4 where the 2d array is filled with user input. I know my main error is with the array in the function but am not sure what it is.
It would be greatly appreciated if someone could find where I went wrong rather than writing a new code. Unless I just went south.
My attempt:
#include <stdio.h>
void largest(int array);
int main() {
int x,y,trash;
int array[4][4];
int row = 4;
int col = 4;
int bigNum,greater;
bigNum=largest(array);
printf("Please enter a value: ")
for(x=0;x<row;x++) {
for(y=0;y<(col);y++) {
scanf("%d",&array[x][y]);
scanf("%d",&trash);
}
}
printf("The largest number in the array is : ",bigNum);
}
void largest(int array[][]) {
for(x=0; x<row; x++) {
for(y=0; y<(col-1); y++) {
if (array[x][y] > array[x][y+1]) {
array[x][y+1] = array[x][y];
}
}
printf("\n")
}
big = array[x][y];
return big;
}
There are a few problems to address here, the first is you can't have int array[][] as a parameter, you need to provide all but the first dimension, int array[][4] would suffice in this limited case.
However, since row and col are local variables in main they aren't visible to your largest functions body, so they'll need to be passed, make the signature
void largest(int row, int col, int array[row][col]);
Since this is a void function, it can't return any value. It will modify the array it's given in place though, so the changes will be visible.
If you're looking for the straight-up log error, the function to find the largest is pretty crazy. A saner implementation would be to just track the largest element you've seen so far:
int largest(int row, in col, int array[row][col]) {
int big = array[0][0]; // assume the first element is the largest
for (int i = 0; i < row, ++i) {
for (int j = 0; j < col; ++j) {
if (array[i][j] > big) big = array[i][j];
}
}
return big;
}
you could then call the function from main as
int bigNum = largest(row, column, array);
You have declared the function largest as void and trying to store the return value of the function, it is not possible, so change it as int data type.
Then the row and the col variable value is not passed to the largest function.
either you should declare it globally or pass it as a argument to the largest function.
And you are trying to get the value for trash, I don't know what is the need for that. you can remove it.
And do the following changes in the largest function:
#include <stdio.h>
int largest(int [4][4]);
int row = 4;
int col = 4;
int main()
{ int x,y,trash;
int array[4][4];
int bigNum,greater;
printf("Please enter a value: ");
for(x=0;x<row;x++)
{
for(y=0;y<col;y++)
{
scanf("%d",&array[x][y]);
//scanf("%d",&trash);
}
}
bigNum=largest(array);
printf("The largest number in the array is : %d\n",bigNum);
return 0;
}
int largest(int array[4][4])
{
int x=0,y=0,big=array[0][0];
for(x=0;x<row;x++)
{
for(y=0;y<col;y++)
{
if (array[x][y]>big)
{
big = array[x][y];
}
}
printf("\n");
}
return big;
}
Try this code!!!!!
You need to get the values in the array from the user first. So you main should be:
int main()
{ int x,y,trash;
int array[4][4];
int row = 4;
int col = 4;
int bigNum,greater;
printf("Please enter a value: ")
for(x=0;x<row;x++)
{
for(y=0;y<(col);y++)
{
scanf("%d",&array[x][y]);
scanf("%d",&trash);
}
}
bigNum=largest(array);
printf("The largest number in the array is : ",bigNum);
return 0; //Because it is "int" main and not "void" main
}
Array is not initialized and you are doing this
bigNum=largest(array);
You should be finding the largest when you have elements in your array.
There are many other bugs in this code:
The largest function is not proper and it is returning void
You can't have array[][] as your parameter and it should be array[][4].
OMG when I went through the code I found that there is bug in almost each and every line.
#include <stdio.h>
int largest(int array[][4]);
int main()
{ int x,y;
int array[4][4];
int row = 4;
int col = 4;
int bigNum;
printf("Please enter a value: ");
for(x=0;x<row;x++)
{
for(y=0;y<(col);y++)
{
scanf("%d",&array[x][y]);
}
}
bigNum=largest(array);
printf("The largest number in the array is : %d",bigNum);
}
int largest(int array[][4])
{
int max=0;
int x,y;
max = array[0][0];
for(x=0;x<4;x++)
{
for(y=0;y<4;y++)
{
if (array[x][y]>max)
{
max = array[x][y];
}
}
}
return max;
}
Errors in your code
You cannot pass two dimensional arrays like you are doing.
Your logic to find the largest is not proper, you are comparing at any movement two adjacent elements and if the first is small you are actually making them equal
Variable scoping errors, row, col, x and y are bound to main method and you cannot access them in other method. look at Global Variables to access them anywhere you want within the program file.
Unnecessary scanf for trash and printf in largest method.
#include<stdio.h>
int row = 4;
int col = 4;
int largestElement(int array[][4],int row);
int main()
{
int x,y;
int array[row][col];
int bigNum,greater;
printf("Please enter a value: ");
for(x=0;x< row;x++)
{
for(y=0;y< col;y++)
{
scanf("%d",&array[x][y]);
}
}
bigNum = largestElement(array, sizeof(array) / sizeof(array[0]));
printf("The largest number in the array is : ",bigNum);
}
int largestElement(int array[][4],int row)
{
int x,y;
int big =0;
for(x=0;x<row;x++)
{
for(y=0;y<(col-1);y++)
if (big < array[x][y]) big = array[x][y];
}
return big;
}
You try this code for finding the biggest elements in the Two dimensional array.
#include <stdio.h>
int largest(int [][4],int ,int);
int main() {
int x,y,trash;
int array[4][4];
int row = 4;
int col = 4;
int bigNum,greater;
printf("Please enter a value: ");
for(x=0;x<row;x++) {
for(y=0;y<col;y++) {
scanf("%d",&array[x][y]);
}
}
bigNum=largest(array,row,col);
printf("The largest number in the array is:%d ",bigNum);
return 0;
}
int largest(int array[][4], int row, int col)
{
int x,y,big=array[0][0];
for(x=0; x<row; x++) {
for(y=0; y<col-1; y++) {
if(big<array[x][y])
big=array[x][y];
}
}
return big;
}

storing input into malloc array (1d and 2d) and printing

I am tryin to take input from the user and store it into an array and print it out: i have 2 functions:
/* Read a vector with n elements: allocate space, read elements,
return pointer */
double *read_vector(int n){
double *vec = malloc(n * sizeof(double));
int i;
for (i = 0; i < n; i++)
vec[i] = n;
return vec;
}
and the print function is:
void print_vector(int n, double *vec){
int i;
for (i = 0; i < n; i++) {
printf("%d\n", vec[i]);
}
}
the main function is:
#include <stdio.h>
#include <stdlib.h>
double *read_vector(int n);
void print_vector(int n, double *vec);
void free_vector(double *vec);
int main(){
int n;
double *vector;
/* Vector */
printf("Vector\n");
printf("Enter number of entries: ");
scanf("%d", &n);
printf("Enter %d reals: ", n);
vector = read_vector(n);
printf("Your Vector\n");
print_vector(n,vector);
free_vector(vector);
}
when i run this, it does not let me enter any numbers, it just skips it and prints out 0's. How do i fix this?
Try the code below. You're almost certainly either not compiling with warnings, or ignoring the warnings. All warnings mean something, and to a beginner they all matter. With gcc use the -Wall option, or even -pedantic.
As halfelf pointed out, you need a scanf in your read loop but it needs to be a pointer (&vec[i]). Always return something at the end of main. Also check the return value of malloc, it could fail and return a null pointer.
#include <stdio.h>
#include <stdlib.h>
double *read_vector(int n)
{
double *vec = malloc(n * sizeof(double));
int i;
for (i = 0; i < n; i++) {
printf("Enter number %i of %i: ", i + 1, n);
scanf("%lf", &vec[i]);
}
return vec;
}
void print_vector(int n, double *vec)
{
int i;
for (i = 0; i < n; i++) {
printf("%f\n", vec[i]);
}
}
void free_vector(double *vec)
{
free(vec);
}
int main()
{
int n;
double *vector;
printf("Vector\n");
printf("Enter number of entries: ");
scanf("%i", &n);
vector = read_vector(n);
printf("Your Vector\n");
print_vector(n, vector);
free_vector(vector);
return 0;
}
In the read_vector(int n) function's for loop:
for (i=0; i<n; i++)
vec[i] = n; // this should be scanf("%lf",vec+i) to read input from stdin
and notice your { and } there. If there's only one line in the loop, { and } is not necessary, OR you have to use a pair of them. The return clause must be out of the loop.
Btw, add return 0 at the end of your main function.
simple..you forgot to write scanf..!
double *read_vector(int n)
{
double *vec = malloc(n * sizeof(double));
int i;
for (i = 0; i < n; i++)
scanf("%d",&vec[i]);
return vec;
}

Resources