user3474902
user3474902

Reputation:

Change the way my output is displayed in C program?

Sorry for bad topic name, i couldn't think of any. I have created this program that gets 7 values, add them and prints average, at the end it prints all the entered values in this format:

10, 15, 20, 15, 30, 45, 50,

I want it to display a comma after every value but after the last value I want to display dot like this:

10, 15, 20, 15, 30, 45, 50.

My code:

float sumFunk(float a, float b) {
         return ( (float) a + b);
}
float avgFunk(float a, float b) {
         return (a / b);
}

int main(void) {

float avg = 0;
float cWeek[7] = {0};
int counter, sum = 0;

for ( counter = 0; counter <= 6; counter++) {
    printf("Enter Temperature of day %d: ", counter+1); scanf("%f", &cWeek[counter]);
    sum = sumFunk(sum, cWeek[counter]);
}
avg = avgFunk(sum, counter);
printf("Average Temp of %d days: %.2f \n", counter, avg);

for ( counter = 0; counter <= 5; counter++ ) {
    printf("%.2f, ", cWeek[counter]);
    }
}

Upvotes: 3

Views: 75

Answers (2)

Mansoor Akram
Mansoor Akram

Reputation: 2056

after the following printf line:

printf("Average Temp of %d days: %.2f \n", counter, avg);

add this line:

int last_element = cWeek [ sizeof cWeek ];

and then at the end add this if loop:

if ( last_element == '\0' ) { //whenever a list ends, this '\0' end character is added as well.

printf("%.2f. ", cWeek[counter]);

}

Upvotes: -1

user3386109
user3386109

Reputation: 34829

The typical way to accomplish this task is with code like this

for ( counter = 0; counter < 7; counter++ )
    printf("%.2f%s", cWeek[counter], (counter + 1 == 7) ? ".\n" : ", " );

counter + 1 == 7 checks to see if the loop is about to end. If so, the string .\n is appended to the output, otherwise a comma and space are appended.

Upvotes: 2

Related Questions