Program will stop once five even numbers are placed in array - c

This is a program that gets numbers input. From the numbers given or inputted, store in an array those numbers only that are even. Input will stop/terminates once 5 even numbers are already stored in the array. So here's my code:
#include <stdio.h>
#include <conio.h>
int main()
{
int num[5];
int x, counter, even[5], numEven=0;
for(counter=0; counter<5; counter++){ //loop for getting the numbers from the user
printf("Enter number: ");
scanf("%d", &num[counter]);
if(num[counter]%2==0){ //storing the even numbers
even[numEven] = num[counter];
numEven++;
}
}
printf("\n\nEven numbers: "); //printing even numbers
for(counter=0; counter<numEven; counter++){
printf("%d, ", even[counter]);
}
getch();
return 0;
}
I have confusion in the part where will I stop the inputting when there's already 5 even numbers stored. Is there something missing? Or am I doing the wrong way? I hope I can get help and suggestions with the code. Thank you very much.

#include <stdio.h>
#include <conio.h>
int main()
{
int x, even[5], numEven = 0;
while (numEven < 5)
{
scanf("%d", &x);
if (x % 2 == 0)
{
even[numEven++] = x;
}
}
printf("\n\nEven numbers: "); //printing even numbers
for(x=0; x<numEven; x++)
{
printf("%d, ", even[x]);
}
getch();
return 0;
}
You keep readin inputs till numEven reaches 5. If the read input is an even number store it in the array and increment numEven.

Use a while loop if the number of times the program will ask the user for input is not fixed and dependent on the user's input.
while (numEven < 5) {
printf("Enter number: ");
scanf("%d", &num[counter]);
if (num[counter] % 2 == 0) {
even[numEven] = num[counter];
numEven++;
}
}

Related

Checking the positivity of elements entered by the user in an array

I have a program which asks user to enter elements that will be assigned into an array. But i want to check the entered number is whether positive or negative. If there is a negative number program should warn to user and asks user to enter positive numbers again. I wrote my code but it goes into a infinite loop.
How can make it correct?
here is my code:
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
int main()
{
int A[MAX] = {};
int n,jj;
printf("How many numbers do you want to enter?\n");
scanf("%d",&n);
for (jj=0; jj<n; jj++)
{
printf(" enter the %d. number\n", (jj+1));
scanf("%d",&A[jj]);
while(A[jj]<=0){
printf("Please enter only positive numbers");
}
}
return 0;
}
For starters this initialization using an empty braced list
int A[MAX] = {};
is incorrect in C. You have to write
int A[MAX] = { 0 };
It is evident that this loop
while(A[jj]<=0){
printf("Please enter only positive numbers");
}
is an infinite loop when A[jj] is not positive. So what you do is what you get.
Instead you could write for example
for (jj=0; jj<n; jj++)
{
printf(" enter the %d. number\n", (jj+1));
do
{
scanf("%d",&A[jj]);
if ( A[jj]<=0 )
{
printf("Please enter only positive numbers");
}
} while ( A[jj] <= 0 );
}
The cause of the infinite loop is due to the use of while(A[jj]<=0)
The problem can be solved in these 2 steps:
read user input into a temporary variable.
Assign the temporary variable to array element, only if the value is positive.
Here is the working code:
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
int main() {
int A[MAX] = {};
int n, jj, temp = 0;
printf("How many numbers do you want to enter?\n");
scanf("%d",&n);
for (jj = 0; jj < n; jj++) {
printf("Enter the # %d number : ", (jj+1));
scanf("%d",&temp);
if (temp < 0) {
printf("Negative number will not be accepted. Please try again\n");
--jj;
continue;
}
A[jj] = temp;
}
return 0;
}
Output:
How many numbers do you want to enter?
3
Enter the # 1 number : 1
Enter the # 2 number : -2
Negative number will not be accepted. Please try again
Enter the # 2 number : 2
Enter the # 3 number : 3

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.

Finding biggest and smallest numbers using user input

