C program that prints out highest number - c

So I need to make a C program that prints out the highest number inputed.
If the input is empty it shouldn't print anything.
If the input includes anything else than a number it shouldn't print anything.
example:
If the input is 1 2 3 2 1 it should print out 3.
If the input is 1 2 a 2 1 it shouldn't print out anything.
This is what i got so far:
#include <stdio.h>
int main()
{
int res, max, x;
res = scanf("%d", &max);
if (res == 1) {
while(res != EOF)
{
res = scanf("%d", &x);
if (x > max)
{
max=x;
}
}
printf("%d", max);
} else {
return 0;
}
return 0;
}
So my question is, how do i make it print out nothing if it contains a letter like in the example above.
Thank in advance!

#include <stdio.h>
int main()
{
int max, x;
if (scanf("%d", &max) != 1)
{
// If there is no number, exit the program.
return 0;
}
while ( scanf("%d", &x) == 1 )
{
if (x > max)
{
max=x;
}
}
// If we came to the EOF, we didn't see any bad input.
if ( feof(stdin) )
{
printf("Max: %d\n", max);
}
return 0;
}

#include <stdio.h>
int main(void){
int res, max, x;
if(1 != scanf("%d", &max))
return -1;
while(EOF != (res = scanf("%d", &x))){
if(res != 1)
return -1;
if (x > max){
max = x;
}
}
printf("%d\n", max);
return 0;
}

If the input is a number, scanf will return 1
#include <stdio.h>
int main()
{
int max, x;
int result;
if (scanf("%d", &max) != 1)
return -1;
x = max;
do {
result = scanf("%d[^\n]", &x);
if ((result != EOF) && (result != 1))
return 0;
else if ((result != EOF) && (x > max))
max = x;
} while (result != EOF);
printf("\n\nMaximum Input : %d\n", max);
return 0;
}
the previous program will stop when there is invalid input, i.e. something that is not a number.

Related

Returning -1 to a user defined function is resulting to termination of program with exit code 0

