I was given an assignment to write a code which takes in numbers as input from the user and provides the sum of it, specifically by the use of pointer arithmetic i.e. no array subscripting a[i] is allowed.
Below is the code that I wrote, which got compiled and even ran. But almost always it gives the sum of the input numbers as 0. I tried to fix it, but to no avail. Thus, I am asking for help, any help is greatly appreciated.
#include<stdio.h>
#define N 5
int sum_array( const int *p, int n)
{
int sum, a[N];
sum = 0;
for(p=&a[0]; p<&a[N]; p++)
sum += *p;
return sum;
}
int main()
{
int a[N], *i,x;
printf("Enter %d Numbers: ", N);
for(i=a; i<a+N; i++)
scanf("%d", i);
// all the input values get scanned as i or the array a
x= sum_array(i,N);
printf("the sum is %d\n", x);
return 0;
}
Beware, you are declaring array int a[N] in both main and sum_array. They are in different scopes, so they are different arrays (and the one from sum_array is never initialized so reading it invokes Undefined Behaviour).
The correct way is to pass the array along with its used length:
Here is a fixed version:
#include<stdio.h>
#define N 5
int sum_array( const int *a, int n) // a points to a array of at least n elements
{
int sum = 0; // initialize at definition time
for(const int *p=a; p<&a[n]; p++) // have the pointer p take all values from a
sum += *p;
return sum;
}
int main()
{
int a[N], *i,x;
printf("Enter %d Numbers: ", N);
for(i=a; i<a+N; i++)
scanf("%d", i);
// all the input values get scanned as i or the array a
x= sum_array(a,N); // pass the array address, not a pointer past last element
printf("the sum is %d\n", x);
return 0;
}
Finally it is mainly a matter of taste, but I was too often burnt for trying to add an instruction in a for loop without braces, so I strongly recommend using always braces for loops:
for(i=a; i<a+N; i++) {
scanf("%d", i);
}
int sum_array( const int *p, int n)
{
int sum = 0, i = 0;
for(i = 0; i < n ; i++)
sum += *(p+i);
return sum;
}
int main(void)
{
int a[N], i = 0, x = 0;
printf("Enter %d Numbers: ", N);
for(i=0; i<N; i++)
scanf("%d", a+i);
// all the input values get scanned as i or the array a
x= sum_array(a,N);
printf("the sum is %d\n", x);
return 0;
}
In x= sum_array(i,N); i is the iterator of your loop so after the loop has finished it points to the first position after the array.
You should pass the original array instead x= sum_array(a,N);
In the sum function you just throw away the passed pointer and replace it with your local a[].
int sum_array( const int *p, int n)
{
int sum = 0;
int *end = &p[n]; // first element after the array.
for(; p<end; p++) // just use p because you don't need the reference to the start of the array
{
sum += *p;
}
return sum;
}
but as you said that array notation is not allowed you can change it as follows
#include "stdio.h"
#define N 5
int sum_array( const int *p, int n)
{
int sum = 0;
const int *end = p+n; // first element after the array.
for(; p<end; p++)
{
sum += *p;
}
return sum;
}
int main()
{
int *a, *i, x;
a = malloc(N * sizeof(*a));
if (a == NULL)
exit(-1);
printf("Enter %d Numbers: ", N);
for(i=a; i<a+N; i++)
{
scanf("%d", i);
}
// all the input values get scanned as i or the array a
x= sum_array(a,N); // pass the array address, not a pointer past last element
printf("the sum is %d\n", x);
return 0;
}
in general, when programming, the code should be kept as simple as possible while still being complete.
The program criteria shows no need to keep a number after it is applied to the sum of the numbers, So in the proposed code, the input number is only kept long enough to be applied to the sum, then it is discarded.
The following proposed code:
cleanly compiles
performs the desired functionality
is kept very simple
properly checks for; and handles any errors
And now the proposed code:
#include <stdio.h> // scanf(), printf(), fprintf(), stderr
#include <stdlib.h> // exit(), EXIT_FAILURE
#define N 5
int main( void )
{
int num = 0;
int sum = 0;
printf("Enter %d Numbers: ", N);
for(size_t i=0; i<N; i++)
{
if( scanf("%d", &num) != 1 )
{
fprintf( stderr, "failed to read number\n" );
exit( EXIT_FAILURE );
}
// implied else, scanf successful
sum += num;
}
printf( "the sum is %d\n", sum );
return 0;
}
Related
When running this program using pointers and arrays to calculate the grade point average from the user input, it outputs a garbage value. How can I alter the code so that the output is correct?
void Insert_Grades(int *array)
{
int grades[4];
int i;
for (int i = 0; i < 4; i++)
{
printf("Enter grade %d: ", i + 1);
scanf("%d", &grades[i]);
}
array = grades;
}
void Calculate_Avg(int *array)
{
int i;
float avg;
float sum = 0;
for (i = 0; i < 4; i++)
{
sum += *(array + i);
}
avg = sum / 4;
printf( "Grade point average is: %f ", avg);
}
int main()
{
int grades[4];
int i;
printf("Enter the number of grades:\n");
Insert_Grades(grades);
Calculate_Avg(grades);
printf("\n");
return 0;
}
you cant assign arrays.
This operation assigns local pointer array with reference of the local array grades. For the extral world this operation means nothing.
array = grades;
You need to copy values instead.
memcpy(array, grades, sizeof(grades));
or
for (size_t index = 0; index < 4; index++)
array[index] = grades[index];
There are multiple problem in your code:
in function Insert_Grades, value are read into the local array grades. The last instruction array = grades has no effect because it only modifies the argument value, which is just local variable, a pointer to int that now points to the first element of grade array.
This explains why the program outputs garbage because the array grades defined in the main() function is uninitialized and is not modified by Insert_Grades().
You could copy the array grade to the caller array pointed to by array, but it seems much simpler to use the array pointer to read the values directly where they belong.
the variable i is defined multiple times, with nested scopes.
you should test the return value of scanf() to detect invalid or missing input.
Here is a modified version:
#include <stdio.h>
void Insert_Grades(int *array, int count) {
for (int i = 0; i < count; i++) {
printf("Enter grade %d: ", i + 1);
if (scanf("%d", &array[i]) != 1) {
fprintf(stderr, "invalid input\n");
exit(1);
}
}
}
float Calculate_Avg(const int *array, int count) {
float sum = 0;
for (int i = 0; i < count; i++) {
sum += array[i];
}
return sum / count;
}
int main() {
int grades[4];
int count = sizeof(grades) / sizeof(*grades);
float avg;
printf("Enter the grades:\n");
Insert_Grades(grades, count);
avg = Calculate_Avg(grades, count);
printf("Grade point average is: %.3f\n", avg);
return 0;
}
I am new to programing.
I'm doing an exercise witch the user inserts numbers in an array and the program prints the average of those numbers.
But part of the exercise is making the numbers that the user inserts using a function, and thats where i'm struggling.
my code:
#include <stdio.h>
main() {
int n = 10, i, array1[10];
float sum = 0.0, average;
printf("insert 10 numbers\n");
for (i = 0; i < n; ++i) {
printf("insert digit no%d: ", i + 1);
scanf("%d", &array1[i]);
sum += array1[i];
}
average = sum / n;
printf("average = %.2f", average);
return 0;
}
all the help is much apreciated :)
Here's a small program to show you how functions work:
#include "stdio.h"
void foo(int array[], int size)
{
for (int i = 0; i < size; i++)
scanf("%d", &array[i]);
}
size_t bar(int array[], int size)
{
int sum = 0;
for (int i = 0; i < size; i++)
sum += array[i];
return (sum);
}
int main(void)
{
int array[3] = {0};
int sum;
foo(array, 3);
sum = bar(array, 3);
printf("array sum = %d\n", sum);
return (0);
}
foo and bar are two functions, they both have a return type on the left side, a name (foo/bar), some parameters in the parentheses, and their body declaration between braces.
When you call a function from your main, you'll have to call it with its required parameters. In my exemple, both functions need an integer array, and an integer value as parameters. That's why we called it this way from the main: foo(array, 3); and bar(array, 3).
When we call a function, the given parameters are copied into memory so you can work with those params into the function body as if they were variables.
Some functions have a return type different than void. Those functions are able to (and must) return a value of the return type with the return statement. Those values can be used, assigned etc, as you can see with the instruction sum = bar(array, 3);
Even the main is a function !
If you want to move user input and average calculation into separate methods. It should be done something like this.
#include <stdio.h>
/*
* Takes an array and get input for N items specified
*/
void getUserInputForArray(int array[], int N) {
printf("insert %d numbers\n", N);
for (int i = 0; i < N; ++i) {
printf("insert digit no %d: ", i + 1);
scanf("%d", &array[i]);
}
}
/*
* Calculate average for a given array of size N
*/
float getAverage(int array[], int N) {
// Initialize sum to 0
float sum = 0.0f;
// Iterate through array adding values to sum
for (int i = 0; i < N; i++)
sum += array[i];
// Calculate average
return sum / N;
}
int main() {
int n = 10, array1[10];
// Pass array to method, since arrays in C are passed by pointers.
// So Even if you modify it in method it would get reflected in
// main's array1 too
getUserInputForArray(array1, n);
// Calculate Average by delegating average calculation to getAverage(...) method
float average = getAverage(array1, n);
printf("average = %.2f", average);
return 0;
}
My exercise is input list integer numbers from keyboard and the end of program by 0. Then print sum of array. This is my code:
#include <stdio.h>
#include <stdlib.h>
const int MAX_ITEMS = 50;
void inputIntegerNumber(int* a, int* count);
int sumOfInteger(int* n, int* count);
int main(int argc, char** argv) {
int x[MAX_ITEMS], count;
inputIntegerNumber(&x, &count);
printf("Sum of array is %d", sumOfInteger(&x, &count));
return (EXIT_SUCCESS);
}
void inputIntegerNumber(int* a, int* count ){
do{
printf("Please! input numbers: ");
scanf("%d", a);
*count++;
}while((*a != 0) && (*count != MAX_ITEMS));
}
int sumOfInteger(int* n, int* count){
int sum = 0;
for (int i = 0; i < *count; i++)
sum += *n;
return sum;
}
I don't know what's wrong with it? It doesn't give me a result same my thinks...
There are some problems like -
inputIntegerNumber(&x, &count);
printf("Sum of array is %d", sumOfInteger(&x, &count));
in both calls you pass &x but x is an array of int and your function expects int * not int (*)[]. This must have given an error atleast.
For both functions you can just pass the array x directly.
And in your function inputIntegerNumber this -
*count++;
You need to increment value of count, so it should be (*count)++. Dereference first and then increment the value.
You are doing some mistakes in your code like passing pointer to a pointer &x value(since array is basically a pointer to some memory location) and overwriting the same location again and again. In scanf("%d", a); you are overwriting the first location again and again without changing a in you input loop.You need to learn about arrays and their usage. In sumOfInteger function also you're not changing the value of n. I changed you code a bit and i was able to see desired output.
#include <stdio.h>
#include <stdlib.h>
const int MAX_ITEMS = 50;
void inputIntegerNumber(int* a, int* count);
int sumOfInteger(int* n, int* count);
int main(int argc, char** argv) {
int x[MAX_ITEMS], count = 0; // zero elements in array
inputIntegerNumber(x, &count);
printf("Sum of array is %d", sumOfInteger(x, &count));
return (EXIT_SUCCESS);
}
void inputIntegerNumber(int* a, int* count ){
int aIndex = 0;
do{
printf("Please! input numbers: ");
scanf("%d", &a[aIndex]);
aIndex++;
}while((a[aIndex-1] != 0) && (aIndex != MAX_ITEMS));
*count = aIndex;
}
int sumOfInteger(int* n, int* count){
int sum = 0;
for (int i = 0; i < *count; i++)
sum += n[i];
return sum;
}
when i run it i can see :
~/Documents/src : $ ./a.out
Please! input numbers: 1
Please! input numbers: 2
Please! input numbers: 3
Please! input numbers: 0
Sum of array is 6
You're overcomplicating things. Before you sit down to write a program, always write the general steps that must be done
Read the numbers from the command line
Convert them to ints and save them in memory
Calculate the sum
Print it
Here is the revised program
#include <stdio.h>
#include <stdlib.h> /* for strtol */
#define DIE(msg) fprintf(stderr, "%s", msg); exit(EXIT_FAILURE)
int main(int argc, char *argv[])
{
int *nums;
if (argc <= 1)
DIE("Usage: [int-list]\n");
/* skip program name */
--argc;
++argv;
nums = malloc(argc * sizeof(int));
if (!nums)
DIE("Out of mem\n");
for (int i = 0; i < argc; ++i) {
char *end;
double val = strtol(argv[i], &end, 0);
if (end == argv[i]) /* no digits detected */
DIE("Usage: [int-list]\n");
nums[i] = val;
}
printf("%d\n", add(nums, argc));
free(nums);
}
int add(int arr[], size_t n)
{
int sum = 0;
for (int i = 0; i < n; ++i)
sum += arr[i];
return sum;
}
To complete the strtol error handling is an exercise for the OP.
How to read space-separated integers representing the array's elements and sum them up in C?
I used the below code but it reads all the elements in a new line:
#include <math.h>
#include <stdio.h>
int main() {
int i = 0, N, sum = 0, ar[i];
scanf("%d" , &N);
for (i = 0; i < N; i++) {
scanf("%d", &ar[i]);
}
for (i = 0; i < N; i++) {
sum = sum + ar[i];
}
printf("%d\n", sum);
return 0;
}
Your array ar is defined with a size of 0: the code invokes undefined behavior if the user enters a non zero number for the number of items.
Furthermore, you should check the return value of scanf(): if the user enters something not recognized as a number, your program will invoke undefined behavior instead of failing gracefully.
Here is a corrected version:
#include <stdio.h>
int main(void) {
int i, N, sum;
if (scanf("%d", &N) != 1 || N <= 0) {
fprintf(stderr, "invalid number\n");
return 1;
}
int ar[N];
for (i = 0; i < N; i++) {
if (scanf("%d", &ar[i]) != 1) {
fprintf(stderr, "invalid or missing number for entry %d\n", i);
return 1;
}
}
sum = 0;
for (i = 0; i < N; i++) {
sum += ar[i];
}
printf("%d\n", sum);
return 0;
}
Note that the program will still fail for a sufficiently large value of N as there is no standard way to check if you are allocating too much data with automatic storage. It will invoke undefined behavior (aka stack overflow).
You should allocate the array with malloc() to avoid this:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int i, N, sum;
int *ar;
if (scanf("%d", &N) != 1 || N <= 0) {
fprintf(stderr, "invalid number\n");
return 1;
}
ar = malloc(sizeof(*ar) * N);
if (ar == NULL) {
fprintf(stderr, "cannot allocate array for %d items\n", N);
return 1;
}
for (i = 0; i < N; i++) {
if (scanf("%d", &ar[i]) != 1) {
fprintf(stderr, "invalid or missing number for entry %d\n", i);
return 1;
}
}
sum = 0;
for (i = 0; i < N; i++) {
sum += ar[i];
}
printf("%d\n", sum);
free(ar);
return 0;
}
Finally, there is still a possibility for undefined behavior if the sum of the numbers exceeds the range of type int. Very few programmers care to detect such errors, but it can be done this way:
#include <limits.h>
...
sum = 0;
for (i = 0; i < N; i++) {
if ((sum >= 0 && arr[i] > INT_MAX - sum)
|| (sum < 0 && arr[i] < INT_MIN - sum)) {
fprintf(stderr, "integer overflow for entry %d\n", i);
return 1;
}
sum += ar[i];
}
#include <math.h>
#include <stdio.h>
int main()
{
int i=0,N,sum=0;
scanf("%d" ,&N);
int ar[N];
for(i=0; i<N; i++)
scanf("%d",&ar[i]);
for(i=0; i<N; i++)
sum=sum+ar[i];
printf("%d\n", sum);
return 0;
}
This should be the code.
You have initially declared the array of size 0 (because i=0).
Even though you declared the array of size 0, when I ran it on my machine, it actually executed successfully with the correct output.
This is generally due to undefined behavior which means that we can only guess the output when the code is correct. If the code has undefined behavior, then it can do whatever it wants (and in the worst case the code will execute successfully giving the impression that it's actually correct).
Declaring a Variable Size Array (VLA) is optional in C11 standard. Thus, it depends on the implementation of the compiler whether it will support VLA or not. As pointed out by #DavidBowling in comments, if the compiler does support, then declaring a VLA of size 0 can invoke undefined behavior (which you should avoid in all cases). If it doesn't support, then this will simply give a compilation error and you'll have to declare the array size as some integer constant (example, int arr[100];).
#include <math.h>
#include <stdio.h>
int main()
{
int i=0,N,sum=0;
scanf("%d" ,&N);
int ar[N];
for(i=0; i<N; i++)
{
scanf("%d",&ar[i]);
}
for(i=0; i<N; i++)
{
sum=sum+ar[i];
}
printf("%d\n", sum);
return 0;
}
You should declare the array after accepting the value of N.
#include <math.h>
#include <stdio.h>
int main()
{
int i=0,N,sum=0;
scanf("%d" ,&N);
int ar[N];
for(i=0; i<N; i++)
{
scanf("%d",&ar[i]);
sum=sum+ar[i];
}
printf("%d\n", sum);
return 0;
}
As this is a very simple question I'll expand it a bit to include some good programming practices.
1. Analyze the problem
We have to complete two tasks here:
Read and store the numbers to array.
Sum the array elements.
Of course you can both read and calculate the same time, but we ❤ the SoC design principle. This will help you later with bigger programs.
2. Create the program structure
In this state we have to consider what function to use, as we already solved the data structure problem (we use array).
Of course, we always can put the whole procedure in main function but this would break the SoC principle.
The main principle here is:
I create a function for a separate procedure.
So we'll have to build two functions. Let's consider the following example:
ReadArrayData will be used to read the data from the standard input (your keyboard in other words) to array. But what will declare as parameters? We surely have to pass the array and the array size. The return type of this function will be void (we don't have to return something).
Keep in mind that if you pass array to function you can manipulate it as you please and keep these changes in your main program. This is because the arrays are passed always by reference to a function.
In the end this will be your function prototype:
void ReadArrayData(int arraySize, int array[]);
CalculateArraySum will be used to calculate the sum of the array elements. The function prototype will be the same as for ReadArrayData with the difference that the returning type will be int (we return the sum).
int CalculateArraySum(int arraySize, int array[]);
3. Write your program
#include <stdio.h>
void ReadArrayData(int arraySize, int array[]);
int CalculateArraySum(int arraySize, int array[]);
int main(void) {
int N;
printf("Give the array size: ");
scanf("%d", &N);
int array[N];
ReadArrayData(N, array);
int sumOfArrayElements = CalculateArraySum(N, array);
printf("The sum of array elements is %d.\n", sumOfArrayElements);
return 0;
}
void ReadArrayData(int arraySize, int array[]) {
printf("Give %d elements: ", arraySize);
for (int i = 0; i < arraySize; ++i) {
scanf("%d", &array[i]);
}
}
int CalculateArraySum(int arraySize, int array[]) {
int sum = 0;
for (int i = 0; i < arraySize; ++i) {
sum += array[i];
}
return sum;
}
I know this was a large scaled answer, but I saw you are new to computer programing. I just wanted to present you the main functionality to solve all kinds of problems. This was just a small introduction. In the end, you have to remember what steps we take to solve a problem. With time and as you solve many problems you will learn many many other things.
I'm trying to sort elements in an array from smallest to largest that a user inputs along with the size. This is my code so far:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAXVALUES 20
void sort(int *A[], int n) {
int i, tmp, j;
for (i = 0; i <= (n - 2); i++) {
for (j = (i + 1); j <= (n - 1); j++) {
if (*A[i] > *A[j]) {
tmp = *A[i];
*A[i] = *A[j];
*A[j] = tmp;
}
}
}
return;
}
int main(int argc, char *argv[]) {
int n, A[MAXVALUES], i;
printf("Enter an array and no. of elements in array: ");
scanf("%d%d", &A[MAXVALUES], &n);
sort(A[MAXVALUES], n);
printf("Ordered array is: \n");
for (i = 0; i <= (n - 1); i++) {
printf(" %d", A[i]);
}
return 0;
}
The compiler compiles it without any errors but it stops working after I put in the inputs. I've yet to quite grasp the theory behind arrays and pointers so could someone tell me where in my code I'm going wrong?
scanf("%d%d", &A[MAXVALUES], &n); is the problem
That's not how you read an array.
First you read the n, after that inside a loop you read every element like
scanf("%d", &A[i]); where i is the index from 0 to n
EDIT:
scanf("%d", &n);
int i = 0;
for(i = 0; i < n; i++)
{
scanf("%d", &A[i]);
}
This is what you want.
You can't use scanf() to read in a whole array at once.
This:
scanf("%d%d", &A[MAXVALUES], &n);
Makes no sense; it passes scanf() the address of the element after the last one in A, causing undefined behavior. The sort() call is equally broken.
To read in multiple numbers, use a loop. Also, of course you must read the desired length first, before reading in the numbers themselves.
Firstly I'll tell you a couple of things about your sorting function. What you want, is take an array (which in C is representable by a pointer to the type of elements that are in that array, in your case int) and the array's size(int) (optionally you can take a sorting method as an argument as well, but for simplicity's sake let's consider you want to sort things from lowest to highest). What your function takes is a pointer to an array of integers and an integer (the second argument is very much correct, or in other words it's what we wanted), but the first is a little more tricky. While the sorting function can be wrote to function properly with this argument list, it is awkward and unnecessary. You should only pass either int A[], either int *A. So your function header would be:
void sort1(int *A, int n);
void sort2(int A[], int n);
If you do this however, you have to give up some dereferencing in the function body. In particular I am referring to
if (*A[i] > *A[j]) {
tmp = *A[i];
*A[i] = *A[j];
*A[j] = tmp;
} which should become
if (A[i] > A[j]) {
tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
You should check out the operators [] and *(dereference) precedence http://en.cppreference.com/w/c/language/operator_precedence
Now, to adapt to these changes (and further correct some code) your main would look like so:
int main(int argc, char *argv[])
{
int A[MAXVALUES], n;
do{
printf("n="); scanf("%d", &n);
}while(n < 0 || n > 20);
int i;
for(i = 0; i < n; ++i)
scanf("%d", &A[i]); //this will read your array from standard input
sort(A, n); //proper sort call
for(i = 0; i < n; ++i)
printf(" %d", A[i]);
printf("\n"); //add a newline to the output
return 0;
}