Printing biggest even number with multiple scanf - c

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

Related

Define a function to check if its a perfect square in C

I tried to write a code to check if a number is a perfect square, but I'm not able to call the function I defined. Where is my mistake?
#include <stdio.h>
#include <math.h>
int isPerfectSquare(int number) {
int i;
for (i = 0; i <= number; i++) {
if (number == (i * i)) {
printf("Success");
break;
} else {
continue;
}
}
printf("Fail");
}
int main() {
int n;
printf("Enter a number: ");
scanf("%d", n);
isPerfectSquare(n);
return 0;
}
I don't get any answer ("Success" or "Fail").
You must pass the address of n instead of its value in scanf("%d", n);:
scanf("%d", &n);
Note however that your function will print both Success and Fail for perfect squares because you should return from the function instead of just breaking from the loop upon success.
Here is a modified version:
#include <stdio.h>
void isPerfectSquare(int number) {
int i;
for (i = 0; i <= number; i++) {
if (number == (i * i)) {
printf("Success\n");
return;
}
}
printf("Fail\n");
}
int main() {
int n;
printf("Enter a number: ");
if (scanf("%d", &n) == 1) {
isPerfectSquare(n);
}
return 0;
}
Note also that your method is quite slow and may have undefined behavior (and produce false positives) if i becomes so large that i * i exceeds the range of type int. You should instead use a faster method to figure an approximation of the square root of n and check if the result is exact.
It is also better for functions such as isPerfectSquare() to return a boolean value instead of printing some message, and let the caller print the message. Here is a modified version using the Babylonian method, also known as Heron's method.
#include <stdio.h>
int isPerfectSquare(int number) {
int s1 = 2;
if (number < 0)
return 0;
// use the Babylonian method with 10 iterations
for (int i = 0; i < 10; i++) {
s2 = (s1 + number / s1) / 2;
if (s1 == s2)
break;
s1 = s2;
}
return s1 * s1 == number;
}
int main() {
int n;
printf("Enter a number: ");
if (scanf("%d", &n) == 1) {
if (isPerfectSquare(n)) {
printf("Success\n");
} else {
printf("Fail\n");
}
}
return 0;
}

how to extract the even number from user input, and combine them as a new number in C program

