Im trying to take 4 digit number from user in c language.
1) I have tried using scanf("%d%d%d%d",&a,&b,&c,&d);
When I compile the code i write the numbers (1234) and enter the code does not execute after pressing enter.
2) I tried :
a=getche();
b=getche();
c=getche();
d=getche();
but when using getche a,b,c,d saving as char not integer. And the code didn't work properly again.
What should i do? How can i take 4 numbers from user and save every digit in different integer?
There is another way just enter the entire numbers and they will be separated:
int number, result;
printf("Please, enter four numbers: ");
scanf("%d", &number);
while (number > 0) {
result = number % 10;
number /= 10;
printf("%d\n", result);
}
printf("\n");
The result:
Please, enter four numbers: 1234
4
3
2
1
How can i take 4 numbers from user and save every digit in different integer?
Because there are some good comments about your problem I'll stick to the Question.
If you need to inform the User about its wrong input like:
1f
or:
g2
Something like this could be a good choice:
#include<stdio.h>
int checkInput(void);
int main(void){
int a = checkInput();
int b = checkInput();
int c = checkInput();
int d = checkInput();
printf("\nYour numbers are:\n");
printf("A = %d\n", a );
printf("B = %d\n", b );
printf("C = %d\n", c );
printf("D = %d\n", d );
return 0;
}
int checkInput(void){
int option,check;
char c;
do{
printf("Please type a number:\t");
if(scanf("%d%c",&option,&c) == 0 || c != '\n'){
while((check = getchar()) != 0 && check != '\n');
printf("\tI sayed a Number please\n\n");
}else{
break;
}
}while(1);
return option;
}
Output:
Please type a number: 2
Please type a number: 1f
I sayed a Number please
Please type a number: 1
Please type a number: g2
I sayed a Number please
Please type a number: 3
Please type a number: 4
Your numbers are:
A = 2
B = 1
C = 3
D = 4
Related
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.
I'm a newbie!
I'm supposed to get 2 integers from the user, and print the result(sum of all numbers between those two integers).
I also need to make sure that the user typed the right number.
The second number should be bigger than the first one.
And if the condition isn't fulfilled, I have to print "The second number should be bigger than the first one." and get the numbers from the user again until the user types right numbers that meet the condition.
So if I programmed it right, an example of the program would be like this.
Type the first number(integer) : 10
Type the second number(integer) : 1
The second number should be bigger than the first one.
Type the first number(integer) : 1
Type the second number(integer) : 10
Result : 55
End
I think that I have to make two loops, but I can't seem to figure out how.
My English is limited, to help your understanding of this quiz, I'll add my flowchart below.
I tried many different ways I can think of, but nothing seems to work.
This is the code that I ended up with now.
But this doesn't work either.
#include <stdio.h>
void main(void)
{
int a = 0;
int b = 0;
int total_sum = 0;
printf("Type the first number : \n");
scanf("%d", &a);
printf("Type the second number : \n");
scanf("%d", &b);
while (a > b) {
printf("The second number should be bigger than the first one.\n");
printf("Type the first number : \n");
scanf("%d", &a);
printf("Type the second number : \n");
scanf("%d", &b);
}
while (a <= b) {
total_sum += a;
a++;
}
printf("Result : \n", total_sum);
}
Instead of using loop to sum the numbers, we can use mathematical formula.
Sum of first N integers= N*(N+1)/2
#include <stdio.h>
int main(void)
{
int a = 0;
int b = 0;
int sum;
//Run infinite loop untill a>b
while(1)
{
printf("Type the first number : ");
scanf("%d", &a);
printf("Type the second number : ");
scanf("%d", &b);
if(a>b)
{
printf("The second number should be bigger than the first one.\n");
}
else
{
break;
}
}
//Reduce comlexity of looping
sum=((b*(b+1))-(a*(a-1)))/2;
printf("Result : %d " , sum);
return 0;
}
After corrections your code should run. The community has pointed out many mistakes in your code. Here's an amalgamated solution:
#include <stdio.h>
int main(void)
{
int a = 0;
int b = 0;
int correctInput=0;
int total_sum = 0;
do
{
printf("Type the first number : \n");
scanf("%d", &a);
printf("Type the second number : \n");
scanf("%d", &b);
if(a<b)
correctInput=1;
else
printf("The second number should be bigger than the first one.\n");
}
while (correctInput ==0) ;
while (a <= b) {
total_sum += a;
a++;
}
printf("Result : %d \n" , total_sum);
return 0;
}
Factorials are used frequently in probability problems. The factorial of a positive integer n (written n! and pronounced "n factorial") is equal to the product of the positive integers from 1 to n: n! = 1 x 2 x 3 x x n Write a program that takes as input an integer n and computes n!.
My program prompts the user for two positive integers to compute their GCD. From the scanner, the program does not accept any input that is not a positive integer and instead prompts the user again.
Most of my code already works correctly. My issue is that my program takes two negative integer inputs before asking for another positive integer. Other characters work just fine. Any tips to solve this minor issue?
Source code
#include <stdio.h>
#include <stdlib.h>
int main() {
int temp1, temp2, A, B, C;
char str[256];
while(1){
printf("Enter a positive integer: ");
while(scanf(" %d", &A)!=1 || A <= 0) {
scanf(" %s", str);
printf("Please enter a positive integer: ");
}
if(A > 0){
break;
}
}
//same loop to get B
//compute GCD of A and B
//print out answer
return 0;
}
Sample Output
Enter a positive integer: -5
-6
Please enter a positive integer: -7
-8
Please enter a positive integer: k
Please enter a positive integer: s
Please enter a positive integer: d
Please enter a positive integer: 5
Your program wants to read something because you told so.
Try this:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int temp1, temp2, scanf_ret, A, B, C;
while(1){
printf("Enter a positive integer: ");
while((scanf_ret=scanf(" %d", &A))!=1 || A <= 0) {
if(scanf_ret<0) {
puts("got unexpected EOF");
return 1;
}
if(scanf_ret==0)scanf(" %*s");
printf("Please enter a positive integer: ");
}
if(A > 0){
break;
}
}
//same loop to get B
//compute GCD of A and B
//print out answer
return 0;
}
In this code,
If scanf_ret is 1, it means the read was successful and there is no need to consume garbage.
If scanf_ret is 0, it means there are some obstacles that cannot be read as integer, so remove them.
If scanf_ret is negative, it means it is the end of input, so exit program.
Also note that you are not to store the garbage, so buffer overrun can be avoided.
1.I have this sample program in C that accepts positive inputs from users and stops when the user inputs negative numbers. It accepts a maximum of ten inputs. It then displays the result in reverse order. I'm wondering how does that happen because when I try to map it the value of c is negative, the second loop will only work if the condition (c>=0) is satisfied.
Example if I input only one positive number and I will input a negative number next.
input[0]=2
i=0+1
c=1-2
input[1]=-4
i=1+1
c=2-2
num=2*input[-1]?
#include<stdio.h>
int main()
{
float in;
float input[10];
int i=0;
int c;
printf("Please input a number:");
do{ scanf("%f", &in);
input[i] = in;
i=i+1;
if(i>10)
break;
c=i-1;
}while(in>=0);
do{ float num;
num= 2*input[c];
printf("Input = %.2f. Num= %.2f.\n", input[c], num);
c=c-1;
}while(c>=0);
return 0;
}
The input using the do-while code:
2
3
-4
The output:
Input:3.00 Output:6.00
Input:2.00 Output: 4.00
And When I try to implement it using for loop, it compiled in gcc but when I try to execute it displays segmentation fault (core dumped).
#include<stdio.h>
int main()
{ float in;
float input[10];
int i,c;
printf("Please input a number:");
for(i=0; in>=0; ){
scanf("%f", &in);
input[i] = in;
i=i+1;
if(i==10)
break;
c=i-2;
}
for(; c>=0;){
float num;
num= 2*input[c];
printf("Input = %.2f. Num= %.2f.\n", input[c], num);
c=c-1;
}
return 0;
}
I'm wondering how does that happen because when I try to map it the value of c is negative
I don't think c does go negitive, when i try to map it with 2 & -4 as inputs i get..
When you enter 2;
it makes input[i] = 2 (i is equal to 0) then after that i is incremented to 1.
and then it makes c = i - 1 or c = 1 - 1 or c = 0.
doesn't quit because in >= 0 (2).
When you enter -4;
i makes input[i] = -4 (i is equal to 1, c is equal to 0) then after i is incremented to 2
and then it makes c = i - 1 or c = 2 - 1 or c = 1.
this time quits because in < 0 & not in >= 0.
do{ scanf("%f", &in);
input[i] = in;
i=i+1;
if(i>10)
break;
c=i-1;
} while (in >=0)
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;
}
}