Why does it tell me its an Armstrong number when I enter strings? - c

This is the code for finding an Armstrong number of 3 digits. But when i enter strings or any other special character it categorizes it as an armstrong number while it should be other way around.
#include <stdio.h>
#include <stdlib.h>
int main() {
int a, original, rev, rem;
printf("Enter the number : \n");
scanf("%d", & a);
original = a;
rev = 0;
while (a != 0) {
rem = a % 10;
rev = rev + (rem * rem * rem);
a /= 10;
}
if (rev == original) {
printf("Its an Armstrong number\n");
} else {
printf("Its not an Armstrong number \n");
}
}

You need to check the result of scanf - it will return the number of items successfully converted and assigned.
if ( scanf( "%d", &a ) != 1 )
// bad input
else
// check if a is an armstrong #
An input like nnnniii is not a valid integer, so the read fails and a is not updated.
While the initial value of auto variables is indeterminate, it's possible that a has an initial value of 0, so your test passes by accident.

It is Undefined Behaviour as you use not initialized variable a.
You should have checked for the incorrect input:
if(scanf("%d", &a) != 1)
{
printf("Invalid input\n");
return 1;
}

#include <stdio.h>
#include <stdlib.h>
int main() {
int a, original, rev, rem;
printf("Enter the number : \n");
if(scanf("%d", &a) != 1)
{
printf("This is not number\n");
return 1;
}
original = a;
rev = 0;
while (a != 0) {
rem = a % 10;
rev = rev + (rem * rem * rem);
a /= 10;
}
if (rev == original) {
printf("Its an Armstrong number\n");
} else {
printf("Its not an Armstrong number \n");
}
}
When you get value, you need to check it is number or not.

Related

Using while loop statement create a program that enter 5 numbers and determine if it is a prime or not and then display the prime numbers only

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.

Not sure why my program keeps prompting error when I try to close it?

#include <stdio.h>
#include <stdlib.h>
int add_even(int);
int add_odd(int);
int main() {
int num, result_odd, result_even, even_count, odd_count;
char name;
printf("What is your name?\n");
scanf("%s", &name);
while (num != 0) {
printf("Enter a number:\n");
scanf("%d", &num);
if (num % 2 == 1) {
printf ("odd\n");
odd_count++;
} else
if (num == 0) {
printf("%s, the numbers you have entered are broken down as follows:\n",
name);
result_even = add_even(num);
printf("You entered %d even numbers with a total value of %d\n",
even_count, result_even);
result_odd = add_odd(num);
printf("You entered %d odd numbers with a total value of %d\n",
odd_count, result_odd);
} else {
printf("even\n");
even_count++;
}
}
return 0;
}
int add_even(int num) {
static int sum = 0;
if (num % 2 != 0) {
return 0;
}
sum += add_even(num);
return sum;
}
int add_odd(int num) {
static int sum = 0;
if (num % 2 == 0) {
return 0;
}
sum += add_odd(num);
return sum;
}
Can anyone give me some insight as to what I did wrong exactly?
The point of the code is to get inputs from the user until they decide to stop by inputting 0. Separating the evens from the odd. Tell them how many even/odd they put and the total of all the even/odd numbers.
I understand how to separate the evens from the odds. I think my issue is with my function.
There are multiple problems in your code:
scanf() causes undefined behavior when trying to store a string into a single character. Pass an array and specify a maximum length.
you should check the return value of scanf(): if scanf() fails to convert the input according to the specification, the values are unmodified, thus uninitialized, and undefined behavior ensues. In your case, if 2 or more words are typed at the prompt for the name, scanf("%d",...) fails because non numeric input is pending, no further characters are read from stdin and num is not set.
num is uninitialized in the first while (num != 0), causing undefined behavior.
functions add_even() and add_odd() are only called for num == 0, never summing anything.
functions add_even() and add_odd() should always return the sum and add the value of the argument num is it has the correct parity. They currently cause undefined behavior by calling themselves recursively indefinitely.
odd_count and even_count are uninitialized, so the counts would be indeterminate and reading their invokes undefined behavior.
In spite of all the sources of undefined behavior mentioned above, the reason your program keeps prompting without expecting an answer if probably that you type more than one word for the name. Only a single word is converted for %s, leaving the rest as input for numbers, which repeatedly fails in the loop. These failures go unnoticed as you do not verify the return value of scanf().
Here is a corrected version:
#include <stdio.h>
#include <stdlib.h>
int add_even(int);
int add_odd(int);
int main(void) {
int num, result_odd, result_even, even_count = 0, odd_count = 0;
char name[100];
printf("What is your name? ");
if (scanf("%99[^\n]", name) != 1)
return 1;
for (;;) {
printf("Enter a number: ");
if (scanf("%d", &num) != 1 || num == 0)
break;
if (num % 2 == 1) {
printf("odd\n");
odd_count++;
add_odd(num);
} else {
printf("even\n");
even_count++;
add_even(num);
}
printf("%s, the numbers you have entered are broken down as follows:\n", name);
result_even = add_even(0);
printf("You entered %d even numbers with a total value of %d\n",
even_count, result_even);
result_odd = add_odd(0);
printf("You entered %d odd numbers with a total value of %d\n",
odd_count, result_odd);
}
return 0;
}
int add_even(int num) {
static int sum = 0;
if (num % 2 == 0) {
sum += num;
}
return sum;
}
int add_odd(int num) {
static int sum = 0;
if (num % 2 != 0) {
sum += num;
}
return sum;
}
You declared:
char name; // One single letter, such as 'A', or 'M'
printf("What is your name?\n"); // Please enter a whole bunch of letters!
scanf("%s", &name); // Not enough space to store the response!
What you really want is more like
char name[31]; // Up to 30 letters, and an End-of-String marker
printf("What is your name?\n"); // Please enter a whole bunch of letters!
scanf("%s", name); // name is the location to put all those letters
// (but not more than 30!)

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.

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;
}
}

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

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;
}

Resources