I'm having trouble figuring out the loop in the average function. User enters sequence and if the number of numbers in the sequence is greater than 0, output avg of the numbers and repeat for another sequence. If the sequence has no numbers, exit program.
I understand that I'm telling the average function to return 0 when sum = 0 and that's why it exits after the 1st sequence (I think).
Any suggestions as to how to avoid that? Pseudocode if possible!
#include<stdio.h>
#include<stdlib.h>
double average();
int main ()
{
while( average() )
{
}
}//end main
double average()
{
double n, sum = 0;
int count = 0;
printf ( "Enter sequence: " );
while( scanf( "%lf", &n ) )
{
sum += n;
count++;
}
if( sum > 0 )
{
printf( "average is %.2f\n", sum/(double)count );
return 1;
}
else
return 0;
}
}
Here is my output:
Enter sequence: 3 4 5 x
average: 4.00
Enter sequence: Press any key to continue . . .
#include <stdio.h>
#include <stdlib.h>
int average(void);
int main(void)
{
while (average())
;
return 0;
}
int average(void)
{
double n, sum = 0;
int count = 0;
printf("Enter sequence: ");
while (scanf( "%lf", &n ) == 1)
{
sum += n;
count++;
}
int c;
while ((c = getchar()) != EOF && c != '\n')
;
if (sum > 0)
{
printf("average is %.2f\n", sum / count);
return 1;
}
else
return 0;
}
This reads anything on the line up to the newline after a conversion fails, thus setting you up for reading the next sequence. The loop test for scanf() is improved; it will exit on EOF, too. The cast in the division was unnecessary; the compiler has to convert count to double because sum is a double, even without you telling it to do so explicitly. The return type of average() is not a double; it is a boolean, which is classically spelled int. In C99 or later (which the code assumes you have; if you don't, you're stuck on Windows and need to move int c; to the top of the function), then you could #include <stdbool.h> and use a return type of bool and replace return 1; by return true; and replace return 0; by return false;.
I think you can initially get input for the variable named count asking for the user to enter the total no of numbers in sequence,and then get those values in sequence.
And if the count is 0,then exit the program.. else continue finding average.
This is because in your case, you have to enter a non numeric char each time to end the sequence.
Well I ended up with this and its working perfectly:
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
double average();
int main () {
while( average() ) {}
}//end main
double average() {
double n, sum = 0;
int count = 0;
printf ( "Enter sequence: " );
getchar();
while( scanf( "%lf", &n ) ){
sum += n;
count++;
}//end while
if( n > 0 ){
printf( " average: %.2f\n", sum/(double)count );
return 1;
}//end if
else
return 0;
}//end function
Related
I'm trying to learn some C, but it's a pain.
I have this task: 'Write a C program to determine the minmum and maximum of a sequence of integer numbers on input, terminged by the string "done".' Very simple task, just like the input:
5
2
9
done
However the output is wrong, and I can't figure it out. I would very much appreciate some help. Thx!
The code:
#include <stdio.h>
#include <string.h>
int main() {
char line[1000];
int val, min = 10, max = -1;
while ( 1 ) {
scanf("%d", &val);
if (val < min) min = val;
if (val > max) max = val;
scanf("%4s", line);
if (strcmp("done", line) == 0) break;
}
printf("Maximum %d\n", max);
printf("Minimum %d", min);
}
Both of the environments I tested the code in will output Max 9, Min 5.
Can someone explain what is going on?
According to the while loop
while ( 1 ) {
scanf("%d", &val);
if (val < min) min = val;
if (val > max) max = val;
scanf("%4s", line);
if (strcmp("done", line) == 0) break;
}
you have to enter a string after each input of a number.
So the second number 2 is considered as an input of a string.
Also integer numbers can be negative less than -1 or positive greater than 10. So this declaration
int val, min = 10, max = -1;
does not make sense.
Instead you can read all numbers in a character array and then to use for example the function atoi to convert the entered string to a number.
For example a simple program can look like
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main( void )
{
char line[16];
int min = 0, max = 0;
int empty = 1;
while ( scanf( "%15s", line ) == 1 && strcmp( line, "done" ) != 0 )
{
int val = atoi( line );
if ( empty )
{
min = val;
max = val;
empty = 0;
}
else if ( max < val )
{
max = val;
}
else if ( val < min )
{
min = val;
}
}
if ( empty )
{
puts( "The sequence of numbers is empty." );
}
else
{
printf( "Maximum %d\n", max );
printf( "Minimum %d\n", min );
}
}
You will need to enter the string "done" only once to break the loop. In all other cases you will need to enter only integer numbers.
I am working on a problem where I need to input a line of numbers with one or more whitespaces in between and add the numbers. But I am having a problem with ignoring the whitespaces.
I have tried using scanf(" ") and scanf("%*c").
What is the most efficient way to do so?
Thanks.
If the number of input integers in an entered string is unknown then you can use the approach shown in the demonstrative program.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
enum { N = 100 };
char line[N];
while ( fgets( line, N , stdin ) != NULL && line[0] != '\n' && line[0] != '\0' )
{
long long int sum = 0;
const char *s = line;
char *p = line;
do
{
s = p;
sum += strtol( s, &p, 10 );
} while ( s != p );
printf( "sum = %lld\n", sum );
}
return 0;
}
If to enter string
1 2 3 4 5
then the output will be
sum = 15
To read integers, use the format string %d, like this:
#include <stdio.h>
int main(void)
{
int sum, i, n;
sum = 0;
n = scanf("%d", &i);
while (n == 1) {
sum += i;
n = scanf("%d", &i);
}
printf("%d\n", sum);
return 0;
}
If you want to read real numbers, use the format string %lf (which stands for long float) and adjust the code above accordingly.
The way to do it in C++ would be
double a;
double b;
double c;
std::cin >> a >> b >> c;
I am not sure if you can do something very similar in C, please tell me if that was helpful.
The function reads coefficients for the polynomial from standard input and stores them in the given array. The capacity parameter tells the function how much room the coeff[] array has for coefficients. The function tries to read all the coefficients it can until it reaches the end-of-file and returns the number of coefficients it actually reads. If the input polynomial is bad (e.g., with too many coefficients or with input that doesn't parse as a floating point number), this function will print "Invalid polynomial" and exit the program with a status of 101.
The input file is like this:
0.0 6.0
25.00 -47.50 25.17 -5.00 0.33
The first two numbers is the range of the plot and the second line represents the coefficients of the polynomial.
This is the code I have so far:
/**
*/
// Include our own header first
#include "poly.h"
// Then, anything else we need in the implementation file.
#include <stdlib.h>
#include <stdio.h>
/** Exit status if the input polynomail is bad. */
#define INVALID_POLYNOMAIL_STATUS 101
int readPoly( int capacity, double coeff[] )
{
double variable = 0.0;
int ch;
int count = 0;
while ( ( ch = getchar() ) != EOF ) {
for(int i = 0; i < capacity; i++) {
if(scanf("%lf", &variable) != 1) {
fprintf(stderr, "Invalid input");
exit(101);
}
else {
coeff[i] = variable;
count++;
}
}
}
return count;
}
getchar may read the beginning of a value, this is not correct like that
A simple way is to stop on any error (EOF or bad value) :
int readPoly( int capacity, double coeff[] )
{
int i;
for(i = 0; i < capacity; i++) {
if (scanf("%lf", &coeff[i]) != 1)
break;
}
return i;
}
An other way is to bypass by hand the spaces to be able to indicate an error :
int readPoly( int capacity, double coeff[] )
{
int i;
for (i = 0; i < capacity; i++) {
for (;;) {
int c;
if ((c = getchar()) == EOF)
return i;
if (!isspace(c)) {
ungetc(c, stdin);
break;
}
if (scanf("%lf", &coeff[i]) != 1) {
fprintf(stderr, "Invalid input");
exit(101);
}
}
return i;
}
Note count is redundant with i, just i is enough, and you can also directly scanf into the array
#define maximum 100
#include <math.h>
#include <stdio.h>
int main () {
float sum, mean, variance, difference;
float sumforvariance, standarddev;
sumforvariance=0;
sum=0;
mean=0;
variance=0;
difference=0;
standarddev=0;
int a, count, b, c;
float insertnum[maximum]
for (a=0; a<maximum; a++) {
scanf("%f",&insertnum[a]);
count ++;
if (insertnum[a]==35.00) {
if (count==1) {
printf ("no data\n");
return 0;
}
break;
}
}
for (b=0; b<count; b++) {
sum+=insertnum[b];
}
mean=sum/count;
for (c=0; c<count; c++) {
difference=insertnum[c]-mean;
sumforvariance=sumforvariance+pow(difference,2);
}
variance=variance/count;
standarddev=sqrt(variance);
printf("mean: %f",mean);
printf("standdev: %f",standarddev);
Hi so I have a simple question. I am trying to calculate a standard deviation and mean for a set of numbers like this
./a.out 12 20 30 etc #
The # is to terminate inputing more numbers. As you can see in the first for loop, I am trying to input the numbers from standard output into an array of floats. The problem is when I enter 35, I do not want to terminate inputting more numbers because its not equal to #. How am I able to enter 35 and continue to enter more numbers until I enter # since they both contain the same numerical value. #=35 and 35=35.
Read you user input in as a string. Sniff for the terminating condition, then convert from string to float. Using the helper function, strtof which is available from #include <stdlib.h>
#define maximum 100
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
int main() {
float sum, mean, variance, difference;
float sumforvariance, standarddev;
sumforvariance = 0;
sum = 0;
mean = 0;
variance = 0;
difference = 0;
standarddev = 0;
int a, count=0, b, c;
float insertnum[maximum];
for (a = 0; a < maximum; a++) {
char userinput[101] = {0};
userinput[0] = '\0';
scanf("%100s", userinput);
if (userinput[0] == '#')
{
break;
}
insertnum[count] = strtof(userinput, nullptr);
count++;
}
return 0;
}
Also, you forgot to initialize count. And your code was inserting the # read into the array as well. So I fixed that for you.
Aside - I'll never forget the day my computer science professor passionately screamed to the class about the dangers of "reading numbers" from input. Users type characters with the keyboard not numbers. Hence, "validating input" became engrained with me to this day. You might want to consider just letting your loop break whenever the user types anything not a number. A modified version of the loop as follows:
for (a = 0; a < maximum; a++) {
char userinput[101] = {0};
userinput[0] = '\0';
scanf("%100s", userinput);
char* endptr = NULL;
float f = strtof(userinput, &endptr);
if (userinput == endptr)
{
// whatever was typed was not a float
break;
}
insertnum[count] = f;
count++;
}
Check the return value of scanf -- when it successfully converts a float it will return 1 (or more generally, however many conversions in the format string succeeded). So when the input is #, it will return 0 (nothing converted) and leave the # on in the input stream. You can then check the next character to make sure its a #. So you end up with a loop like:
for (a=0; a<maximum && scanf("%f",&insertnum[a]) == 1; a++) {
++count;
}
or even
for (count=0; count < maximum && scanf("%f",&insertnum[count]) == 1; ++count);
if (count == maximum) {
// read the limit -- may be more data
} else {
if (getchar() == '#') {
// got the expected terminator
} else {
// something else caused a problem
I am trying to print out each integer on a new line, given integers separated by whitespace from a user input. It stops printing after a specific number, lets say 84. For example
The user input is
20 -4 84 8
How could i use a while loop to print these out as
20
-4
84
i know about scanf("%d %d %d %d", a, b, c, d), However the input size would be unknown, such that there could be only 3 numbers or 7 numbers. So far i have:
#include <stdio.h>
int main(void)
{
int i = 0;
int x = 0;
scanf("%d", &x);
while (x != 84) {
print("%d\n", x[i]);
i++;
}
}
Push the scanf into the while condition. Something like
while (scanf("%d", &x) != EOF && x != 84)
print("%d\n", x);
The basic concept should be of two-steps:
Read the number
Check and decide whether to print /continue.
A psuedo-code would look like
while ((ret =scanf(x)) && ret != EOF ){
if (x == VAL) break;
printf(x);
}
You have a few errors:
the array num does not exist;
the scanf must be repeated inside the while loop.
The corrected code is thw following:
#include <stdio.h>
int main(void)
{
int x;
while( 1 ){
scanf( "%d", &x );
print( "%d\n", x );
if( x==84 ) break;
}
}
You need to put scanf() inside the while loop in order to update every new input. No need for arrays if you want to print only the inputted values because you can print it after new input. Better do it with do-while loop.
#include <stdio.h>
int main(void)
{
int i = 0;
int x = 0;
do {
if ( scanf("%d", &x) < 0 )
break;
printf("%d\n", x);
} while (x != 84);
}