Addition (+) does not want to run in if/else - c

#include <stdio.h>
int main(void)
{
int a;
scanf("%d", &a);
for (int i = 0; ; i++)
{
char values[2];
scanf("%c", &values[0]);
scanf("%d", &values[1]);
if (values[0] == '*')
{
a = a * values[1];
printf(" = %d\n", a);
}
else if (values[0] == '+')
{
a = a + values[1];
printf(" = %d\n", a);
}
else if (values[0] == '%')
{
a = a % values[1];
break;
}
}
printf("%d", a);
}
When I input 5 + 3 + 7 + 10 + 2 + 3 + 1 % 11, it would show 5 (because 5%11 = 5). But the + operation didn't work. Can you see what is the problem here?

I think as values[2] is only two variable you need, you can use two different variable to do your job. use one char type variable and one int type variable as you need these two. You have another problem in your code, use a getchar() in the inside of the loop then your code will work fine, cause when you give a integer value as input then take a character value last you enter the new line that goes to that character that is why your code was giving error.
#include <stdio.h>
int main(void){
int a;
scanf("%d", &a);
for (int i = 0; ; i++)
{
getchar();
char ch;
int value;
scanf("%c", &ch);
scanf("%d", &value);
if (ch == '*')
{
a = a * value;
printf(" = %d\n", a);
}
else if (ch == '+')
{
a = a + value;
printf(" = %d\n", a);
}
else if (ch == '%')
{
a = a % value;
break;
}
}
printf("%d", a);
}

There are multiple problems:
value is an array of char: scanning the operator into a char is fine, but the value should be converted into an int variable.
the scanf("%c", ...) will store the next byte into the variable, but after converting an int, the next byte is the pending space or newline, not the '+'. You should use scanf(" %c", ...) to skip the whitespace after the previous conversion.
Here is a modified version:
#include <stdio.h>
int main(void) {
int a;
if (scanf("%d", &a) != 1)
return 1;
for (int i = 0; ; i++) {
char op;
int value;
if (scanf(" %c", &op) != 1)
break;
if (scanf("%d", &value) != 1)
break;
if (op == '*') {
a = a * value;
printf(" = %d\n", a);
} else
if (op == '+') {
a = a + value;
printf(" = %d\n", a);
} else
if (op == '-') {
a = a - value;
printf(" = %d\n", a);
} else
if (op == '%') {
a = a % value;
printf(" = %d\n", a);
} else
if (op == '/') {
a = a / value;
printf(" = %d\n", a);
} else {
printf("invalid operator %c\n", op);
break;
}
}
printf("%d\n", a);
return 0;
}

Related

double value changed when printf() C

I'm trying to learn about pointer, and I got a task, but when I tried to print a float array, the 1st value changed.
void getinputA(double *aa){
while(1){
scanf("%lf", &*aa);
getchar();
if(*aa< 100 || *aa>10000){
printf("input the right amount\n")
}else{
printf("success\n\n");
break;
}
}
return;
}
void getinputB(double *bb){
while(1){
scanf("%lf", &*bb);
getchar();
if(*ten == 1 || *ten == 3 || *ten == 6 || *ten == 12){
printf("success\n\n")
}else{
printf("input the right number\n");
break;
}
}
return;
}
void getinputC(double *cc){
while(1){
scanf("%lf", &*cc);
getchar();
if(*cc<1 || *aa>10){
printf("input the right number\n")
}else{
printf("success\n\n");
break;
}
}
return;
}
int main(){
double A;
int B, C, Rep, D;
getinputA(&A);
Rep = (12/B)*C
for(int i=0; i<Rep; i++){
if(i == 0){
D[i] = A;
//checked, still correct
}else{
D[i] = AnotherVarInMyCode[i-1];
//checked, still correct
}
AnotherVar[i] = A[i]*(DifferentVar/(12/B));
AnotherVarInMyCode[i] = A[i]+AnotherVar[i];
}
AFunction();
//here
for(int i=0; i<Rep; i++){
printf("%d %.2lf\n", i+1, D[i]);
//when I input 1000, it prints -400, and when I input 100, it -0,98
}
return 0;
}
I found out that the value change after it runs a function which I don't use D, why does this happen? And how to fix it?
I've checked my code, but I can't figure out why it changed.
if changed from 1000 to -200, and from 100 to -0.98

How can I fix my problem about terminating the program instead of repeat it from the start using while loop? C Language

