c program for calculating expressions - c

I have made this program to calculate expressions like '2 + 6 - 9'(with spaces between numbers and operators), but the last if block is not correct. How can I break the loop when \n is received, and also store the input if not.
#include <stdio.h>
#include<stdlib.h>
void main()
{
char oper;
int sum,y;
scanf("%d %c",&sum,&oper);
while(1)
{
scanf("%d",&y);
if(oper=='+')
sum += y;
else if(oper=='-')
sum -= y;
else if(oper=='/')
sum /= y;
else if(oper=='*')
sum += y;
if((scanf("%c",&oper))=='\n')
break;
}
printf("\n =%d",sum);
}

See the documentation for scanf
On success, the function returns the number of items of the argument list successfully filled.
Replace this part:
if((scanf("%c",&oper))=='\n')
break;
with:
if(scanf("%c",&oper) && oper=='\n')
break;
This:
checks whether scanf() has put any value into oper
if yes then it checks if the value is equal to \n

Related

(Visual Studio)Calculation _using for sentence

Want to elicit average of entered real value,until negative value is entered.
My problem is
My calculation don't quit when negative value is entered
It keep asks printf sentence for 3 time.
What did I do wrong?
#include <stdio.h>
int main(void)
{
double total = 0.0;
double input=0.0;
int num = 0;
for (; input >= 0.0;)
{
total += input;
printf("real number(minus to quit):");
scanf_s("%1f", &input);
num++;
}
printf("average:%f \n", total / (num - 1));
return 0;
}
you have many problems with your code :
it's not %1f in the line scanf_s("%1f", &total); as %1f will give you undefined behavior , it's %lfas you are scanning a double , there is a big difference between number one and lower case L
the function called scanf returns an integer indicating how many elements could be assigned to the input that the user entered , so , you should do if(scanf_s("%lf", &input) == 1) to check if the assignment done successfully, that will help you in detecting if - is entered instead of the number
if the user entered a lonely - then sacnf will fail to convert and you have to take another approach
when you are printing the average in this line : printf("average:%f \n", total / (num - 1)); , you actually prints a double , so it's %lf instead of %f
the condition of the for loop is incorrect , you are saying for (; input >= 0.0;) but this will prevent you from entering any negative values as when entering a negative value , the for loop will break , so you could use while(1) instead of the for loop and only break when a - is entered alone
so here is my edited version of yours , I introduced a dummy string to read the buffer and check whether the input was a lonely - or not , and if not then I try to convert it to double and here is my edited solution :
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char dummy[30];
double total = 0.0;
int num = 0;
double DecimalConverted = 0;
while(1)
{
printf("real number(minus to quit):");
fgets(dummy, 30, stdin); // gets the input into the buffer
if(dummy[0] == '-' && dummy[1] == '\n') // break from the loop on condition that '-' only entered
break;
// convert the string to decimal
DecimalConverted = strtod(dummy ,NULL);
if(DecimalConverted == 0)
printf("not a number\n");
else{
total += DecimalConverted;
num++;
}
}
printf("average:%lf \n", total / (num - 1));
return 0;
}
and here is the output :
real number(minus to quit):12
real number(minus to quit):-51
real number(minus to quit):-
average:-39.000000

C programming Luhn algorithm

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.

Why am I receiving an error at my "for" loop saying 'break' statement not in loop or switch?