test case:
input: 1234
output: 24
input: 2468
output: 2468
input: 6
output: 6
I have this code:
#include <stdio.h>
#include <math.h>
int main() {
int num;
printf("Enter a number: \n");
scanf("%d", &num);
int numberLength = floor(log10(abs(num))) + 1;
int inputNumberArray[numberLength];
int evenNumberCount = 0;
int even[10];//new even no. array
int i = 0;
do {
inputNumberArray[i] = num % 10;
num = num / 10;
i++;
} while (num != 0);
i = 0;
while (i < numberLength) {
if (inputNumberArray[i] % 2 == 0) {
evenNumberCount ++;
even[i] = inputNumberArray[i];
}
i++;
}
printf("array count %d\n", evenNumberCount);
i = 0;
for (i = 0; i < 8; i++) {
printf(" %d", even[i]);//print even array
}
i = 0;
int result = 0;
for (i = 0; i < 10; i++) {
if (evenNumberCount == 1) {
if (even[i] != 0) {
result = even[i];
} else {
break;
}
} else {
if (even[i] != 0) {
result = result + even[i] * pow(10, i);
} else
break;
}
}
printf("\nresult is %d", result);
/*
int a = 0;
a = pow(10, 2);
printf("\na is %d", a);
*/
}
when I enter number 1234, the result/outcome is 4, instead of 24.
but when I test the rest of test case, it is fine.
the wrong code I think is this: result = result + even[i] * pow(10, i);
Can you help on this?
Thanks in advance.
why do you have to read as number?
Simplest algorithm would be
Read as text
Validate
loop through and confirm if divisible by 2 and print live
next thing, have you try to debug?
debug would let you know what are doing wrong. Finally the issue is with indexing.
evenNumberCount ++; /// this is technically in the wrong place.
even[i]=inputNumberArray[i]; /// This is incorrect.
As the user Popeye suggested, an easier approach to accomplish this would be to just read in the entire input from the user as a string. With this approach, you can iterate through each letter in the char array and use the isdigit() method to see if the character is a digit or not. You can then easily check if that number is even or not.
Here is a quick source code I wrote up to show this approach in action:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char input[100] = { '\0' };
char outputNum[100] = { '\0' };
// Get input from user
printf("Enter a number: ");
scanf_s("%s", input, sizeof(input));
// Find the prime numbers
int outputNumIndex = 0;
for (int i = 0; i < strlen(input); i++)
{
if (isdigit(input[i]))
{
if (input[i] % 2 == 0)
{
outputNum[outputNumIndex++] = input[i];
}
}
}
if (outputNum[0] == '\0')
{
outputNum[0] = '0';
}
// Print the result
printf("Result is %s", outputNum);
return 0;
}
I figured out the solution, which is easier to understand.
#include <stdio.h>
#include <math.h>
#define INIT_VALUE 999
int extEvenDigits1(int num);
void extEvenDigits2(int num, int *result);
int main()
{
int number, result = INIT_VALUE;
printf("Enter a number: \n");
scanf("%d", &number);
printf("extEvenDigits1(): %d\n", extEvenDigits1(number));
extEvenDigits2(number, &result);
printf("extEvenDigits2(): %d\n", result);
return 0;
}
int extEvenDigits1(int num)
{
int result = -1;
int count = 0;
while (num > 1) {
int digit = num % 10;
if (digit % 2 == 0) {
result = result == -1 ? digit : result + digit * pow(10, count);
count++;
}
num = num / 10;
}
return result;
}
}
You are overcomplicating things, I'm afraid.
You could read the number as a string and easily process every character producing another string to be printed.
If you are required to deal with a numeric type, there is a simpler solution:
#include <stdio.h>
int main(void)
{
// Keep asking for numbers until scanf fails.
for (;;)
{
printf("Enter a number:\n");
// Using a bigger type, we can store numbers with more digits.
long long int number;
// Always check the value returned by scanf.
int ret = scanf("%lld", &number);
if (ret != 1)
break;
long long int result = 0;
// Use a multiple of ten as the "position" of the resulting digit.
long long int power = 1;
// The number is "consumed" while the result is formed.
while (number)
{
// Check the last digit of what remains of the original number
if (number % 2 == 0)
{
// Put that digit in the correct position of the result
result += (number % 10) * power;
// No need to call pow()
power *= 10;
}
// Remove the last digit.
number /= 10;
}
printf("result is %lld\n\n", result);
}
}

how do I add up the sum of the digits of a number except for digits that repeat themselves in c?

I have an assignment and I need to add up the digits of it and ignore the once that repeat themselves
for example 234111 -> 2 + 3 + 4 + 1 -> 10
I tried doing this:
#include
int main(void)
{
int i = 0;
int num = 0;
int sum = 0;
printf("Please enter a number\n");
scanf("%d", &num);
while(num > 0){
sum += num%10;
num /= 10;
}
printf("%d", sum);
return 0;
}
what I did just adds up the digits, it doesn't ignore that ones that get repeated
What do i need to add to the code?
You can keep an array of 'flags' for which digits have been used already:
#include <stdio.h>
int main(void)
{
// int i = 0; // You don't actually use this in the code!
int num = 0;
int sum = 0;
int used[10] = { 0, }; // Set all "used" flags to zero
printf("Please enter a number\n");
scanf("%d", &num);
while (num > 0)
{
int digit = num % 10; // Get the digit
if (!used[digit]) sum += digit; // Only add if not used already
used[digit] = 1; // Now we have used it!
num /= 10;
}
printf("%d", sum);
return 0;
}
Feel free to ask for further clarification and/or explanation.
Just read each character and record if you've already seen it:
#include <stdio.h>
#include <ctype.h>
int
main(void)
{
int seen[10] = {0};
int sum = 0;
int c;
while( ( c = getchar()) != EOF ) {
int v = c - '0';
if( isspace(c)) {
continue;
}
if( v < 0 || v > 9 ) {
fprintf(stderr, "Invalid input\n");
return 1;
}
if( ! seen[v]++ )
sum += v;
}
printf("%d\n", sum);
return 0;
}

Program loops infinitely if a non-integer is entered, and does not accept plural digit inputs