I have new problem about while-loop!
When I input the l_res as y it means that the condition of while loop is still TRUE, instead repeat it from the start, it terminated the program. → enter image description here
int main()
{
//VARIABLES
char f_res[4];
char l_res = 'y';
int a,b,c,x;
while(l_res == 'y')
{
printf("Enter 3 digit capacitor Code: ");
scanf("%d %d %d",&a,&b,&c);
x = (a*10)+b;
printf("What is the unit of the value?(Pico-picofarad, Nano-Nanofarad): ");
scanf("%s", f_res);
if(strcmp(f_res, "Pico") == 0)
{
if(c == 0)
{
x = x;
}
else
{
while(c <= 5 && c > 0)
{
c--;
x = x*10;
}
}
printf("\nCapacitor value is: %d pF\n\n",x);
}
else if(strcmp(f_res, "Nano") == 0)
{
float x = ((a*10)+b)*0.001;
if(c == 0)
{
x = x;
}
else
{
while(c <= 5 && c > 0)
{
c--;
x = x*10;
}
}
printf("\nCapacitor value is: %.3f pF\n\n",x);
}
else
{
printf("\nINVALID Input!\n\n");
}
printf("Do you want to enter other capacitor Code?( y-Yes, n-No): ");
scanf(" %c", l_res);
}
return 0;
}
How can I fix this?

C simple program