incredibly new to programming I am receiving an error on line 12 stating that my break statement is not in the loop or switch. Can anyone explain where my error is and how to fix it?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int n1, n2, i, gcd, lcm;
printf("Enter two positive integers: ");
scanf("%d %d",&n1,&n2);
for(i=1; i <= n1 && i <= n2; ++i) {
printf("Enter two positive integers: ");
scanf("%d %d",&n1,&n2);
if(n1==-1,n2==-1) break;
// Checks if i is factor of both integers
if(n1%i==0 && n2%i==0)
gcd = i;
}
lcm = (n1*n2)/gcd;
printf("The LCM of two numbers %d and %d is %d.", n1, n2, lcm);
return 0;
}
If you are "receiving an error on line 12 stating that my break statement is not in the loop or switch" then either you have a very deficient compiler or you've posted the wrong code. That code has a few problems but a break in the wrong place is not one of them.
That particular error message often occurs when you've mislaid some braces, along the lines of:
int i;
for (i = 0; i < 10; ++i)
printf("%d\n", i);
if (someCondition)
break;
That's because, despite the fact it looks like you're breaking out of a loop, the actual break statement is not within the loop. Only the printf is.
In terms of the code you have provided, there are numerous ways to clean it up:
Remove unneeded includes.
Refactor out the number input to a common function.
Allow a single non-positive number to terminate the program.
Use DRY principle for input, there's really any need to duplicate code segments if you structure it corretly.
Make input more robust, allowing for invalid numbers.
Add more comments, these will greatly assist you (or others who have to maintain your code) in the future.
Use better variable names. Other than i for small localised loops, I almost never use single-character variable names.
Fix the if(n1==-1,n2==-1) bit. That doesn't do what you appear to think it does. The comma operator will evaluate both expressions but the result of the full expression is the rightmost one. So it's effectively if(n2==-1).
To that end, the following is how I would write the code:
#include <stdio.h>
#define ERR_NON_POS -1
#define ERR_INVALID -2
// Gets a single number.
// If non-positive or invalid, returns error (a negative value ERR_*).
// Otherwise, returns the (positive) number.
int getNumber(void) {
int number;
if (scanf("%d", &number) != 1) return -2;
if (number <= 0) return -1;
return number;
}
int main(void) {
// Infinite loop, we'll break from within as needed.
for (;;) {
printf("Enter two positive integers (a negative number will stop): ");
// Do it one at a time so a SINGLE negative number can stop.
int number1 = getNumber();
if (number1 == ERR_INVALID) {
puts("** Non-integral value entered");
break;
}
if (number1 == ERR_NON_POS) break;
int number2 = getNumber();
if (number2 == ERR_INVALID) {
puts("** Non-integral value entered");
break;
}
if (number2 == ERR_NON_POS) break;
// Work out greatest common divisor (though there are better ways
// to do this than checking EVERY possibility).
int gcd = 1;
for (int i = 2; (i <= number1) && (i <= number2); ++i) {
if (number1 % i == 0 && number2 % i == 0) {
gcd = i;
}
}
// Work out the lowest common multiple.
int lcm = number1 * number2 / gcd;
// Print them both and go get more.
printf("For numbers %d and %d, GCD is %d and LCM is %d.\n", number1, number2, gcd, lcm);
}
return 0;
}
And, if you're wondering about the more efficient way of calculating GCD, you should look into Euclid's algorithm. This can be defined as (for non-negative a and b):
gcd(a,b) = a if b is zero
gcd(b, a mod b) if b is non-zero
That means you can have a recursive function:
int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
Or an iterative one if you're vehemently opposed to recursion:
int gcd(int a, int b) {
while (b != 0) {
int t = a % b;
a = b;
b = t;
}
return a;
}

How to prevent an infinite loop with scanf failure