Assigned task is to ask for # of values, and then at the end output the minimum, maximum, and average values and at this point I've run out of bug fixes
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int main()
{
int ErrorDetection = 1;
char valCounter;
int valnumber;
int Incrementer;
int StoredValue;
int MinimumValue = 100;
int MaximumValue = 0;
float Average;
int AddToStored;
int Sum = 0;
printf("MIN, MAX, and MEAN CALCULATOR\n\n");
while (ErrorDetection != 0)
{
printf("How many values are to be entered?\n");
scanf("%s", &valCounter);
if (valCounter > '0' && valCounter < '9') {
ErrorDetection = 0;
}
else {
ErrorDetection = 1;
printf("INPUT ERROR!\n");
}
valCounter = valCounter - 47;
}
for (Incrementer = 1; Incrementer < valCounter; Incrementer++)
{
ErrorDetection = 1;
while (ErrorDetection != 0) {
printf("Value %d: ", Incrementer);
scanf(" %d", &StoredValue);
if (StoredValue > 0 && StoredValue < 9) {
ErrorDetection = 0;
}
else {
ErrorDetection = 1;
printf("INPUT ERROR!\n");
continue;
}
}
if (StoredValue > MaximumValue) {
MaximumValue = StoredValue;
}
if (StoredValue <= MinimumValue) {
MinimumValue = StoredValue;
}
Sum = Sum + StoredValue;
}
valCounter = valCounter - 1;
Average = (float)Sum / (float)valCounter;
printf(
"Minimum value is %d, maximum value is %d, and average value is %g.\n",
MinimumValue, MaximumValue, Average
);
}
If you input a 2 digit number things begin to breakdown, but at the same time I don't know how to go through with errorchecking if I allow multiple digit answers, as I make use of ASCII conversions to check if an input is a number or not.
You have undefined behavior here.
char valCounter;
scanf("%s", &valCounter);
You have declared valCounter as char type but trying to read string type.
Hence change the scanf to.
scanf("%c", &valCounter);
I would suggest you declare valCounter as int
int valCounter;
scanf("%d", &valCounter);
in that case your if will become.
if ((valCounter > 0) && (valCounter < 9))
and you don't need
valCounter = valCounter - 47; //remove
Also your for loop should start from 0 instead of 1
for(Incrementer = 1 ; Incrementer < valCounter; Incrementer++)
should be
for(Incrementer = 0 ; Incrementer < valCounter; Incrementer++)
Your problem is here.
char valCounter;
scanf("%s", &valCounter);
You're telling scanf to read a string, but you're passing it the address of a character. You should be asking for an integer, and giving it the address of an integer.
int valCounter;
scanf("%d", &valCounter)
There's more information here, including reasons why scanf might not be the best idea:
How to scanf only integer?

Need 10 outputs per line

I am having trouble refining some code. My code takes a number "n" and calculates that many prime numbers. I need to display 10 primes per line of output data. Any tips would be appreciated.
#include <stdio.h>
int main()
{
int n, i = 3, count, c;
printf("How many primes would you like?");
scanf("%d",&n);
if ( n >= 1 )
{
printf("2");
}
for ( count = 2 ; count <= n ; )
{
for ( c = 2 ; c <= i - 1 ; c++ )
{
if ( i%c == 0 )
break;
}
if ( c == i )
{
printf(" %d",i);
count++;
}
i++;
}
return 0;
}
Just try
printf(" %5d", i);
/* ^ to help align the numbers
and
if ((count + 1) % 10 == 0)
fputc(stdout, '\n');
fix for the first time when you already print 2.
bool is_prime(int anyNum) //takes an integer array returns, is_prime
{
bool is_prime = true;
for (int c = 2; c <= anyNum - 1; c++)
{
if (anyNum % c == 0)
{
//printf("%d is not prime\r\n" , anyNum);
is_prime = false;
}
}
return is_prime;
}
int main()
{
int num_primes;
printf("How many primes would you like: ");
std::cin >> num_primes;
printf("\r\nScanned Primes Are---\r\n");
int foundPrimes = 0;
int x = 0;
for (; x <= num_primes; x++)
{
bool gotLuckyFindingPrime = is_prime( x );
if (gotLuckyFindingPrime)
{
if (foundPrimes % 10 == 0)
{
printf("\r\n");
}
printf(" %d", x);
foundPrimes = (foundPrimes + 1) % 10;
}
}
}
Does handle ten digit showing on cmd too, you can experiment with formatting

Resources