In this factorial program when entered any non numeric or negative number then the program should ask to renter the value but in the output the program is getting terminated.
Is it because I am returning -1 in display() function? If so then is it compulsory to return a variable (or other function) value to a function if the function is meant to return a value?
#include <stdio.h>
int display();
void fact_fun(int num_fact);
int main() {
int num = 0;
char next;
next = display();
if (next == -1) { //WHEN ANY CHARACTER OR NEGATIVE NUMBER IS ENTERED IT WILL ASK TO RENTER
printf("\nOnly positive number is allowed");
display();
}
while (next >= 0) { //WHEN NEGATIVE NUMBER IS ENTERED IT WILL END THE LOOP
num = next;
fact_fun(num);
next = display();
}
return 0;
}
int display() {
char inp[10] = { 0 };
int input;
int index = 0;
printf("\nEnter number to find factorial or press ENTER KEY to exit: ");
while (((input = getchar()) != EOF) & (index < 10)) {
if ((input >= '0') && (input <= '9')) {
inp[index++] = input;
} else
if (input == '\n')
break;
else
return -1;
}
input = atoi(inp);
return input;
}
void fact_fun(int num_fact) {
int fact = 1;
if (num_fact == 0) {
printf("\nFactorial of %d is 1", num_fact);
return;
} else {
for (int i = 1; i <= num_fact; i++) {
fact = fact * i;
}
printf("\nFactorial of %d is %d", num_fact, fact);
}
}
Also when I press ENTER KEY I am getting output as below:
Factorial of %d is 1
Enter number to find factorial or press ENTER KEY to exit:
And when enter \n the program gets terminate. As per my understanding it should treat the Enter key and \n same. If not then what is the difference and how should I check for ENTER KEY value?
User input is line buffered by default. It is much simpler for your purpose to read input one line at a time from the user, parse it to assert input validity and compute the factorial only for valid input.
Note also that you can simplify the computation as the special case for 0 is redundant with the code for the general case. You should also check for potential arithmetic overflow as the computation may easily exceed the range of type int and produce undefined behavior.
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
int display();
void fact_fun(int num_fact);
int main() {
int num;
while ((num = display()) >= 0) {
fact_fun(num);
}
return 0;
}
int display() {
char buf[256];
char *p;
long value;
for (;;) {
printf("Enter number to find factorial or press ENTER KEY to exit: ");
if (fgets(buf, sizeof buf, stdin) == NULL || *buf == '\n')
return -1;
errno = 0;
value = strtol(buf, &p, 0);
if (p == buf) {
printf("Invalid input: not a number\n");
} else {
if (value < 0) {
printf("Invalid input: negative values not allowed\n");
} else
if (errno != 0 || value > INT_MAX) {
printf("Invalid input: value too large for type int\n");
} else {
return (int)value;
}
}
}
void fact_fun(int num_fact) {
int fact = 1;
for (int i = 1; i <= num_fact; i++) {
if (fact > INT_MAX / i) {
printf("Invalid input: arithmetic overflow\n");
return;
}
fact = fact * i;
}
printf("Factorial of %d is %d\n", num_fact, fact);
}
Here is your code with some corrections. There were two problems.
The first is that you have to finish reading the input until you reach an end of the line or EOF.
The second is that you need two error codes, one for invalid input, and a second for no-input. (Your comment in the code indicates that you want to exit on no-input).
#include <stdio.h>
#include <stdlib.h>
int display();
void fact_fun(int num_fact);
int main() {
//int num = 0;
char next;
while( 1 ) {
next = display();
if (next == -2) {
break;
}
if (next == -1) {
//WHEN ANY CHARACTER OR NEGATIVE NUMBER IS ENTERED IT WILL ASK TO RENTER
printf("\nOnly positive number is allowed");
}
else {
fact_fun(next);
}
}
return 0;
}
int display() {
char inp[10] = { 0 };
char c;
int input = 0;
int index = 0;
printf("\nEnter number to find factorial or press ENTER KEY to exit: ");
while ( ((c = getchar()) != EOF) && (c != '\n') && (index < 10)) {
if ( (c >= '0') && (c <= '9') ) {
inp[index++] = c;
} else {
input = -1;
break;
}
}
// Finish inputting the line
while ( (c != EOF) && (c != '\n') ) {
c = getchar();
}
if ( !input ) {
if ( index )
input = atoi(inp);
else
input = -2;
}
return input;
}
void fact_fun(int num_fact) {
int fact = 1;
if (num_fact == 0) {
printf("\nFactorial of %d is 1", num_fact);
return;
} else {
for (int i = 1; i <= num_fact; i++) {
fact = fact * i;
}
printf("\nFactorial of %d is %d", num_fact, fact);
}
}
In this factorial program when entered any non numeric or negative number then the program should ask to renter the value
The while loop in your main() function only loops to ask for new numbers until input() returns a negative number. You have even documented it:
while(next>=0) //WHEN NEGATIVE NUMBER IS ENTERED IT WILL END THE LOOP
...
When you do return -1 in input(), the function returns -1, which will set next to -1 and end the loop. The program then exists shortly after that.
There is nothing inherently wrong with using a return statement to return -1 from a user defined function. It's quite normal and common to do things like that.

*pointer_variable != '\0' is not working for the check of unsuccessful conversion in strtol() function

The program was not working for input 5r i.e in input when first character is number and remaining next character is any alphabet or negative number. For example when I am giving input as 5r in the output I am getting factorial of 5.
So I tried putting check for strtol unsuccessful conversion :-
if (p == buf || *p != '\0'){ printf("\nInvalid input: not a number\n");}
but I am getting output as Invalid input: not a number for all the input.
I found many similar questions in Stack Overflow. However, they don't resolve my issue. I am not understanding what is wrong with this simple check? How can I successfully detect errors from strtol?
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <errno.h>
int display();
void fact_fun(int num_fact);
int main()
{
int num;
while ((num = display()) >= 0)
{
fact_fun(num);
}
return 0;
}
int display()
{
char buf[256];
char *p;
long value;
for (;;)
{
printf("\nEnter number to find factorial or press ENTER KEY to exit: ");
if (fgets(buf, sizeof buf, stdin) == NULL || *buf == '\n')
return -1;
errno = 0;
value = strtol(buf, &p, 0);
if (p == buf || *p != '\0')
{
printf("\nInvalid input: not a number\n");
}
else
{
if (value < 0)
{
printf("\nInvalid input: negative values not allowed\n");
}
else if (errno != 0 || value > INT_MAX)
{
printf("\nInvalid input: value too large for type int\n");
}
else
{
return (int)value;
}
}
}
}
void fact_fun(int num_fact)
{
int fact = 1;
for (int i = 1; i <= num_fact; i++)
{
if (fact > INT_MAX / i)
{
printf("\nInvalid input: arithmetic overflow\n");
return;
}
fact = fact * i;
}
printf("\nFactorial of %d is %d\n", num_fact, fact);
}
The string you get from fgets contains '\n' as last char because you hit enter, so replace it with '\0'. That is a common error we C coders sometimes make.
Edit:
So I have tested it myself, and you're right, the reason is that strtoI does not mess with line terminator, so now it works fine with the following check:
*p != '\n'
The full working code is this:
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <errno.h>
int display();
void fact_fun(int num_fact);
int main()
{
int num;
while ((num = display()) >= 0)
{
fact_fun(num);
}
return 0;
}
int display()
{
char buf[256];
char *p;
long value;
for (;;)
{
printf("\nEnter number to find factorial or press ENTER KEY to exit: ");
if (fgets(buf, sizeof buf, stdin) == NULL || *buf == '\n')
return -1;
errno = 0;
value = strtol(buf, &p, 0);
if (p == buf || *p != '\n')
{
printf("\nInvalid input: not a number\n");
}
else
{
if (value < 0)
{
printf("\nInvalid input: negative values not allowed\n");
}
else if (errno != 0 || value > INT_MAX)
{
printf("\nInvalid input: value too large for type int\n");
}
else
{
return (int)value;
}
}
}
}
void fact_fun(int num_fact)
{
int fact = 1;
for (int i = 1; i <= num_fact; i++)
{
if (fact > INT_MAX / i)
{
printf("\nInvalid input: arithmetic overflow\n");
return;
}
fact = fact * i;
}
printf("\nFactorial of %d is %d\n", num_fact, fact);
}

I can not determine if it is a prime number

The below program correctly outputs the divisors of the input numbers, but it does not correctly report whether the inputs are prime. For example, when the input is 13, it does not print "The number you entered is a prime number." What's wrong with it?
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
int num;
bool isPrime = true;
printf("Enter a number: ");
while (scanf("%d", &num) == 1)
{
for (int i = 2; i * i <= num; ++i)
{
if (num % i == 0)
{
if (i * i != num)
{
printf("%d ve %d, divides %d\n", i, num / i, num);
}
else
{
printf("%d divides %d.\n", i, num);
}
isPrime = false;
}
}
}
if (isPrime)
{
printf("The number you entered is a prime number.");
}
return 0;
}
the reason is that scanf is in a while loop if there's a valid input but you are checking & printing if it's prime outside of the loop... if you expect this program just get one input and validate it once, then you just need to change that while to if:
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
int num;
bool isPrime = true;
printf("Enter a number: ");
if (scanf("%d", &num) == 1)
{
for (int i = 2; i * i <= num; ++i)
{
if (num % i == 0)
{
if (i * i != num)
{
printf("%d ve %d, divides %d\n", i, num / i, num);
}
else
{
printf("%d divides %d.\n", i, num);
}
isPrime = false;
}
}
}
if (isPrime)
{
printf("The number you entered is a prime number.");
}
return 0;
}
If you expect this program goes in a loop to keep on getting input and validating if it's prime or not, this should do the job:
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
int num;
bool isPrime = true;
while (1)
{
isPrime=true;
printf("Enter a number: ");
if (scanf("%d", &num) == 1)
{
for (int i = 2; i * i <= num; ++i)
{
if (num % i == 0)
{
if (i * i != num)
{
printf("%d ve %d, divides %d\n", i, num / i, num);
}
else
{
printf("%d divides %d.\n", i, num);
}
isPrime = false;
}
}
}
if (isPrime)
{
printf("The number you entered is a prime number.\n");
}
}
return 0;
}
You have missed 2 things !
You should have printed inside the while loop !
In addition to that you didn't change the status of isPrime=true; !
Hope this answers your question !
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
int num;
bool isPrime = true;
while (scanf("%d", &num) == 1)
{
for (int i = 2; i * i <= num; ++i)
{
if (num % i == 0)
{
if (i * i != num)
{
printf("%d ve %d, divides %d\n", i, num / i, num);
}
else
{
printf("%d divides %d.\n", i, num);
}
isPrime = false;
}
}
if (isPrime)
{
printf("The number you entered is a prime number.\n");
}
isPrime=true;
}
return 0;
}
When you entered a prime number, your while loop doesn't break. Try it:
#include <stdio.h>
#include <stdbool.h>
int main(void) {
int num;
bool isPrime = true, finishIt = false;
printf("Enter a number: ");
while (1) {
while (1) {
if (scanf("%d", &num) != 1)
continue;
if (num == 0) {
finishIt = true;
break;
}
int i;
for (i = 2; i * i <= num; ++i) {
if (num % i == 0) {
if (i * i != num) {
printf("%d ve %d, divides %d\n", i, num / i, num);
} else {
printf("%d divides %d.\n", i, num);
}
isPrime = false;
}
}
if (i * i >= num)
break;
}
if (isPrime) {
printf("The number you entered is a prime number.");
}
isPrime = true;
if (finishIt)
break;
}
return 0;
}

Printing biggest even number with multiple scanf

I would like to get an output of the biggest even number. but when I input 1 2 3 (3 calls to scanf) the output is 4.
#include <stdio.h>
#include <stdlib.h>
int main() {
int ary[100];
int x, y = 0;
int amount;
scanf("%d", &amount);
fflush(stdin);
for (x = 1; x <= amount; x++) {
scanf("%d", &ary[x]);
if (ary[x] % 2 == 0) {
if (ary[0] < ary[x]) {
ary[0] = ary[x];
}
}
}
printf("%d", ary[0]);
getchar();
return 0;
}
Before the loop initialize ary[0] for example the following way (otherwise uninitialized value of ary[0] is used in the program)
ary[0] = 1;
then substitute these if statements
if(ary[x]%2==0)
{
if(ary[0]<ary[x])
for
if( ary[x]%2==0 && ( x == 1 || ary[0]<ary[x] ) )
And at last write
if ( ary[0] != 1 ) printf("%d",ary[0]);
Take into account that this call
fflush(stdin);
has undefined behavior and should be removed.
In fact there is no need to declare an array. Without the array the program can look like
#include <stdio.h>
int main( void )
{
unsigned int n;
int max_even = 1;
printf("How many numbers are you going to enter: ");
scanf("%u", &n);
int x;
for (unsigned int i = 0; i < n && scanf( "%d", &x ) == 1; i++)
{
if ((x % 2) == 0 && (max_even == 1 || max_even < x))
{
max_even = x;
}
}
if (max_even != 1)
{
printf("maximum entered even number is %d\n", max_even);
}
else
{
puts("None even number was enetered");
}
return 0;
}
Its output might look like
How many numbers are you going to enter: 10
0 1 2 3 4 5 6 7 8 9
maximum entered even number is 8
#include <stdio.h>
#include <stdlib.h>
int main() {
int ary[100];
int ary[0 = 0;
int x, y = 0;
int amount;
scanf("%d", &amount);
fflush(stdin);
for (x = 1; x <= amount; x++) {
scanf("%d", &ary[x]);
if (ary[x] % 2 == 0) {
if (ary[0] < ary[x]) {
ary[0] = ary[x];
}
}
}
printf("%d", ary[0]);
getchar();
return 0;
}
Your code does not work because ary[0] is not yet initialized the first time you compare its value to the value read, furthermore it might not be even for the other comparisons.
You should use an indicator telling you whether an even value has been seen.
Here is a solution:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int has_even = 0, max_even = 0, value, amount, x;
if (scanf("%d", &amount) != 1)
return 1;
for (x = 0; x < amount; x++) {
if (scanf("%d", &value) != 1)
break;
if (!has_even || value > max) {
max_even = value;
has_even = 1;
}
}
if (has_even)
printf("%d\n", max_even);
else
printf("no even value\n");
getchar();
return 0;
}

C - Reading and 2d int array with rows terminated by 0 until end of input

I am trying to write a program in C that will read max of 50 rows of 5 integers and print them after reaching end of stdin.
#include <stdio.h>
#include <stdlib.h>
int readInput(int numbers[][5], int row) {
int x, i = 0;
while (1) {
if (scanf("%d", &x) !=1 ) exit (1);
if (x == 0) {
return 1;
}
if (feof(stdin)) {
return 0;
}
numbers[row][i] = x;
i++;
}
}
int main ( void ) {
int numbers[50][5];
int row = 0; int val;
int i,j;
while (1) {
val = readInput(numbers, row);
if ( val == 1){
row++;
continue;
} else if (val == 0) {
break;
}
}
for (i = 0; i < row+1; i++) {
for ( j = 0; j < 5; j++) {
printf("%d ", numbers[i][j]);
}printf("\n");
}
}
Problem is that no matter how I try to tell the program that the endless loop in main needs to end, it never does. I really need to understand the concept of reaching end of input, that is why I dont want to simply write a loopthat finishes after a certain amount of iterations, I want to learn how to break the loop after reaching end of stdin.
Your current code doesn't capture the EOF that scanf may return.
You can try something like:
int readInput(int numbers[][5], int row) {
int x, i = 0;
while (1) {
int t = scanf("%d", &x); // Save return value
if (t == EOF) return 0; // Check for EOF
if (t !=1 ) exit (1);
if (x == 0) {
return 1;
}
numbers[row][i] = x;
i++;
}
}
CTRL+D (or CTRL+Z for windows) can be used to indicate EOF

Resources