Writing a program to find the largest in a series of numbers. - c

I am very new to C. I am using A modern Approach to C programming by King 2nd Edition.
I am stuck on chapter 6. Question 1: Write a program that finds the largest in a series of numbers entered by the user. The program must prompt the user to enter the numbers one by one. When the user enters 0 or a negative number, the program must display the largest non negative number entered.
So far I have:
#include <stdio.h>
int main(void)
{
float a, max, b;
for (a == max; a != 0; a++) {
printf("Enter number:");
scanf("%f", &a);
}
printf("Largest non negative number: %f", max);
return 0;
}
I do not understand the last part of the question, which is how to see which non-negative number is the greatest at the end of user input of the loop.
max = a > a ???
Thanks for your help!

So you want to update max if a is greater than it each iteration thru the loop, like so:
#include <stdio.h>
int main(void)
{
float max = 0, a;
do{
printf("Enter number:");
/* the space in front of the %f causes scanf to skip
* any whitespace. We check the return value to see
* whether something was *actually* read before we
* continue.
*/
if(scanf(" %f", &a) == 1) {
if(a > max){
max = a;
}
}
/* We could have combined the two if's above like this */
/* if((scanf(" %f", &a) == 1) && (a > max)) {
* max = a;
* }
*/
}
while(a > 0);
printf("Largest non negative number: %f", max);
return 0;
}
Then you simply print max at the end.
A do while loop is a better choice here because it needs to run at least once.

#include<stdio.h>
int main()
{
float enter_num,proc=0;
for(;;)
{
printf("Enter the number:");
scanf("%f",&enter_num);
if(enter_num == 0)
{
break;
}
if(enter_num < 0)
{
proc>enter_num;
proc=enter_num;
}
if(proc < enter_num)
{
proc = enter_num;
}
}
printf("Largest number from the above is:%.1f",proc);
return 0;
}

Related

C programming: Trouble summing numbers entered by the user with for loop

So, I have to write a program to ask the user for an integer, and then that integer will determine how many more entries the user gets before adding all the numbers that were entered. So, if the first entered integer is "5", then the user can enter 5 more integers. Those 5 integers are then added together at the end and displayed. I have written a program with for loops, but for some reason, it is only adding first 4 integers and not the 5th one. Here is the code:
int main() { //declare main function
int c=0,n,i; //declare integers
int sum=0;
printf("\nEnter an integer: "); //ask user for input and create a label
scanf("%d",&n);
if (n>=0) { //use if statement
for (i=0;i<n;i++) //use for loop inside if statement to account for negative integers
{
sum+=c;
printf("Enter an integer: ");
scanf("%d",&c);
}
}
else {
printf("Wrong number. You can only enter positive integers!");
}
printf("The sum of the %d numbers entered is: %d",i,sum);
return 0;
}
Just change the position of
sum+=c;
to after the scanf it should work.
It is good to split the program. use functions. Not everything in the main function.
int getInteger(void)
{
char str[100];
int number;
while(!fgets(str, 100, stdin) || sscanf(str, "%d", &number) != 1)
{
printf("Wrong input. Try again:") ;
}
return number;
}
int main()
{
int nsamples;
long long sum = 0;
printf("Enter number of samples:");
while((nsamples = getInteger()) <= 0)
{
printf("Try again, entered number must be >= 0\n");
}
printf("Enter numbers:\n");
for(int i = 1; i <= nsamples; i++)
{
printf("Sample no %d:", i);
sum += getInteger();
}
printf("The sim is: %lld\n", sum);
}

Programs counting even and odd numbers

