Thread: Addition using function involving array

  1. #1
    Registered User
    Join Date
    Sep 2017
    Posts
    1

    Addition using function involving array

    I know there are some serious issues with this program, please help correct it.

    What I want the program to do is to scan an array of numbers and use function to calculate the sum


    Code:
    /"Program to enter a list of number and perform their addition using function"/
    
    
    #include<stdio.h>
    
    
    int addn(int b[])
    
    
    {
    int i=1;  /"initialize i to 1"/
    
    
    int sum=0;
    
    
    sum+= b[i];
    
    
    return sum;
    
    
    }
    
    
    
    
    main()
    {
    
    
    int j, n, a[20];
    int result;
    printf("Enter the count of numbers to be added:\n");
    
    
    scanf("%d", &n); /"The 
    
    
    for(j=1;j<=n;j++)
    {
    scanf("%d", &a[j]); /"number input"/
    
    
    printf("Entered numbers are: %10d\n", a[j]);   /"Display the entered numbers"/
    
    
    printf("Performing addition\n");
    
    
    result= addn(a);
    }
    
    
    printf("The sum is :%d", result);  /"Display the result"/
    
    
    return 0;
    
    
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,667
    > result= addn(a);
    1. Add the n parameter, so result= addn(a,n);

    2. Move it down a line, so it's no longer part of the for loop in main.

    3. Put another for loop inside addn() to iterate over your array elements (that's why you also need n).
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Question involving Array and Char
    By KMAN999 in forum C Programming
    Replies: 7
    Last Post: 06-10-2011, 11:48 AM
  2. Help with an array involving integration?
    By gulfx01 in forum C++ Programming
    Replies: 2
    Last Post: 04-10-2010, 09:48 PM
  3. Replies: 2
    Last Post: 04-22-2009, 02:35 AM
  4. array involving even numbers
    By dantestwin in forum C++ Programming
    Replies: 13
    Last Post: 07-10-2004, 08:40 AM
  5. Question involving converting array->int
    By Unregistered in forum C++ Programming
    Replies: 8
    Last Post: 01-13-2002, 09:51 AM

Tags for this Thread