Hi, this program reads and integer, and checks whther it is even or odd. and als
ID: 3544265 • Letter: H
Question
Hi, this program reads and integer, and checks whther it is even or odd. and also adds up the even or odd ones using a print statement, please have a look it has a couple errors, once you fixed it, please explain in detail where the problem came from so I can understand it. thanks
#include <stdio.h>
int main(void)
{
/* declare the variables. */
int x;
void checkifEvenorOdd(int);
while (1)
{
printf(" Enter a positive integer ");
scanf("%d", &x);
if (x<=0)
{
break;
}
else
{
checkifEvenorOdd(x);
}
}
return 0;
}
int checkifEvenorOdd(int x)
{
if((x%2)==0) /* Checking whether remainder is 0 or not. if 0 then the enteed value is Even */
{
int countEven=0;
countEven++;
printf(" the number %d is even.",x);
printf(" the total number of even integers is %d ",countEven);
}
else /* Checking whether remainder is 0 or not. if not 0 then the enteed value is Odd */
{
int countOdd=0;
countOdd++;
printf(" the number %d is odd ",x);
printf(" the total number of odd integers is entered %d ",countOdd);
}
Explanation / Answer
#include <stdio.h>
void checkifEvenorOdd(int);
int main(void)
{
/* declare the variables. */
int x;
while (1)
{
printf(" Enter a positive integer ");
scanf("%d", &x);
if (x<=0)
{
break;
}
else
{
checkifEvenorOdd(x);
}
}
return 0;
}
void checkifEvenorOdd(int x)
{
if((x%2)==0) /* Checking whether remainder is 0 or not. if 0 then the enteed value is Even */
{
static int countEven=0;
countEven++;
printf(" the number %d is even.",x);
printf(" the total number of even integers is %d ",countEven);
}
else /* Checking whether remainder is 0 or not. if not 0 then the enteed value is Odd */
{
static int countOdd=0;
countOdd++;
printf(" the number %d is odd ",x);
printf(" the total number of odd integers is entered %d ",countOdd);
}
}
Explanation:
(1) The prototype definition of the function should reside top of the main function.
(2) Make the variables countEven and countOdd static such that they are allocated memory only once throught the program and redefinition doesn't change the variable value such that you can know the number of odd and even integers entered throught the program.
(3) Another error was, you wrongly wrote the return type of the new function as "int" instead of "void"
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.