I'm self-studying C and I'm trying to make 2 programs for exercise:
the first one takes a number and check if it is even or odd;
This is what I came up with for the first one:
#include <stdio.h>
int main(){
int n;
printf("Enter a number that you want to check: ");
scanf("%d",&n);
if((n%2)==0)
printf("%d is even.",n);
else
printf("%d is odd.",n);
return 0;
}
the second one should take n numbers as input and count the number of even numbers, odd numbers, and zeros among the numbers that were entered. The output should be the number of even numbers, odd numbers, and zeros.
I would like to ask how to implement the loop in this case: how can I set an EOF value if every integer is acceptable (and so I cannot, say, put 0 to end)? Can you show me how to efficiently build this short code?
#include <stdio.h>
int main(void) {
int n, nEven=0, nOdd=0, nZero=0;
for (;;) {
printf("\nEnter a number that you want to check: ");
//Pressing any non-numeric character will break;
if (scanf("%d", &n) != 1) break;
if (n == 0) {
nZero++;
}
else {
if (n % 2) {
nEven++;
}
else {
nOdd++;
}
}
}
printf("There were %d even, %d odd, and %d zero values.", nEven, nOdd, nZero);
return 0;
}
Check the return value of scanf()
1, 1 field was filled (n).
0, 0 fields filled, likely somehtlig like "abc" was entered for a number.
EOF, End-of-file encountered (or rarely IO error).
#include <stdio.h>
int main(void) {
int n;
for (;;) {
printf("Enter a number that you want to check: ");
if (scanf("%d",&n) != 1) break;
if((n%2)==0)
printf("%d is even.",n);
else
printf("%d is odd.",n);
}
return 0;
}
Or read the count of numbers to subsequently read:
int main(void) {
int n;
printf("Enter the count of numbers that you want to check: ");
if (scanf("%d",&n) != 1) Handle_Error();
while (n > 0) {
n--;
printf("Enter a number that you want to check: ");
int i;
if (scanf("%d",&i) != 1) break;
if((i%2)==0) {
if (i == 0) printf("%d is zero.\n",i);
else printf("%d is even and not 0.\n",i);
}
else
printf("%d is odd.\n",i);
}
return 0;
}
hey look at this
#include<stdio.h>
#include<conio.h>
void main()
{
int nodd,neven,num,digit ;
clrscr();
printf("Count number of odd and even digits in a given integer number ");
scanf("%d",&num);
nodd = neven =0; /* count of odd and even digits */
while (num> 0)
{
digit = num % 10; /* separate LS digit from number */
if (digit % 2 == 1)
nodd++;
else neven++;
num /= 10; /* remove LS digit from num */
}
printf("Odd digits : %d Even digits: %d\n", nodd, neven);
getch();
}
You can do something like this:
#include <stdio.h>
int main(){
int n,evenN=0,oddN=0,zeros=0;
char key;
do{
clrscr();
printf("Enter a number that you want to check: ");
scanf("%d",&n);
if(n==0){
printf("%d is zero.",n);
zeros++;
}
else if((n%2)==0){
printf("%d is even.",n);
evenN++;
}
else{
printf("%d is odd.",n);
oddN++;
}
puts("Press ENTER to enter another number. ESC to exit");
do{
key = getch();
}while(key!=13 || key!=27) //13 is the ascii code fore enter key, and 27 is for escape key
}while(key!=27)
clrscr();
printf("Total even numbers: %d",evenN);
printf("Total odd numbers: %d",oddN);
printf("Total odd numbers: %d",zeros);
return 0;
}
This program ask for a number, evaluate the number and then ask to continue for another number or exit.

Finding biggest and smallest numbers using user input

