Just learning C and I'm trying to understand how I get the sum of numbers using 2 functions but the results is incorrect.
I'm trying to ask the user for 10 numbers which are stored in an array in function main. The sum is then calculated in a separate function and then displayed in main.
Here is my original code without multiple functions that works:
int main()
{
int n[10];
int index;
int sum_n = 0;
int largest_n;
int smallest_n;
int *p;
p = &n[10];
int a;
printf("Enter 10 Integers\n");
for (index = 0; index < 10; index ++){
scanf("%d", &n[index] );
sum_n += n[index];
}
printf("The Sum of numbers is %d\n", sum_n);
}
Here is me trying to convert it to functions but the sum isn't working out:
int calculations (int);
int main()
{
int n[10];
int index;
int largest_n;
int smallest_n;
int *p;
p = &n[10];
int a;
printf("Enter 10 Integers\n");
for (index = 0; index < 10; index ++){
scanf("%d", &n[index] );
}
if (n[index] = 10){
//sum_n += n[index];
printf("The Sum of numbers is %d\n",calculations(n[index]));
}
&
int calculations (int num){
int sum_n = 0;
sum_n += num;
return sum_n;
}
When I run the second program using functions for numbers 1 to 10 I'm getting:
I'm either doing something blatantly wrong or not understanding what I'm doing at all.
every time you call a function the variables declared within a function are reset.
in case you want a variable that won't be reset every time you call a function you can simply make it static.
moreover you are passing and argument n[10] but your array stores number from n[0] to n[9] . And if you want sum of all ten numbers then you have to call calculation function for every number or you could just pass whole array. here is modified code.
#include<stdio.h>
int calculations (int);
int main()
{
int n[10];
int index;
int largest_n;
int smallest_n;
int *p;
p = &n[10];
int a;
int ans=0;
printf("Enter 10 Integers\n");
for (index = 0; index < 10; index ++){
scanf("%d",&n[index]);
ans = calculations(n[index]);
}
printf("The Sum of numbers is %d\n",ans);
}
int calculations (int num){
static int sum_n;
sum_n += num;
return sum_n;
}
First you don't need array for sum in this code, Second always remember to check what returned by scanf.The code is very simple.
first part with main
int main()
{
int n;
int sum=0;
printf("Enter 10 Integers\n");
for (int index = 0; index < 10; index ++){
if(scanf("%d", &n))
sum+=n;
}
printf("The Sum of numbers is %d\n",sum);//calculations(n));
}
Second using function calculation
int sum=0;
void calculation(int num){
sum+= num;
}
int main()
{
int n;
printf("Enter 10 Integers\n");
for (int index = 0; index < 10; index ++){
if(scanf("%d", &n))
calculation(n);
}
printf("The Sum of numbers is %d\n",sum);//calculations(n));
}
Your function calculations() simply returns its parameter (0 + num is simply num).
The statement
int sum_n = 0;
in it resets sum_n to 0 every time of calling it.
Move this statement out of it - directly into main() function (and before calling calculations()).
Corrections mentioned in comments below.
int calculations (int *num){ //Should be a pointer or array eg. int num[] as you want to pass an array to this function
int sum_n = 0;
int i;
//Create loop here to iterate over array and sum elements
for(i=0; i<sizeof(num)/sizeof(int); i++)
sum_n+=num[i];
return sum_n;
}
And
if (n[index] = 10){ //This is logically incorrect. This should be if(index==10).
// n[index]=10 will assign 10 to a[10] and if will still pass as if(10) is true but make a note of it. Don't use assignment operator inside if, you need comparison operator `==`
printf("The Sum of numbers is %d\n",calculations(n[index])); //You should call calculations like this -> calculations(n). You should pass whole array not just an element.
}
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;
}
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;
}
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.
I'm attempting to make a program that generates an array of random numbers where no two cells contain the same number within a given range.
Example: asking it to make an array of 4 should yield something like: 4 2 1 3, instead what I get is this: 4 2 1360726912 245694014
#include <stdio.h>
#include <time.h>
#define TRUE 1
#define FALSE 0
// generates a random number within a given range
int random(int from, int to) {
int
high = to + 1,
low = from;
return (rand() % high - low) + low;
}
// returns a random number different from any number in the array
int gen_different(int arr_len, int arr[]) {
int rand_val = random(1, arr_len);
int matches = FALSE;
for(int i = 0; i < arr_len; i++) {
if(rand_val == arr[i]) matches = TRUE;
}
if(matches) gen_different(arr_len, arr);
return rand_val;
}
// generates an array with a given number of cells, containing all different numbers
void gen_arr(int count, int arr[]) {
for(int i = 0; i < count; i++)
arr[i] = gen_different(count, arr);
}
int main() {
srand(time(NULL));
printf("Please enter an array number: ");
int num = 0;
scanf("%d", &num);
int* arr[num];
gen_arr(num, arr);
for(int i = 0; i < num; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
I get that my issue has something to do with pointers, but I'm not quite sure what I should change to make it work. Any help?
you are initializing arr[num] as
int* arr[num]; //array of pointers to integers
it should be like
int arr[num]; ////array of integers
One possible problem is you are declaring your array as a pointer to an array
int* arr[num];
this is the same as:
int ** arr;
You should actually use
int arr[num];
As you are expecting an array in your functions.
I think that:
int* arr[num];
is not what you want. Try
int arr[num];
(Note this is not legal C before C99)
Expression:
(rand() % high - low) + low
looks suspect as it is the same as rand() % high.
Did you mean:
(rand() % (high - low)) + low
?