Well it is a problem about finding the biggest and smallest number in a group of numbers, but we do not know how many numbers the user wants-
So far this is what i have done:
#include <stdio.h>
#include <conio.h>
int main()
{
int num;
int i;
int maxi=0;
int minim=0;
int cont = 0;
printf ("\nQuantity of numbers?: ");
scanf ("%d", &num);
while (num>0)
{
printf ("\nEnter number:");
scanf ("%d", &i);
if (num>i)
minim=i++;
else
if (i>num)
max=i++;
cont++;
}
printf ("\nBiggest number is es: %d", maxi);
printf ("\nSmallest number is: %d", minim);
getch();
return 0;
}
I did my program to ask how many numbers the user will want to put and i made the program to read them, BUT when it reads the biggest or/and smallest numbers it will sometimes changes biggest with small and it will not read negative numbers.
How do i do to make my program better?
You're comparing against the wrong values.
do
{
printf("Enter a number.\n");
scanf("%i", &input);
if min > input
min = input
if max < input
max = input
} while (input > 0);
#include <stdio.h>
#include <conio.h>
#include <limits.h>
int main(){
int num;
int i;
int maxi=0;
int minim=INT_MAX;
int cont = 0;
printf ("\nQuantity of numbers?: ");
scanf("%d", &num);
if(num > 0){
while (num>0){
printf ("\nEnter number:");
if(scanf("%d", &i) == 1 && !(i<0)){
if(minim > i)
minim = i;
if (maxi < i)
maxi = i;
++cont;
--num;
} else {
//fprintf(stderr, "redo input!\n")
;
}
scanf("%*[^\n]%*c");
}
printf ("\nBiggest number is : %d", maxi);
printf ("\nSmallest number is : %d\n", minim);
}
getch();
return 0;
}
You should initialize mini to the largest possible int, i.e. INT_MAX and maxi to the smallest possible int, i.e., INT_MIN. This way, even if the first number is negative, it will be considered for maxi, and if the first number is positive it will still be considered for mini. The constants INT_MAX and INT_MIN are included in <climits> or <limits.h>.
Also, you are comparing the current entered number with num, which is the counter of numbers entered by user, not one of the values he wants to compare. A better modified code would be :
#include<limits.h>
#include<stdio.h>
int main()
{
int num;
int maxi=INT_MIN; //initialize max value
int mini=INT_MAX; //initialize min value
int temp;
scanf("%d", &num); //take in number of numbers
while(num--) //loop "num" times, num decrements once each iteration of loop
{
scanf("%d", &temp); //Take in new number
if(temp>maxi) //see if it is new maximum
maxi=temp; //set to new maximum
if(temp<mini) //see if new minimum
mini=temp; //set to new minimum
}
printf("\nMaxi is:\t%d\nMini is:\t%d\n", maxi, mini); //print answer
return 0;
}

Receive two inputs in C language

I want a program that can get two integers from user and put the sum of those inputs in a variable, after that checks that is sum more than 5 or not ? (I know I can do it with if , ... but I want to do it with while). I myself did it but it has some problems, would you mind saying what is the problem and how can I debug it ? Here is my code :
#include <stdio.h>
int main()
{
int ui1;
int ui2;
puts("Please enter two numbers:");
scanf("%2i", &ui1, &ui2);
int sum;
sum = ui1+ui2;
while(sum > 5) {
printf("Whats up !");
}
return 0;
}
This line is only scanning for 1 integer (%i with a 2 format, indicating only take 2 digits.):
scanf("%2i", &ui1, &ui2);
But it seems you expected to receive two integers.
This will leave the second argument, ui2, uninitialized.
(It should fill ui1 successfully, at least)
Try instead:
scanf("%i %i", &ui1, &ui2);
Try including the scanf statement into the loop, it will no longer be an infinite loop... (also need to dereference the integers, see EDIT)
#include <stdio.h>
int main()
{
int ui1;
int ui2;
puts("Please enter two numbers:\n");
//scanf("%2i", &ui1, &ui2);
int sum = 10;//(so that it will enter the loop at least once)
//sum = ui1+ui2;
while(sum > 4)
{
printf("enter number 1:\n");
scanf("%i", &ui1); //EDIT &
printf("enter number 2:\n");
scanf("%i", &ui2); //EDIT &
sum = ui1+ui2;
}
printf("result is: %d\n", sum);
getchar();//so you can see the result;
getchar();
return 0;
}
Actually while is a loop stmt not a conditional checker
if you want conditional checker use if...else series , switch etc
Note: in your code loop starts if (sum > 5) and never ends (infinate "Whats up !")
sum = ui1+ui2;
while(sum > 5) ///loop starts if (sum > 5) and never ends (infinate "Whats up !")
{
printf("Whats up !"); // (infinate "Whats up !")
}
if(sum > 5)
{
//greater stuff
}
else
{
//lower stuff
}
See Tutorial Here conditionals Stmts
You need to reset the "sum", because otherwise the while loop will be true FOREVER.
Second the input scanf is simply wrong.
Here the correct code
#include <stdio.h>
int main()
{
int ui1;
int ui2;
puts("Please enter two numbers:");
scanf("%d %d", &ui1, &ui2);
int sum;
sum = ui1+ui2;
while(sum > 4) { printf("Whats up !");
sum=0;}
return 0;
}
I'm not sure that i got what you want to do... but if you simply want to check the sum of the two integers using the while statement, you can put a break inside the while loop and everything will work :)
#include <stdio.h>
int main()
{
int ui1;
int ui2;
puts("Please enter two numbers:");
scanf("%2i", &ui1, &ui2);
int sum;
sum = ui1+ui2;
while(sum > 5) {
printf("Whats up !");
break;
}
return 0;
}
As others told you, using a if is the best solution

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