Well it is a problem about finding the biggest and smallest number in a group of numbers, but we do not know how many numbers the user wants-
So far this is what i have done:
#include <stdio.h>
#include <conio.h>
int main()
{
int num;
int i;
int maxi=0;
int minim=0;
int cont = 0;
printf ("\nQuantity of numbers?: ");
scanf ("%d", &num);
while (num>0)
{
printf ("\nEnter number:");
scanf ("%d", &i);
if (num>i)
minim=i++;
else
if (i>num)
max=i++;
cont++;
}
printf ("\nBiggest number is es: %d", maxi);
printf ("\nSmallest number is: %d", minim);
getch();
return 0;
}
I did my program to ask how many numbers the user will want to put and i made the program to read them, BUT when it reads the biggest or/and smallest numbers it will sometimes changes biggest with small and it will not read negative numbers.
How do i do to make my program better?
You're comparing against the wrong values.
do
{
printf("Enter a number.\n");
scanf("%i", &input);
if min > input
min = input
if max < input
max = input
} while (input > 0);
#include <stdio.h>
#include <conio.h>
#include <limits.h>
int main(){
int num;
int i;
int maxi=0;
int minim=INT_MAX;
int cont = 0;
printf ("\nQuantity of numbers?: ");
scanf("%d", &num);
if(num > 0){
while (num>0){
printf ("\nEnter number:");
if(scanf("%d", &i) == 1 && !(i<0)){
if(minim > i)
minim = i;
if (maxi < i)
maxi = i;
++cont;
--num;
} else {
//fprintf(stderr, "redo input!\n")
;
}
scanf("%*[^\n]%*c");
}
printf ("\nBiggest number is : %d", maxi);
printf ("\nSmallest number is : %d\n", minim);
}
getch();
return 0;
}
You should initialize mini to the largest possible int, i.e. INT_MAX and maxi to the smallest possible int, i.e., INT_MIN. This way, even if the first number is negative, it will be considered for maxi, and if the first number is positive it will still be considered for mini. The constants INT_MAX and INT_MIN are included in <climits> or <limits.h>.
Also, you are comparing the current entered number with num, which is the counter of numbers entered by user, not one of the values he wants to compare. A better modified code would be :
#include<limits.h>
#include<stdio.h>
int main()
{
int num;
int maxi=INT_MIN; //initialize max value
int mini=INT_MAX; //initialize min value
int temp;
scanf("%d", &num); //take in number of numbers
while(num--) //loop "num" times, num decrements once each iteration of loop
{
scanf("%d", &temp); //Take in new number
if(temp>maxi) //see if it is new maximum
maxi=temp; //set to new maximum
if(temp<mini) //see if new minimum
mini=temp; //set to new minimum
}
printf("\nMaxi is:\t%d\nMini is:\t%d\n", maxi, mini); //print answer
return 0;
}

C while loop infinite loop EOF not working