The Code is supposed to make change for a dollar and works fine. but the professor says that he will be enter random numbers along with letters. It works fine with numbers but when a letter is entered an infinite loop will occur any suggestions?
#include <stdio.h>
#include <stdlib.h>
#define amtPaid 1
#define SENTINAL -1
int quarters(int numChange);
int dimes(int numChange);
int nickels(int numChange);
int pennies(int numChange);
int main(void)
{
double amtDue = 0; // how much is paid
while(1){
printf("\nPlease enter the price less than 1 dollar: ");
scanf(" %lg", &amtDue);
int changeReturn = (amtPaid - amtDue) * 100 + 0.5; // convert decimal to whole number
int updated = 0; // remaining change after amt of change
int numberQuarters = quarters(changeReturn); // number of quarters needed
if(changeReturn >= 0 && changeReturn <= 100){ // if changereturn is between 0 and 100 execute code
printf("\nNice!");
printf("\nWe owe you %i cents" , changeReturn);
if(numberQuarters >= 0){ // get and print number of quarters
printf("\nQuarters: %i", numberQuarters);
updated = changeReturn % 25;
}
if(dimes(updated) >= 0){ // get and print number of dimes
printf("\nDimes: %i", dimes(updated));
updated = updated % 10;
}
if(nickels(updated)>= 0){ // get and print number of nickels
printf("\nNickels: %i", nickels(updated));
updated = updated % 5;
}
if(pennies(updated) >= 0){ // get and print number pennies
printf("\nPennies: %i", pennies(updated));
}
}
else if(amtDue == SENTINAL){
break;
}
else {
printf("That does not make sense to me. please type a valid number");
}
printf("\n %g", amtDue);
}
return 0;
}
int quarters(int numChange){
int numQuarters = 0;
numQuarters = numChange / 25;
return numQuarters;
}
int dimes(int numChange){
int numDimes = 0;
numDimes = numChange / 10;
return numDimes;
}
int nickels(numChange){
int numNickels = 0;
numNickels = numChange / 5;
return numNickels;
}
int pennies(numChange){
return numChange;
}
In case an inappropriate value is supplied other than the expected value of the format specifier with scanf(), the scanf() will fail and the inappropriate value will remain in the input buffer, providing the feed to next scanf(), only to cause successive failures. In that case, you need to clean up the input buffer before going for next input. You can use something like
check the return value of scanf()
In case of failure, use while( getchar() != '\n' ); to clean the input buffer.
That said, int nickels(numChange) is now invalid in c (C99 onwards). You have to make it as int explicitly.
Instead of using scanf(" %lg", &amtDue);, get the user input as a string, so you can do proper checking.
char input[500];
fgets(input, 500, stdin);
// do some input checking
double val = atof(input);
// do calculations on the number
To check, there's all kinds of functions to help you in ctype.h, one that you might find interesting is isalpha.
Manual References:
fgets
atof converts string to double
atoi converts string to integer
isalpha

Finding if a Number if Prime or not In C

I was writing a C Program to find if a number is prime or not. Everytime I run it and enter a number, the value of the input changes. PLease point out the loopholes.
#include<stdio.h>
#include<conio.h>
int main()
{
int x;
int y;
y=getchar();
for(x=2;x<y;++x){
if(y%x != 0 && y!=x)
printf(" THE NUMBER %d is A PRIME \n", y);
else
printf(" \r THE NUMBER %d IS NOT A PRIME", y);
break;
}
}
I use the Code::Blocks IDE with GCC Compiler
As the name implies, getchar() gets a single character from standard input. For example, if you enter 3, the y gets the ASCII code of the character '3', which is obviously not what you want.
Try scanf:
scanf("%d", &y);
getchar returns the ASCII code of a single character. Consequently, your program picks up the ASCII code of the first character of the number you input and checks if it is prime.
Instead, you need to read an integer:
scanf("%d", &y);
The complete program:
#include<stdio.h>
#include<conio.h>
int main()
{
int x;
int y;
scanf("%d", &y);
for(x=2;x<y;++x){
if(y%x != 0 && y!=x)
printf(" THE NUMBER %d is A PRIME \n", y);
else {
printf(" \r THE NUMBER %d IS NOT A PRIME", y);
break;
}
}
}
Note: You can stop when x >= sqrt(y)
Well, you are calling getchar() which is used to input a single character and this is what happens in your case:
getchar() returns a character.
Character is then converted into integer when you store it in variable of type int.
Hence that integer contains the ASCII of input character i.e. 3 will be stored as 51 that is the reason input changes.
What you need to do is to input an integer instead of character. Try this:
scanf("%d", &y);
Hope this helps.
First answers are correct about input for y:
scanf("%d", &y);
Also, please note that you should loop until square root of x, and not more if your want to optimize your algorithm (I won't demonstrate here why, it's a mathematical property).
#include <stdio.h>
#include <math.h>
// ...
int x;
int x_max;
int y;
scanf("%d", &y);
x_max = (int)floor(sqrt(y));
for(x=2;x<=x_max;++x){
// ...

Resources