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)
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 have tried to write a program in C to check Luhn algorithm for credit cards, but it doesn't work. I think I do not have quite clear how getchar() works, but this program looked sensible to me. Can you tell me what is wrong with it? Thank you in advance for any help with this.
#include <stdio.h>
int main(void) {
char x;
int n, sum, i, c;
sum = 0;
printf("Insert the number of digits: ");
scanf("%d",&n);
printf("Insert the digits: ");
for(i = n; i > 1; i = i - 1){
x = getchar();
if(i%2==0)
if(2*x < 10) sum = sum + 2*x;
else sum = sum + 2*x - 9;
else sum = sum + x;
i = i - 1;
}
c = (9*sum)%10;
x = getchar();
getchar();
if(x == c) printf("Last digit: %d,\nCheck digit: %d,\nMatching",x,c);
else printf("Last digit: %d,\nCheck digit: %d,\nNot Matching",x,c);
}
getchar() reads one character. Therefore, the x = getchar(); in the loop is not good because
It firstly read a newline character if you enter that after the first "number of digits".
It will read a character, not an integer. Character codes typically differ from the integer the character represents, and it may affect the check digit calculation.
Instead of x = getchar();, you should do this in the loop:
scanf(" %c", &x); /* ignore whitespace characters (including newline character) and read one character */
x -= '0'; /* convert the character to corresponding integer */
#include <stdio.h>
#define N 16
void luhn_algorithm();
int main(){
int a[N];
int i;
printf("type the card number:\n");
for(i=1;i<=N;i++){
scanf("%d",&a[i]);
}
luhn_algorithm(a);
}
void luhn_algorithm(int *a){
int i,multiply=1,m,sum=0,total=0;
for(i=1;i<=N;i++){
if(i%2!=0){
multiply=a[i]*2;
if(multiply>9){
while(multiply>0){
m=multiply%10;
sum+=multiply;
multiply/=10;
}
multiply=sum;
}
}
else if(i%2==0){
multiply=a[i]*1;
if(multiply>9){
while(multiply>0){
m=multiply%10;
sum+=multiply;
multiply/=10;
}
multiply=sum;
}
}
total+=multiply;
}
if(total%10==0){
printf("\nthis credit card is valid ");
}
else{
printf("\nthis credit card is not valid");
}
}
this is the program i made to check if credit card number is valid or not try this out.
I took the numbers in an array and then multiplied it according to their position and added them all if the last digit of the added total comes out to be 0 that means the card is valid otherwise its not.
check it out if theres something wrong please tell me.
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
I want user to enter 8 numbers.
If they enter less than 8 numbers, the program will exit.
What if statement should I use?
Should I put in my loop sum += i then if sum not 8 then exit?
This is what I got so far but it doesn't work out:
int main() {
int i, numb;
int sum = 0;
// the loop to enter 8 numb
printf("enter 8 numbers");
if (i=0;i<8;i++) {
scanf("%d", &numb);
sum =+i;
if (sum < 8)
exit(1);
}
return (0);
}
You want the user to enter 8 numbers and since you have not mentioned anything about the sum, I'll assume it doesn't matter what it is. Remove the inner if condition altogether and replace the outer if with a loop.
Here is the code:
for (i = 0; i < 8; i++) {
scanf("%d", &numb);
//Do whatever you want to do with the number here
Because of the way the console works you can't tell where the EOF is. You can achieve what you want by checking the separators between the numbers. If you want the numbers to be no less than 8 on the same line, you can do it this way
int main() {
int i, numb;
int sum = 0;
char separator=' ';
// the loop to enter 8 numb
printf("enter 8 numbers");
for (i = 0; i<8; i++)
{
if (separator == '\n')//enter character encountered
break;
scanf("%d%c", &numb,&separator);
}
if (i < 8)
exit(1);
return (0);
}
Here is an algorithm which does exactly what you want:
1. Set a counter to 0
2. While not end of file (EOF) do
1. Read a number
2. Increase counter by 1
3. If sum counter equals 8, return 1, else return 0
and your code repaired (since you've finally posted what you tried to do):
int main()
{
int i, numb, counter = 0;
printf("enter 8 numbers");
while(scanf("%d", &numb) != EOF)
{
counter++;
}
if (counter < 8)
{
printf("not enough numbers\n");
exit(1);
}
return (0);
}
Live demo: http://ideone.com/iiOl1A
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;
}
}