Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <errno.h>
- /* define a more readable value for how many grades we want */
- #define NUM_GRADES 10
- /* weird way of making swap in C */
- #define swap(type, i, j) {type t = i; i = j; j = t;}
- int main(int argc, char** argv){
- int i,j,ret;
- size_t read_b,size; // C is weird, ignore
- int grades[10];
- char buf[10]; // ignore
- /* this is a String in C, logistics arent really relevant */
- char *s_name;
- s_name = (char*) malloc( sizeof(char) * 100 );
- fprintf(stdout, "Please enter the student's name.\n"); // print message to user
- /* read entire line from terminal and store it somewhere */
- read_b = getline(&s_name, &size, stdin);
- fprintf(stdout, "Please enter 10 grades.\n"); // print message to user
- /* read 10 integers from user input to terminal */
- for( i = 0; i < NUM_GRADES; ++i ) grades[i] = 0;
- for( i = 0; i < NUM_GRADES; ++i ){
- /*
- * reads an input in terminal
- * then converts it to an integer and saves it
- * NOTE: This is a poor example of how to do this right
- * it's just simple/fast.
- */
- ret = scanf( "%s", buf );
- grades[i] = atoi( buf );
- if( grades[i] < 0 || grades[i] > 100 ) exit(1); // error
- if( ret == 0 || ret == EOF ) exit(1); // error
- } // end for
- for( i = 2; i < NUM_GRADES; ++i ){
- // sum += grades[i];
- printf("Grades[%d] = %d\n", i, grades[i]);
- }
- /* bubble sort */
- int flag;
- for( ;; ){ // infinite loop
- flag = 0;
- for( j = 1; j < NUM_GRADES; ++j ){
- /* "bubbleup" */
- if( grades[j-1] > grades[j] ){
- swap( int, grades[j-1], grades[j] );
- flag = 1;
- } // end if
- } // end j for
- if( flag == 0 ) break; // if flag is false eg 0 stop looping
- } // end i for
- int sum;
- sum = 0;
- /*
- * calculate the sum
- * start at index 2 because the array is in
- * increasing order thus grades[0] and grades[1]
- * are the lowest and the dropped grades
- */
- for( i = 2; i < NUM_GRADES; ++i ){
- sum += grades[i];
- printf("Grades[%d] = %d\n", i, grades[i]);
- }
- /*
- * output the name, sum and average of scores
- *
- * %s tells the function to print that string (s_name)
- * %d tells the function to print that integer (sum)
- */
- fprintf(stdout, "Student name: %s\nTotal of top 8 scores: %d\nAverage: %d\n", s_name, sum, sum/8);
- /* C stuff */
- exit(1);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement