int32_t number;
uint32_t x = 1;
puts("What number do you want to count: ?");
{
scanf("%i", &number);
printf("You typed%i.\n", number);
while(x < number) {
printf("%i and then \n", x);
x++;
}
if (x > 100 || x < 1)
printf("error");
}
I want to print all the numbers till the user inputs numbers. But if the inputted number is less than 1 or greater than 100 then it should say error and ask the user to input the number again but it does not do that. for instance if the number is 455 it should say error and prompt the user to input the number again.The program above only prints error after printing all the numbers even number grater or less than 100 and 1 respectively.
#include <stdint.h>
#include <stdio.h>
int main(void)
{
int32_t number;
while (puts("What number do you want to count? "), // prompt the user
scanf("%i", &number) != 1 // reading an int failed
|| number < 1 || 100 < number) // number not in range
{
fputs("Error!\n\n", stderr); // print an error message
int ch;
while ((ch = getchar()) != EOF && ch != '\n'); // remove garbage left in stdin
}
printf("You typed %d.\n", number);
for(int32_t i = 0; i < number; ++i)
printf("%i and then\n", i);
}
Related
In my code I can only input 1 number. How to enter 4 additional numbers and determine if it's a prime or not and then display only the prime numbers.
#include<stdio.h>
int main()
{
int n, c = 2, f = 1;
printf("Enter a number:");
scanf("%d", &n);
while(c < n)
{
if(n%c == 0)
{
f = 0;
break;
}
c++;
}
if(f) printf("%d is prime number\n\n", n);
return 0;
}
Here is my output, using the code above:
Please enter a number:2
...Program finished with exit code 0
Press ENTER to exit console.
And here is the expected output:
Please enter a number:1
Please enter a number:2
2 is a prime number.
Please enter a number:3
3 is a prime number.
Please enter a number:4
Please enter a number:5
5 is a prime number.
Let's say you want to check 5 numbers whether they are prime or not.
The approach you followed, you just have to do the same for rest of the numbers.
To do that, you can run an additional loop. For example,
int inputSize = 5;
while(inputSize--)
{
printf("Enter a number:");
scanf("%d", &n);
// now check if the number is prime or not
}
Note: Don't forget to initialize the values in proper place.
Sample code:
#include<stdio.h>
int main()
{
int inputSize = 5;
while(inputSize--)
{
int n, c = 2, f = 1;
printf("Enter a number:");
scanf("%d", &n);
while(c < n)
{
if(n%c == 0)
{
f = 0;
break;
}
c++;
}
if(f) printf("%d is prime number\n\n", n);
}
return 0;
}
Check out the following resource to know more about primality of a number
https://www.studytonight.com/c-programs/c-program-to-check-whether-a-number-is-prime-or-not
It is evident that you need a loop with 5 iterations to enter 5 numbers.
As the notion of prime numbers is defined for natural numbers then you need to use an unsigned integer type to store entered numbers.
And your code is incorrect because for numbers 0 and 1 it outputs that they are prime numbers.
The program can look the following way.
#include <stdio.h>
int main( void )
{
const size_t N = 5;
for ( size_t i = 0; i < N; i++ )
{
printf( "Please enter a number: " );
unsigned int n = 0;
if ( scanf( "%u", &n ) == 1 )
{
int prime = n % 2 == 0 ? n == 2 : n != 1;
for ( unsigned int i = 3; prime && i <= n / i; i += 2 )
{
prime = n % i != 0;
}
if ( prime ) printf( "%u is a prime number.\n", n );
}
else
{
while ( getchar() != '\n' );
}
putchar( '\n' );
}
}
The program output might look like
Please enter a number: 1
Please enter a number: 2
2 is a prime number.
Please enter a number: 3
3 is a prime number.
Please enter a number: 4
Please enter a number: 5
5 is a prime number.
You need to read the numbers in a loop. You also need to check that the input really is a number. The function scanf returns the number of successfully read values. Try this:
#include <stdio.h>
int main(void)
{
int c, ch, i, m, n;
i = 0;
while (i < 5) {
printf("Enter a number: ");
m = scanf("%d", &n);
if (m == 1) {
c = 2;
while ((c < n) && (n % c != 0)) {
c++;
}
if (c == n) {
printf("%d is prime number\n", n);
}
putchar('\n');
i++;
} else {
fprintf(stderr, "Not a number\n\n");
do { ch = getchar(); } while (ch != '\n');
}
}
return 0;
}
If the input is invalid we can give the user another chance. In this case we first need to read past the unread characters which represents the invalid input.
Also note that the algorithm can be improved by only inspecting numbers up to the square root of n.
I'm pretty new to programming so answer to this one might be simple but i can't find it. When checking wether the variable is over 1000 or under 1 the program works but whenever i input a letter the program just loops infinitely. Anyways here's the code and thanks for your help:
printf("Player 1 enter A number between 1 and 1000: ");
scanf("%d", &num);
while(num<1 || num>1000 || !isdigit(num)){
printf("please enter different number: ");
scanf("%d", &num);
}
scanf is a poor choice for reading input from the user.
You probably want this:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
// Get a number from the user
// number: pointer to the number
// return value: 1 if the user has typed a number
// 0 if the user ha not typed a number
int GetNumber(int *number)
{
char inputbuffer[20];
fgets(inputbuffer, sizeof inputbuffer, stdin); // read raw line from user
if (!isdigit(inputbuffer[0])) // if first char isn't a digit
return 0; // it's not a number, return 0
*number = strtol(inputbuffer, NULL, 10); // convert to number
return 1;
}
int main()
{
int num;
printf("Player 1 enter A number between 1 and 1000: ");
while (!GetNumber(&num) || num < 1 || num > 1000) {
printf("please enter different number: ");
}
printf("number = %d\n", num);
return 0;
}
Alternative version of GetNumber:
int GetNumber(int *number)
{
char inputbuffer[20];
fgets(inputbuffer, sizeof inputbuffer, stdin);
char *endptr;
*number = strtol(inputbuffer, &endptr, 10);
if (*endptr != '\n') // if user input ends with somethign else than
return 0; // \n it's not a number (e.g: "123a")
return 1;
}
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.
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;
}
}
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;
}