Thread: C Homework

  1. #16
    Registered User Cesia's Avatar
    Join Date
    Dec 2011
    Posts
    15
    I actually avoid forums and such to ask for help, but my friends in the class are as lost as I am, one of them having taken the C++ class already. I'm looking over/in the tutorial on here already. Yep, this is actually a university, somehow. I was at a community college out of high school where I did VB; we used VB6 at the time. I had got decent for it at that level we were doing, but that was a few years ago. Haven't touched it since....well, I tried a few times but couldn't remember anything.

    I've made some progress, but I have run into something. Since I'm using scanf, I figured I'd do some print statements to see if it was working. For some reason, once I get to the 8th element, it's reassigning my variable for the number of elements thus ending the loop. I don't see a statement to reassign that variable at that given point. This is just me working with scanf and making the array.

    Code:
    #include <stdio.h>
    
    int main() {
    
        int numElem = 0;
        int array[numElem];
        int i;
     
        printf("Enter the number of elements: \n");
        scanf("%d", &numElem);
        printf("Now enter the elements one at a time.\n");
        for (i = 1; i < numElem; i++) {
            printf("Element %d: ", i);
            scanf("%d", &array[i]);
            printf("i = %d, numElem = %d\n", i, numElem);
        }
    
        printf("Number of elements: %d\n", numElem);
        for(i=1; i <= numElem; i++){
            printf("Element %d: %d\n", i, array[i]);
        }
        return 1;

  2. #17
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Arrays don't magically resize themselves in C.

    Your code has created array with size zero, since that is the initial value of numElem. This means array has no elements whatsoever. Subsequently changing the value of numElem does not magically resize the array. Similarly, scanf("%d", &array[i]) does not magically make array[i] a valid element of array.

    Because of that, your code is trashing random areas of memory every time you call scanf(). It just so happens, on your system, that the random area of memory being trashed corresponds to some variable (I'm guessing i).

    Try
    1) declaring array to be a pointer to int, not an array of int.
    2) after reading in numElem, and before the loop, allocate memory for your array. For example : array = malloc(numElem * sizeof(int)). If you do this, use free(array) when you no longer need the array.

    You also are not helping yourself with array indices starting at 1. Array indexing in C starts at zero. If an array has n elements, the valid indices for elements of that array are 0 to n-1. Writing to array[n] writes past the end of the array - and trashes whatever happens to be there.

    Also, by convention, main() returns zero when it succeeds, not 1.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  3. #18
    Registered User Cesia's Avatar
    Join Date
    Dec 2011
    Posts
    15
    hmm, ok. Now to look up pointers. Thanks.

    I was using return 1; to end the program there so as to not include any of the rest of my code. Couldn't figure out how to skip the rest without putting them all in comments, so I put return 1;.


    Edit: Thanks, I got that bit to work after some tinkering.
    Last edited by Cesia; 12-17-2011 at 09:30 PM.

  4. #19
    Registered User Cesia's Avatar
    Join Date
    Dec 2011
    Posts
    15
    Well, after a few infinite loops that crashed my computer, I just need to figure out the last 4 methods, and I'm done with this problem. For now, sleep.

    Thank you to those that helped. I may actually learn something about this language now.

  5. #20
    Registered User
    Join Date
    Oct 2011
    Posts
    23
    Quote Originally Posted by Cesia View Post
    Well, after a few infinite loops that crashed my computer, I just need to figure out the last 4 methods, and I'm done with this problem. For now, sleep.

    Thank you to those that helped. I may actually learn something about this language now.
    Here are some tutorials that might help you especially if you want to use dynamic arrays:
    Dystopian Code: Defining a Numeric Array Structure in C
    Dystopian Code: The Minimum and Maximum Element of an Array in C
    Dystopian Code: The Arithmetic, Geometric and Harmonic Mean of an Array in C

  6. #21
    Registered User Cesia's Avatar
    Join Date
    Dec 2011
    Posts
    15
    Thanks, I'll look them over.

  7. #22
    Registered User Cesia's Avatar
    Join Date
    Dec 2011
    Posts
    15
    On the plus side, I ordered 3 books online last night for c and c++. They're not exactly new, but better than nothing, right? Anyways.

    This is absolutely horrible, I know. If I can get it to work, I'll try and clean it up to put the functions outside of main and then call them and such, probably work on my documentation too. But this is my code thus far.

    I've tried a few different things such as making most things float so I wouldn't have to convert/cast, and that failed spectacularly. My values are ints. I attempted making an array of type float in hopes I could just use that for the methods that are of type float. However, I'm still getting 0. I've attempted making another variable of type float to use in the division aspect of the calculation, but I couldn't get the value of a to transfer to it. Or rather, it would and be 0. I'm not used to this where if you declare a variable as 0 at the beginning, it stays that way and that the stored value doesn't change. If I make the variable mean an int, I get the correct whole number but 0 if it's float.

    Code:
    #include <stdlib.h>#include <stdio.h>
    #include <time.h>
    #include <math.h>
    
    
    //code from qsort example
    int intComp(const void* a, const void* b) {
      int valA = *((int*)a);
      int valB = *((int*)b);
      if (valA < valB) return -1;
      if (valA == valB) return 0;
      else return 1;
    }
    
    
    //Main program.  PS:  It's a REAL mess. Gomen(sorry).
    int main() {
    
    
        int numElem = 0;
        int *array = (int*) malloc(numElem * sizeof(int));
        float *array2 = (float*) malloc((int)array * sizeof(float));
        int i;
        int max;
        int min;
        float mean;
        float median;
        int mode;
        float stdev;
        int a = 0;
        int temp = 0;
    
    
        printf("Enter the number of elements: \n");
        scanf("%d", &numElem);
        printf("Now enter the elements one at a time.\n");
        for (i = 0; i < numElem; i++) {
            printf("Element %d: ", i);
            scanf("%d", &array[i]);
        }
    
    
        //Sorts the array for easier use
        qsort(array, numElem, sizeof(int), intComp);
    
    
        //Makes a second array type float.
        for(i = 0; i < numElem; i++){
            array2[i] = array[i];
        }
        printf("Sorted Array:\n");  //test start
        for(i = 0; i < numElem; i++){
            temp = array[i];
            printf("%d ", temp);
        }
        printf("\n---\n");
        temp = 0;
        printf("Float Array:\n");
        for(i = 0; i < numElem; i++){
            temp = array2[i];
            printf("%d ", temp);
        }
        printf("\n---\n");   //test end
    
    
        //Computes the max
        max = array[numElem-1];
        
        //Computes the min
        min = array[0];
    
    
    //TODO: Compute the mean
        //computes the sum of array elements
        for(i = 0; i < numElem; i++){
            a += array2[i];
        }
        printf("sum: %d\n", a);  //test
        //sum of elements divided by the number of elements
        mean = a/numElem;
       
    //TODO: Compute the median
        //if number of elements is even
        if(numElem%2==0){
            a = array[numElem/2] + array[numElem/2-1]/2;
            median = array[a];
            printf("num/2 = %d , num/2-1 = %d\n", array[numElem/2], array[numElem/2-1]);
        }
        //if number of elements is not even
        else {
            median =  array[numElem/2];
        }
        
    //TODO: Compute the mode
        for(i = 0; i < numElem; i++){
            
    
    
        }
        
    //TODO: Compute the standard deviation
        
        
    
    
        //Prints the computed values next to appropriate lables
        printf("Max: %d\n", max);
        printf("Min: %d\n", min);
        printf("Mean: %f\n", mean);
        printf("Median: %f\n", median);
        printf("Mode: %d\n", mode);
        printf("StDev: %f\n", stdev);
    
    
        free(array);
        free(array2);
        return 0;
    }
    Edit: Well heck....I just realized part of my reason now. In my print statements. I was using %d instead of %f.
    So my problem now is. I get 4.00000 instead of 4.33333. I'm going to assume this has to do with casting or that the variables in the equation are of int instead of float? This hitch is also holding me up on calculating the median if the number of items are positive.
    Last edited by Cesia; 12-18-2011 at 05:30 PM. Reason: figured something out

  8. #23
    Registered User
    Join Date
    Sep 2010
    Posts
    25
    It probably has to do with data typing: What kind of data type does a variable hold? Integer? Or, float?

    Integer means whole number only. There are no decimals or fractional parts to an integer. When you load a float value into an integer variable, the computer will only load up the whole number parts. It'll just drop, or truncate, all of those decimal parts. It'll be as though those decimals weren't computed.

    What's worse, when this happens in your program by accident or because that's how the program was written, that cutting off of values can occur in bad ways. Unanticipated filtering of values by changing data type will muck up your results, if it wasn't done on purpose. The computer will do exactly as it was told. If the program says to cram a float value into an integer variable, that's what the program will do.

    In glancing over the code, I can see that this happened in many of the calculations involving the variable "a". In the variable declarations, "a" is declared as an integer. Later on, it is used in calculations with variables that hold floats. So, while floats were used to begin the calculations of the mean and the median, during the calculation process they were assigned to a variable that only accepts integers. This creates a cutoff; it's what's probably truncating some of your values.

    Generally speaking, you might have had less fuss with beginner design if you had declared these as float instead of integer: a, temp, min, max, and mode. Anything that holds a calculated value would have done well with float or double. The situations that call for integer counting include those times when a whole number or counting number set would do the trick: loop counters and array counters in this program would be good candidates for an integer data type.

    If you might need a decimal, at least make the data type a float. When you are counting discrete, unbreakable, non-fraction, items, use integer.

    Having a float hold an integer or an integer hold a float occurred in almost every value calculation in the program.

    In the following lines, maybe update the data type to allow the variable to hold a float: 24, 25, 28, 30 and 31.

    Notice also that one array holds integers and another holds float values. I don't remember where exactly in the posted code; but, my gut instinct is that this was part of one of the data type mixing problems.

    In the following lines, either an integer was loaded into a float or a float was loaded into an integer as part of a calculation: 49, 60, 67, 70, 76, 80, 91 and 96.

    Until the data type of the variables is cleared up, none of your calculations will be likely to reflect a good float value. By declaring variables that will hold calculation results or parts as float, you will reduce the effect of this type of error.
    Last edited by agxphoto; 12-18-2011 at 06:36 PM.

  9. #24
    Registered User Cesia's Avatar
    Join Date
    Dec 2011
    Posts
    15
    I attempted making them floats, but I get a lot of 'array subscript is not an integer'. The float array was my attempt to pass the numbers over into it so I could use them to calculate the floats. That didn't work so well. It usually starts with erroring at my qsort function then erroring later on depending on which I turn to float and so on. I don't assume there's a way to make it turn ints into floats? Worse comes to worse, I'll just turn everything into ints and take the hit to my grade for not having decimals where he wants. I still have two other programs to code. I do understand what you're saying though. Thanks. Might try to get this to work over break.

  10. #25
    Registered User
    Join Date
    Jul 2011
    Posts
    25
    Try to break your code up into individual functions. Your teacher is really, really not going to like you if everything is plugged into main. It also helps a ton for you, because you can figure out problems significantly easier if each primary task is split up.

    As far as your output is concerned, it likely has to deal with truncation or not properly casting. That's a very easy fix, though.
    Last edited by Amberlampz; 12-18-2011 at 09:11 PM.

  11. #26
    Registered User Cesia's Avatar
    Join Date
    Dec 2011
    Posts
    15
    Well, if I have time after my other two programs, I'll break it up. As of right now, I'm against the clock. Was working on this one all weekend and only got a small amount done on the other one that's due with it.

    I'm not really sure what truncation is, but I'll look it up once I get time.

  12. #27
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    Quote Originally Posted by Cesia View Post
    Code:
        int numElem = 0;
        int *array = (int*) malloc(numElem * sizeof(int));
        float *array2 = (float*) malloc((int)array * sizeof(float));
    What do you think you get when you allocate 0 bytes?
    Why do you cast a pointer "array" to an int?
    And what does it have to do with the number of bytes you wish to allocate?

    Tim S.
    Last edited by stahta01; 12-18-2011 at 11:45 PM. Reason: grammer

  13. #28
    Registered User Cesia's Avatar
    Join Date
    Dec 2011
    Posts
    15
    I'm not actually sure what I was doing there. I think I was trying to make it the size of the length of array.

  14. #29
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    Quote Originally Posted by Cesia View Post
    I'm not actually sure what I was doing there. I think I was trying to make it the size of the length of array.
    What you are doing it not safe! And, it is NOT what you say you are trying to do.

    You NEED to know the size of the space you wish to allocate using malloc at the time you call the function.

    Tim S.

  15. #30
    Registered User Cesia's Avatar
    Join Date
    Dec 2011
    Posts
    15
    Ok, finally got this finished. ^.^ Thanks so much for everyone's help. For some reason, it crashes at the end of the program after it's run everything. Not sure why, but it does what it needs to now. Classmate and myself worked on it after class today.

    Edit: I had my code posted, but then decided against it. For one, I don't want it causing a red flag if searched. Secondly, I learned a few things by doing it, so I figure posting it all for someone else just wouldn't be beneficial to them, right?
    Last edited by Cesia; 12-19-2011 at 08:51 PM. Reason: grammar; see mentioned edit

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Homework help...
    By pSyXaS in forum C Programming
    Replies: 2
    Last Post: 05-08-2011, 02:21 AM
  2. can somebody help me with my homework in c++
    By gosse in forum C++ Programming
    Replies: 19
    Last Post: 04-29-2011, 02:10 PM
  3. Help for Homework!
    By alionas in forum C Programming
    Replies: 4
    Last Post: 11-20-2010, 10:36 AM
  4. homework
    By misplaced in forum C++ Programming
    Replies: 18
    Last Post: 10-04-2004, 06:56 AM
  5. I want homework!
    By Tynnhammar in forum C++ Programming
    Replies: 9
    Last Post: 09-29-2004, 02:49 PM