I am having problem with EOF in my while loop. It does not seem to simply end when EOF is entered but rather does this...
How can I fix it and have the while loop stop and move on. Thanks.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <limits.h>
void findLargestandSmallest(int integer, int* largest, int* smallest, int* average, int count);
int main(void)
{
//Local Declaration
int integer;
int largest;
int smallest;
int average;
int count; // number count
//Starting statemnets
smallest = INT_MAX;
largest = INT_MIN;
count = 0;
// Starting prompts
printf("\nHello this program will take in intagers and print");
printf("\nout the largest, smallest and avarage of integers");
printf("\nenterd int.");
printf("\nPlease enter in a integer ");
while (scanf("%d", &integer) != EOF)
{
if (integer != EOF)
{
count++;
findLargestandSmallest(integer, &largest, &smallest, &average, count);
}
else
{
printf("\n \n");
}
}
printf("\nThe largest number entered is %d and the smallest", largest);
printf("\nwas %d and the average of all the numbers is %d\n", smallest, average);
return 0;
}
void findLargestandSmallest(int integer, int *largest, int *smallest, int *average, int count)
{
int x; // just a holder variable
// finds average
x = 0;
x += integer;
*average = (x / count);
// Finds smallest and largest
if (integer <= *smallest)
{
*smallest = integer;
}
if (integer >= *largest)
{
*largest = integer;
}
printf("Enter another integer or <EOF> to quit ");
return;
}
[1]: http://i.stack.imgur.com/P0307.png
UPDATE: I found out what I was doing wrong. Its simple. In the while loop while(scanf("%d", &integer) != EOF) don't set it like that but like this (scanf("%d", &integer)) EOF is understood. To simply call it in DOS use use "Ctrl+Z" on your last input. i.e "number^Z" is how it will look after using "Ctrl+Z" Also here is the better and working code for this problem for anyone else that runs into this.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <limits.h>
void findLargestandSmallest(int integer, int* largest, int* smallest);
int main(void)
{
//Local Declaration
int integer;
int largest;
int smallest;
int average;
int sum;
int count;
//Starting statemnets
smallest = INT_MAX;
largest = INT_MIN;
count = 0;
sum = 0;
// Starting prompts
printf("\n--------------------------------------------------------");
printf("\n- Hello, this program will take in intagers and print -");
printf("\n- out the largest, smallest, and avarage of the -");
printf("\n- integers enterd. -");
printf("\n- NOTE: To quit: use \"Ctrl+Z\" on the last integer -");
printf("\n- you enter i.e \"number^z\" -");
printf("\n--------------------------------------------------------\n");
printf("\nEnter integers\n");
// Finds largest and smallest number
while (scanf("%d", &integer))
{
sum += integer;
count++;
findLargestandSmallest(integer, &largest, &smallest);
}
// Finds average
count--;
average = (sum / count);
// End prompts
printf("\n--------------------------------------------------------");
printf("\nThe largest number entered was %d, the smallest", largest);
printf("\nwas %d, and the average of all the numbers is %d.", smallest, average);
printf("\n--------------------------------------------------------");
printf("\nGoodbye\n");
return 0;
}
void findLargestandSmallest(int integer, int *largest, int *smallest)
{
if (integer < *smallest)
{
*smallest = integer;
}
if (integer > *largest)
{
*largest = integer;
}
return;
}
scanf returns the number of elements successfully converted. If it can't convert any, it returns 0. EOF is only returned for end-of-file (on Unix a Control-D).
So you should modify your program to save the return value from scanf and then test it for 0 and EOF separately.
It is also pointless to compare the integer variable with EOF, since all you can possibly know about EOF is that it is a negative integer. Read the scanf manual page and understand what it does and what it returns when and where. That'll solve the puzzle. :-)
Alright, some more hints. Can you make sense of this?
for (;;) {
int successfully_converted = scanf("%d", &integer);
if (successfully_converted == EOF) {
/* Do something when the user is tired of typing. */
puts("Thank you for an enjoyable game.\n");
exit(0);
} else if (successfully_converted == 0) {
puts("This didn't look like an integer\n");
exit(1);
} else {
/* Do something with integer. */
}
}
You are not comparing the integer value with EOF
. You are comparing the scanf result with EOF..
Here as you enter 1 value each time, scanf result will be 1.
So evrrytime the while loop condition fails and infinite loop is generated.
Also if you EOF then what character would you enter to end the loop???
So EOF should not be used.
So I would suggest you to use do while loop
do
{
scanf("%d",&integer);
....
...
printf("enter 1 to continue");
scanf("%d",&check);
}while(check == 1);
Test the result of scanf() against EOF, 0, and 1.
int cnt;
while ((cnt = scanf("%d", &integer)) == 1) {
count++;
findLargestandSmallest(integer, &largest, &smallest, &average, count);
}
if (cnt == 0) {
printf("Something other than an integer was entered.\n");
}
else if (cnt == EOF) {
printf("EOF or I/O Error occurred.\n");
}
// Add the following for debug if desired
else {
printf("Should _never get here!\n");
}
...
UPDATE: I found out what I was doing wrong. Its simple. In the while loop while(scanf("%d", &integer) != EOF) don't set it like that but like this (scanf("%d", &integer)) EOF is understood. To simply call it in DOS use use "Ctrl+Z" on your last input. i.e "number^Z" is how it will look after using "Ctrl+Z" Also here is the better and working code for this problem for anyone else that runs into this.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <limits.h>
void findLargestandSmallest(int integer, int* largest, int* smallest);
int main(void)
{
//Local Declaration
int integer;
int largest;
int smallest;
int average;
int sum;
int count;
//Starting statemnets
smallest = INT_MAX;
largest = INT_MIN;
count = 0;
sum = 0;
// Starting prompts
printf("\n--------------------------------------------------------");
printf("\n- Hello, this program will take in intagers and print -");
printf("\n- out the largest, smallest, and avarage of the -");
printf("\n- integers enterd. -");
printf("\n- NOTE: To quit: use \"Ctrl+Z\" on the last integer -");
printf("\n- you enter i.e \"number^z\" -");
printf("\n--------------------------------------------------------\n");
printf("\nEnter integers\n");
// Finds largest and smallest number
while (scanf("%d", &integer))
{
sum += integer;
count++;
findLargestandSmallest(integer, &largest, &smallest);
}
// Finds average
count--;
average = (sum / count);
// End prompts
printf("\n--------------------------------------------------------");
printf("\nThe largest number entered was %d, the smallest", largest);
printf("\nwas %d, and the average of all the numbers is %d.", smallest, average);
printf("\n--------------------------------------------------------");
printf("\nGoodbye\n");
return 0;
}
void findLargestandSmallest(int integer, int *largest, int *smallest)
{
if (integer < *smallest)
{
*smallest = integer;
}
if (integer > *largest)
{
*largest = integer;
}
return;
}

