Thread: Little help with my code

  1. #1
    Registered User
    Join Date
    Jul 2014

    Little help with my code

    So I started learning arrays in C. I made a simple program.

    #include <stdio.h>
    int grades[9];
    int main(void)
        int i = 0;
        int amount_subjects;
        int total;
        int ans;
        printf("How many subjects do you have? ");
        scanf("%d", &amount_subjects);
        while (i != amount_subjects)
            printf("Type in your grade: ");
            scanf("%d", &grades[i]);
        total = grades[0] + grades[1] + grades[2] + grades[3] + grades[4] + grades[5] + grades[6] + grades[7] + grades[8];
        printf("\nADD = %d", total);
        ans = total / amount_subjects;
        printf("\n%d", ans);
    I know it is not the best. I know I could of used a for statement. I know I should comment in my code.

    So it is a small program that calculates the average of your grades.
    Total amount of grades Divided by Amount of classes/Subjects
    See the program works fine with small numbers like 6, 11, 7
    It adds them to 24 Then it divides by 3 and the answer is 8. It is correct

    But for bigger numbers like 60,78,90,65,68,70,70,80,70,77 it does not add them correctly.

    Program adds them to 651 That is wrong. it should be 728.

    Did I make a mistake? What is it?

    Oh I used Dev-C++ 5.5.3 to compile it.
    Compiler is: TDM-GCC 4.7.1 64-Bit Release

  2. #2
    Registered User
    Join Date
    Oct 2006
    You listed 10 numbers, but you only have space for 9, and you only add up 9. Since you're certainly going beyond the bounds of your array, you're going to get undefined behavior. Literally anything can happen, from appearing to work correctly, to crashing your computer and wiping out your hard drive. If you want to add up an arbitrary number of elements, rather than a fixed number, you should probably look into using a dynamic array and malloc()/free().
    What can this strange device be?
    When I touch it, it gives forth a sound
    It's got wires that vibrate and give music
    What can this thing be that I found?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 09-19-2012, 01:58 PM
  2. Replies: 1
    Last Post: 03-10-2010, 11:28 AM
  3. Replies: 14
    Last Post: 04-01-2008, 02:23 AM
  4. producing c/c++ code from flowcharts,pseudo code , algorithims
    By rohit83.ken in forum C++ Programming
    Replies: 3
    Last Post: 02-20-2008, 07:09 AM
  5. Replies: 0
    Last Post: 02-21-2002, 06:05 PM

Tags for this Thread