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

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

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.

When I am trying to take a contact number from a user and I am print it shows always 0

The source code is below.
#include <stdio.h>
int main()
{
long long n;
int count;
lable:
count = 0;
printf("Enter your contact number : ");
scanf("%lld", &n);
//know that enterd interger(contact number) have how many numbers in it
while (n != 0) {
n /= 10;
++count;
}
//if numbers are 10 then your contact number is right
if(count==10)
{
printf("contact number enterd sucessfully\n");
goto exit;
}
else
//else numbers are not 10 then invalid contact number and enter again
{
printf("In valid contact number enter again...........\n");
goto lable;
}
exit:
printf("contact number : %lld ",n);
return 0;
}
In this code, I try to enter the contact number from the user and it is checked how many numbers in your contact number, then there is 10 numbers in your contact number so it is right, but the numbers are not 10 It is showing an error and enter the number from the user again. when the number is right program is print user contact number 0.
Please guide me what is the problem with this code?
what you have done is you are changing the value of n to 0 in the while loop and printing the same n at the end. That's why it is printing 0.
what you can do is, you can take a temporary variable to count number of characters. Refer the code below:
#include <stdio.h>
int main()
{
long long n,temp; //taking a temporary variable along with n;
int count;
lable:
count = 0;
printf("Enter your contact number : ");
scanf("%lld", &n);
temp = n; // assigning n to temp variable
//know that enterd interger(contact number) have how many numbers in it
while (temp != 0) { //counting the number of digits using temp variable.
temp /= 10;
++count;
}
//if numbers are 10 then your contact number is right
if(count==10)
{
printf("contact number enterd sucessfully\n");
goto exit;
}
else
//else numbers are not 10 then invalid contact number and enter again
{
printf("In valid contact number enter again...........\n");
goto lable;
}
exit:
printf("contact number : %lld ",n);
return 0;
}
The problem is with the statement n /= 10;
Here you are using assignment operator so it changes the value of n.
For example, if you entered n as 9876543210, then after 1st iteration, the value of n will be 9876543210/=10 i.e. 987654321. In this way after all iterations the value of n will be 0.
You can use temporary variable to store the n value and print it.
#include <stdio.h>
int main()
{
long long n, m;
int count;
lable:
count = 0;
printf("Enter your contact number : ");
scanf("%lld", &n);
m = n;
//know that enterd interger(contact number) have how many numbers in it
while (n != 0) {
n /= 10;
++count;
}
//if numbers are 10 then your contact number is right
if(count==10)
{
printf("contact number enterd sucessfully\n");
goto exit;
}
else
//else numbers are not 10 then invalid contact number and enter again
{
printf("In valid contact number enter again...........\n");
goto lable;
}
exit:
printf("contact number : %lld ",m);
return 0;
}
Ponder over this portion:
while (n != 0) {
n /= 10;
++count;
}
What you're doing here changing the value of n that you've scanned from the user. So what you can do is not using the variable n rather make a copy of it and use it. A good practice here is to make the variable constant that you don't want to edit accidentally.

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

Program will stop once five even numbers are placed in array

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

Resources