I'm learning starting to learn C, so I tried to make a simple program with what I know. The program SHOULD ask for a letter, ask if you want the position of a letter in the alphabet(if so it displays "x is the y letter in the alphabet" with the suffix) and then it asks if you want the letter in binary and puts it in binary. But for some reason it doesn't work. I tried "manual debugging"(using puts() to see what doesn't work) and the class "getNumber" works but the value changes when it goes to the main class.
a returns "2686719" instead of "a is the 1st letter in the alphabet" and b returns "2b is the 2z\<<y in the alphabet".
This is the code, what did I do wrong?
#include <stdio.h>
#include <stdlib.h>
//011
int main(){
int x = 2;
char letter;
puts("Write a letter");
char temp2;
scanf("%c", &temp2);
int number;
letter = temp2;
puts("get alphabet position? y/n ");
char temp[2];
scanf("%s", temp);
char answer = temp[0];
int tempNumber2 = getNumber(letter);
if(answer == 'y'){
char suffix[3];
int number = tempNumber2;
printf("%d", number);
if (number == 1){
x = 1;
suffix[0] = "s";
suffix[1] = "t";
}else if (number < 27){
suffix[0] = "t";
suffix[1] = "h";
x = 1;
}
if (x == 1){
printf("%c is the %d", letter, number);
printf("%s in the alphabet\n", suffix);
}}else if (answer == 'n'){
x = 1;
}else if (answer != 'y' && answer != 'n'){
puts("ERROR, invalid letter");
x = 3;
};
if(x != 3){
puts("Convert to binary?");
}
return 0;
}
int getNumber(letter){
char tempLetter = letter;
int tempNumber = -1;
char alphabet[27] = "abcdefghijklmnopqrstuvwxyz";
int i = 0;
while(i < 27){
i++;
if(tempLetter == alphabet[i]){
tempNumber = i;
tempNumber++;
printf("%d \n", tempNumber);
return tempNumber;
}
};
}
By the way, I haven't gotten to the binary part hence why it's empty.
As everyone stated in the comments your problem is that suffix's last char is not set to '\0'.
Moreover, you could getNumber in a much simpler way:
int getNumber(char letter) {
return (int)(letter - 'a') + 1;
}
Btw, you can make your code look a little better (didn't change it too much):
int main() {
char letter;
char answer;
puts("Write a letter");
scanf("%c", &letter);
getchar(); // read \n
puts("get alphabet position? y/n ");
scanf("%c", &answer);
getchar(); // read \n
if (answer == 'n') {
return 0;
}
if (answer != 'y') {
puts("ERROR, invalid letter");
return 1;
}
int number = getNumber(letter);
char suffix[3];
suffix[2] = 0;
if (number == 1) {
suffix[0] = 's';
suffix[1] = 't';
} else if (number == 2) {
suffix[0] = 'n';
suffix[1] = 'd';
} else if (number == 3) {
suffix[0] = 'r';
suffix[1] = 'd';
} else {
suffix[0] = 't';
suffix[1] = 'h';
}
printf("%c is the %d%s letter in the alphabet\n", letter, number, suffix);
puts("Convert to binary?");
return 0;
}

Program errors due to strcmp and strcpy in C

No matter how I edit my program there seems to be overflow errors and mismatching type errors. Can someone help me to make this run without errors.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int choice;
int i;
int j;
char type;
int amount;
int don_count = 0;
int req_count = 0;
int flag;
char donations_inv_type[100][20];
int donations_amount[100];
char requests_inv_type[100][20];
int req_amount[100];
printf("Welcome to the Food Bank Program\n\n 1. Add a donation\n 2. Add a request\n 3. Fulfill a request\n 4. Print status report\n 5. Exit\n\nEnter your choice: ");
scanf("%d", &choice);
while (choice != 5) {
if (choice == 1) {
printf("\nEnter inventory type: ");
scanf("%s", &type);
printf("Enter the amount: ");
scanf("%d", &amount);
printf("\nDonation Added!\n\n");
flag = -99;
for (i = 0; i < don_count; i++) {
if (strcmp(donations_inv_type[i], type) == 0)
flag = i;
}
if (flag == -99) {
strcpy(donations_inv_type[i], type);
donations_amount[i] = amount;
don_count++;
}
else
donations_amount[flag] += amount;
printf("Donation Added!\n");
printf("Press any key to continue . . .\n\n");
}
else if (choice == 2) {
printf("\nEnter inventory type: ");
scanf("%s", &type);
printf("Enter the amount: ");
scanf("%d", &amount);
strcpy(requests_inv_type[req_count], type);
req_amount[req_count] = amount;
req_count++;
}
else if (choice == 3) {
printf("\n\n-------- Fulfilling Requests--------");
flag = -99;
for (i = 0; i < don_count; i++) {
if (strcmp(donations_inv_type[i], requests_inv_type[0]) == 0)
flag = i;
}
if (flag == -99)
printf("Cannot be Fulfilled\n\n");
else if (donations_amount[flag] > req_amount[0]) {
donations_amount[flag] -= req_amount[0];
printf("Request Fulfilled");
req_amount[0] = 0;
}
else if (donations_amount[flag] == req_amount[0]) {
printf("Request Fulfilled");
for (i = flag; i < don_count; i++) {
strcpy(donations_inv_type[i], donations_inv_type[i + 1]);
strcpy(donations_amount[i], donations_amount[i + 1]);
}
don_count--;
for (i = flag; i < req_count; i++) {
strcpy(requests_inv_type[i], requests_inv_type[i + 1]);
strcpy(req_amount[i], req_amount[i + 1]);
}
req_count--;
}
else if (donations_amount[flag] < req_amount[0]) {
printf("Partially Fulfilled");
req_amount[0] -= donations_amount[flag];
for (i = flag; i < don_count; i++) {
strcpy(donations_inv_type[i], donations_inv_type[i + 1]);
strcpy(donations_amount[i], donations_amount[i + 1]);
don_count--;
}
}
}
else if (choice == 4) {
printf("Printing the Donations Table\n\n");
for (i = 0; i < don_count; i++) {
printf("%s %d", donations_inv_type[i], donations_amount[i]);
}
printf("Printing the Requests Table\n\n");
for (i = 0; i < req_count; i++) {
printf("%s %d", requests_inv_type[i], req_amount[i]);
}
}
printf("Welcome to the Food Bank Program\n\n 1. Add a donation\n 2. Add a request\n 3. Fulfill a request\n 4. Print status report\n 5. Exit\n\nEnter your choice: ");
}
}
Any help is greatly appreciated and I would love an explanation as to what I did wrong so that I can learn and not make the same mistakes next time.
Declare type as character array.
char type[50];
Remove & in scanf(). You should not use & while reading string.
scanf("%s", &type); ==> scanf("%s", type);
^
Here you want to copy integers not strings
strcpy(donations_amount[i], donations_amount[i + 1]);
strcpy(req_amount[i], req_amount[i + 1]);
Modify like this
donations_amount[i]=donations_amount[i + 1];
req_amount[i]= req_amount[i + 1];
Instead of char type you need char type[100]
Error in your code:
if (strcmp(donations_inv_type[i], type) == 0)
// ^^^^ should be char*
Note: Functions strcmp() and strcpy() should be passed \0 nul-terminated array of char (or say string).
Your scanf should look like scanf("%s", type);

End a program with the Enter key

I am trying have a program end when the user hits the Enter key. For some reason it doesn't seem to work. When I use "char c is not equal to enter key" it takes in an extra integer in c (the last inputted integer). What is the problem with this code?
#include <stdio.h>
#include <stdlib.h>
#define framenumber 4
int test1 =0;
int test2=1;
int main(void)
{
int mainarray[framenumber][2] = {0}, nHP = 3, takein, iPT;
char c = getchar();
printf("Enter: ");
while(1)
{
char c = getchar();
if(c == '\n') {
printf("here");
}
else
{
printf("not enter\n");
takein = atoi(&c);
for (iPT = 0; mainarray[iPT][test2] != takein && iPT < framenumber; iPT++);
if (mainarray[iPT][test2] != takein)
{
//search for a victim
do {
nHP = (nHP + 1) % framenumber;
} while ( !( mainarray[nHP][test1] == 1 ? mainarray[nHP][test1] = 0 : 1 ) );
//update the page table
mainarray[nHP][test1] = 1;
mainarray[nHP][test2] = takein;
}
else
{
mainarray[iPT][test1] = 1;
}
puts("page table:");
for (iPT = 0; iPT < framenumber; iPT++)
{
printf("%s %d, %d.\n", iPT == (nHP + 1) % 4 ? ">": " ", mainarray[iPT][test1], mainarray[iPT][test2]);
}
putchar('\n');
printf("Enter: ");
}
}
return 0;
}
Do not create block variable. (In while loop).
char c='\0'; /* initialize with 0 */
printf("Enter: ");
while(c!='\n') /* loop terminate condition */
{
c= getchar(); /* remove declaration */
if(c =='\n')
{
printf("here");
}
else
{
getchar(); /* read (eat) an extra input */
printf("not enter\n");
....

Resources