How to create C program to determine lagest number by entered value?

I've created a program to determine largest number, but my lecturer says it isn't perfect, can anybody make it perfect?
#include <stdio.h>
int main () {
double a,b=0,n, i;
printf("limit of n input: ");
scanf ("%lf",&n);
for (i=1;i<=n;i++) {
scanf("%lf",&a);
if (a>b) b=a;
}
printf("%.2lf", b);
return 0;
}
If by "not perfect" she meant "doesn't properly handle negative numbers or an empty set", then you'd want to
Treat n<1 as a special case (why should 0 be the largest of an empty set?)
Read the first number outside of the loop, so you're not making as assumption as to the smallest possible number
I would do it that way, sorry for the mass of text. I think it is coming from the typical Objective-C style programming with long words:
#include <stdio.h>
int clean_stdin() {
while (getchar()!='\n');
return 1;
}
int main(int argc, char *argv[]) {
char c;
signed int count = 0; // number of numbers to scan
unsigned int fireErrorMessage = 0;
do {
if (fireErrorMessage == 1) {
printf("You entered not a positive natural number. Please enter a number >0 Examples: 1 22 4012\n"); // output for the user
}
if (fireErrorMessage == 0) {
fireErrorMessage = 1;
}
printf("How many integers do you want to insert (Inser a number >0)? ");
} while (((scanf("%d%c", &count, &c) != 2 || c != '\n') && clean_stdin()) || count < 1);
signed int indexOfNumber; // for index, declared outside because of output at the end
signed int highestNumberIndex;
double highestNumber; // saving the highest value in a helper variable
fireErrorMessage = 0;
for (indexOfNumber = 1; indexOfNumber <= count; indexOfNumber++) {
double scannedNumber;
do {
if (fireErrorMessage == 1) {
printf("You entered not a number. Please enter a number. Examples: 3.0 -1 14\n"); // output for the user
}
if (fireErrorMessage == 0) {
fireErrorMessage = 1;
}
printf("Input number %d: ", indexOfNumber); // output for the user
} while (((scanf("%lf%c", &scannedNumber, &c) != 2 || c != '\n') && clean_stdin()));
fireErrorMessage = 0;
if (indexOfNumber == 1 || scannedNumber > highestNumber) {
highestNumberIndex = indexOfNumber;
highestNumber = scannedNumber;
}
}
printf("Highest input number on index %d, the value is about %.2lf\n", highestNumberIndex, highestNumber);
return 0;
}
Output
How many integers do you want to insert (Inser a number >0)? aa5
You entered not a positive natural number. Please enter a number >0 Examples: 1 22 4012
How many integers do you want to insert (Inser a number >0)? -3
You entered not a positive natural number. Please enter a number >0 Examples: 1 22 4012
How many integers do you want to insert (Inser a number >0)? 3
Input number 1: aa
You entered not a number. Please enter a number. Examples: 3.0 -1 14
Input number 1: -50.0001
Input number 2: 51a
You entered not a number. Please enter a number. Examples: 3.0 -1 14
Input number 2: -1.00
Input number 3: -0.1
Highest input number on index 3, the value is about -0.10
This code caters for negative, not a number input for the loop index as well as negative and not a number inputs inside the loop. Thanks
#include <stdio.h>
#include <math.h>
int main () {
int n, i;
double a,b=0;
printf("limit of n input: ");
scanf ("%lf",&n);
if(n < 0){
printf("value of n cannot be negative");
return 0;
}
else if (n == 0)
return 0;
else if (isnan(n))
return 0;
else{
for (i=1;i<=n;i++)
{
scanf("%lf",&a);
if(!isnan(a) && a > 0)
{
if (a>b) b=a;
}
}
printf("%.2lf", b);
return 0;
}
}

Resources