C program does not recognize my input for 'max' - c

Hi I keep trying to figuure this out but my input keeps getting ignored, thanks in advance
#include <stdio.h>
#include <stdlib.h>
int main(){
float a, b, a0, b0,i;
char ans;
printf("Fibonacci search method\n\nEnter the function:\n");
printf("\nEnter the intervals over which the Fibonacci method must be applied:\n");
for (i = 1; i <= 1; i++) {
printf("a0 = ", i);
scanf("%f", & a);
printf("bo = ", i);
scanf("%f", & b);
}
printf("Narrow down on either a maximiser or a minimiser (max/min): \n", ans);
scanf(" %c", &ans);
while(ans == 'max'){
printf("maximum selected");
}
printf("minimum selected");
return 0;
}

First of all, you're comparing a single char to a whole string, so you need to modify your ans variable declaration to make it a string, like:
char ans[4]
Keep in mind, this will have a maximum size of 3. If you need to store a bigger string, you'll need to modify this.
Then, after doing this, using a while to do that comparison isn't correct. It's better to implement an if-else. And, inside that, the comparison you're doing is wrong. You need to compare strings, not chars, so you need to use strcmp() function, like:
strcmp(ans,"max") == 0
If this function returns a 0, it means both strings are equal.
Another thing to comment is that you will need to modify your scanf to scan a string, not a char, the new one will be scanf("%3s", &ans);.
And let me tell you one more thing. The for you're using has no sense. You're using a for with parameters i = 1; i <= 1; i++. That means i will start the buckle fulfilling the conditions to break it, so it will only be executed once. In other words, the code inside that for will be executed just once, no matter if it's inside or outside the for.
Anyway, and to sum up, here's your new code:
int main(){
float a, b, a0, b0,i;
char ans[4];
printf("Fibonacci search method\n\nEnter the function:\n");
printf("\nEnter the intervals over which the Fibonacci method must be applied:\n");
for (i = 1; i <= 1; i++) {
printf("a0 = ", i);
scanf("%f", & a);
printf("bo = ", i);
scanf("%f", & b);
}
printf("Narrow down on either a maximiser or a minimiser (max/min): \n", ans);
scanf("%3s", &ans);
if(strcmp(ans,"max") == 0)
printf("maximum selected");
else
printf("minimum selected");
return 0;
}

Related

Scanning Values Until Getting a Significant Character in C

For my homework, I am trying to code a calculator which can also calculate average of taken numbers. I don't want to ask for number of numbers because our teacher don't want it in that way. So I thought of scanning values until the user presses "p". But as you would guess, the numbers are float and "p" is a character. What I want to do is assigning the value scanned to both of them if it is possible. I tried different ways, played with the codes but it isn't working properly. So I am seeking your advice.
It prints a value when p is inputted as like 3rd, 5th, 7th (oddth) number (sometimes right, sometimes wrong but I can fix it if I figure this out). But it doesn't print a value in other occasions and expects infinite inputs from the user.
This is the code I have written for this. scanf("%f %c", &number1, &pause); command is where I want to know about, actually.
#include<stdio.h>
float number1, number2, i, result;
char pause;
int main() {
scanf("%f", &number1);
i = 0;
while (pause != 'p') {
number2 = number1 + number2;
scanf("%f %c", &number1, &pause);
i++;
}
result = number2 / (i - 1);
printf("%f", result);
}
Use double not floats if there is no specific reason to do so (like using uC without double FPU).
You do not initialize the variables
Always check the result of the I/O operation.
#include <stdio.h>
int main ()
{
double number1= 0, number2 = 0, i = 0, result = 0;
char pause = 0;
char line[128];
while (pause != 'p')
{
if(fgets(line, sizeof(line), stdin))
{
if(sscanf(line, "%lf %c",&number1, &pause) != 2)
{
printf("Wrong input - try again\n");
pause = 0;
continue;
}
number2 = number1 + number2;
i++;
}
else
{
// do something with I/O error
}
}
result = number2 / (i-1);
printf("%lf",result);
}
You can play with it yourself : https://onlinegdb.com/Hy3y94-3r
I noticed 3 problems with your code.
First I would advise you to use meaningful variables names. number1, number2, etc. and the i which represents the number of inputs given can be an int instead of a float.
Secondly, you lack of printing to the user what's going on in your program; it's better to have messages like "enter your number, do you wanna stop? the result is...etc".
Lastly, having two inputs in one line of code can make it hard to debug, knowing that reading strings and characters in C is already hard for beginners. For example, %c does not skip whitespace before converting a character and can get newline character from the previous data entry.
Here is my fix: I changed some variables' names, printed some messages and read the two inputs in two different lines with adding scanf(" %c") with the space to avoid that problem.
#include<stdio.h>
float sum, temp, result;
int nb;
char pause;
int main () {
pause='a';
while (pause != 'p'){
printf("Enter your number: ");
scanf("%f",&temp);
sum+=temp;
nb++;
printf("type 'p' if you want to stop: ");
scanf(" %c",&pause);
}
result = sum / nb;
printf("the average is : %f",result);
}
I tested it, should work fine
Edit: after explaining that you don't want to ask the user each time, here is how the code should work (the case that the user don't input a float is not treated, and just take it as zero
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
float sum, temp, result;
int nb;
char input[50];
int main () {
sum=0;
nb=0;
printf("Enter your numbers, then type 'p' to stop\n");
do{
printf("Enter your next number: ");
scanf("%s", input);
if(strcmp(input,"p")!=0)
{
float temp= atof(input);
sum+=temp;
nb++;
}
}while(strcmp(input,"p")!=0);
if(nb!=0)
result = sum / nb;
printf("\nThe average is : %f",result);
}

for loop resulting in undefined behaviour c

#include <stdio.h>
#include <stdlib.h>
int main() {
int i;
int mult;
int n;
int ans;
ans = mult * i;
printf("Please enter a multiple you want to explore.");
scanf("%d", &mult);
printf("Please enter the number which you would want to multiply this number till.");
scanf("%d", &n);
for(i = 0; i<n; i++) {
printf("%d x %d = %d \n", &mult, &i , &ans);
}
return 0;
}
Hi guys, this is a simple code which is supposed to help the user to list the times table for n times. However, i am receiving undefined behaviour and I am quite stumped as to what is wrong with my implementation of my "for" loop.
I am receiving this as my output.
6356744 x 6356748 = 6356736
for n times in my consoles.
I want to ask
Is anything wrong with the logic of my code? (i assume i do have a problem with my code so please do enlighten me)
Would it be better(or even possible) to use pointers to point to the memory addresses of the mentioned variables when i have to change the value of the variables constantly? If yes, how do i go around doing it?
Thanks!
In printf you must provide integers. You are now giving the addresses of integers. So change
printf("%d x %d = %d \n", &mult, &i , &ans);
to
printf("%d x %d = %d \n", mult, i, ans);
and to make the table, replace ans with just mult*i, so:
printf("%d x %d = %d \n", mult, i, mult*i);
You should also check the return value of scanf to check if it has succeeded reading your input:
do {
printf("Please enter a multiple you want to explore.");
} while (scanf("%d", &mult)!=1);
do {
printf("Please enter the number which you would want to multiply this number till.");
} while (scanf("%d", &n)!=1);
The things you see are the values of the variables memory location.
Change your lines inside for loop as below
ans = mult * i;
printf("%d x %d = %d \n", mult, i, ans);
There are some mistakes in your code .
you are using the & operator in print statement which is used to print the address of the variable.
Initiate the loop with the value '1' instead of '0' & execute the loop till 'i' less than equal to 'n'.
instead of using the ans variable outside the loop , use it inside the loop as it evaluate the multiplication result in each iteration of the loop.
#include <stdio.h>
int main()
{
int i;
int mult;
int n;
int ans;
printf("Please enter a multiple you want to explore.");
scanf("%d", &mult);
printf("Please enter the number which you would want to multiply this number till.");
scanf("%d", &n);
for(i = 1; i<=n; i++) {
ans = mult*i ;
printf("%d x %d = %d \n", mult, i , ans);
}
return 0;
}

If statements not working inside while loop

Only the 'strlen' function is being executed by the program.
The if statements inside this while loop do not even work...
#include<stdio.h>
#include<string.h>
#include <ctype.h>
main()
{
char cMessage[100];
int cLow = 0, cUp = 0, cSpec = 0, cSpace = 0, cNum = 0;
printf("Enter your message: ");
scanf("%s", cMessage);
int x = 0;
while(cMessage[x] != 0)
{
x = strlen(cMessage);
printf("Total characters: %d", x);
if(islower(cMessage[x]))
{
printf("\nTotal Lowercase Letters: %d", cLow);
cLow++;
}
else if(isupper(cMessage[x]))
{
printf("\nTotal Uppercase Letters: %d", cUp);
cUp++;
}
else if(isalnum(cMessage[x]))
{
printf("\nTotal Special Characters: %d", cSpec);
cSpec++;
}
else if(isspace(cMessage[x]))
{
printf("\nTotal Lowercase Letters: %d", cSpace);
cSpace++;
}
else if(isdigit(cMessage[x]))
{
printf("\nTotal Lowercase Letters: %d", cNum);
cNum++;
}
}
x++;
}
I cannot figure out the cause of this issue...
What may be the cause of this?
EDIT: So here's the revised code of the program, the only problem that I have now is that the spaces are not being counted. And btw, is there a specific function used to 'count' special characters? I've used 'isalnum' and I realized it was wrong
#include<stdio.h>
#include<string.h>
#include <ctype.h>
#include<conio.h>
main(){
char cMessage[100];
int cLow=0, cUp=0, cSpec=0, cSpace=0, cNum=0;
printf("Enter your message: ");
scanf("%s", cMessage);
int x=0;
while(cMessage[x]){
printf("Total characters: %d", strlen(cMessage));
while(cMessage[x]!=0){
if(islower(cMessage[x])){ cLow++;}
if(isupper(cMessage[x])){ cUp++;}
if(isalnum(cMessage[x])){ cSpec++; }
if(isspace(cMessage[x])){ cSpace++; }
if(isdigit(cMessage[x])){ cNum++; }
x++;
}
printf("\nTotal Lowercase Letters: %d", cLow);
printf("\nTotal Uppercase Letters: %d", cUp);
printf("\nTotal Special Characters: %d", cSpec);
printf("\nTotal Spaces: %d", cSpace);
printf("\nTotal Numbers: %d", cNum);
getch();
}
}
The x = strlen(cMessage); will give you the length of cMessage which is always the index of the last item + 1.
for example if: cMessage = "The" and x = strlen(cMessage) , then:
x = 3
cMessage[0] = 'T'
cMessage[1] = 'h'
cMessage[2] = 'e'
cMessage[3] = NULL terminator // equivalence to 0
Note that there is usually a NULL terminator after the last character.
So as you can see, the while condition is always false after the first pass.
Try to use a separate variable to iterate through cMessage.
Also you need to consider putting variables like cUp++' before the 'printf statements.
A more elegant alternative will be using for statement instead of while.
Also note that isalnum(cMessage[x]) is interfering with if(isdigit(cMessage[x])) so, it is better to use separate if statements and git rid of else if, moreover, if you want to count special characters you have to negates isalnum to be: if(!isalnum(cMessage[x])).
At last your input will not accept sentences (word with spaces between them), so you have to consider replacing:
scanf("%s", cMessage);
with
scanf("%[^\n]s",&cMessage);
You take x as the lenght of your string. So that's one longer then your Array. After the full array is always a 0 to show the program the array is not longer. This way you can never go in the if's
cMessage[x] after x=strlen(cMessage) is always 0. String contains chars from 0 till x - 1, char at post x is 0. Thus any if-condition is false.
I suppose x=strlen(cMessage); is not needed and must be removed, x++ must be three last operator in the loop body, since you want to count chars of different kinds.
printf("Total characters: %zu", strlen(cMessage));
while(cMessage[x] != 0) {
if(islower(cMessage[x])) {
...
}
x++;
}
%d is not proper format for size_t type on 64-bit platform. Read this: How can one print a size_t variable portably using the printf family?

C - Integer throwing out random value?

Currently I am writing a simple program in C that reads in values the user enters in a loop. For some reason, when I initialize the integer a I am given a random value as opposed to the value I specified. Any help would be greatly appreciated
#include <stdio.h>
int main()
{
char sName[10];
int sTime;
int a = 0;
printf("%d", &a);
printf("Please enter the name of your snail: ");
scanf("%s", &sName);
for(a = 10; a < 20; a = a + 1) {
printf("%d", &a);
printf("Please enter the %d time of your snail: ", &a + 1);
scanf(" %d ", &sTime);
}
return 0;
}
Change this:
printf("%d", &a);
to this:
printf("%d", a);
&a is the address of a (and it's of type int*, so %d is the wrong format). a gives you the value of a.
You still need the & in scanf(" %d ", &sTime);; scanf needs the address of sTime so it knows where to store the value.
You're printing the address of a. You don't want the & in there:
printf("%d", a);
You do want the & for scanf() because you need to tell that function where (at what address) to store the value.

C skip a "while" loop?

I have a problem, I tried to write a program to show the whole sum from 1 to 22 and after that, to do 2 while loops. The first one is supposed to perform the sum of some numbers given by the user, as an example: you type 10, 30 and 40 then as you enter a 0 the program sums the first three numbers. Unfortunetly the first while loop is not working. It goes directly to the last while loop where it is supposed to type a decimal numbers like (10.20 30.50 40.55) and after you type 0 again it sum those numbers and add and multipli every entry with 1.19. So far the last loop is working properly, unfortunately the second loop does not, if I move printf and scanf over the while it let me write but just start writing w/o stopping the number I wrote . Thank You in advance!
Here is the code :
#include <stdio.h>
int main()
{
int sum = 0;
int a;
int b;
double i;
double sum1 = 0;
for (a= 0; a <= 22; a++) {
sum = sum + a;
printf("the sum from 1 till 22 : %i\n ", sum);
}
while (b != 0) {
printf("type a number:");
scanf("%i", &b);
sum += b;
printf("%i\n", b);
}
printf("the sum is : %i\n", sum);
while(i !=0) {
printf ("Type a decimal number:");
scanf ("%lf",&i);
sum1 += i*1.19;
printf("%lf\n", i);
}
printf("The decimal summ is: %lf\n",sum1);
return 0;
}
You don't initialise i to any value before entering the loop with
while(i != 0)
i might very well be zero at this point, so your loop won't be entered even once. Initialising i to a non-zero value should fix this particular problem. The same holds for the variable b.
You should turn on warnings in your compiler, so it can show you problems like this one.
The first time the condition of the second while is evaluated, b has undefined value, since it wasn't initialized. The same applies to the third while.
Whether or not both loops are executed is only a question of chance.
Initialize both variables with non-zero values to ensure both whiles are entering. Or use a do-while:
do {
printf("type a number:");
scanf("%i", &b);
sum += b;
printf("%i\n", b);
} while (b != 0);
Don't test b with while, test it after the user enters the number. Then you can use break to exit the loop.
while (1) {
printf("type a number:");
scanf("%i", &b);
if (b == 0) {
break;
}
sum += b;
printf("%i\n", b);
}
while(1) {
printf ("Type a decimal number:");
scanf ("%lf",&i);
if (i == 0.0) {
break;
}
sum1 += i*1.19;
printf("%lf\n", i);
}
Your only issues are initialization: see edits in the code below. (it compiles and runs)
Did you get any compiler warnings for these? If not, you should change your settings so you do.
#include <stdio.h>
int main()
{
int sum = 0;
int a;
int b=-1; //initialize (any non-zero value will work)
double i;
double sum1 = 0;
for (a= 0; a <= 22; a++) {//a initialized in for(...) statement, (this is good)
sum = sum + a;
printf("the sum from 1 till 22 : %i\n ", sum);
}
while (b != 0) { //b Needs to be initialized before using (done above)
printf("type a number:");
scanf("%i", &b);
sum += b;
printf("%i\n", b);
}
printf("the sum is : %i\n", sum);
i=-1; //initialize i to any non-zero value
while(i !=0) {
printf ("Type a decimal number:");
scanf ("%lf",&i);
sum1 += i*1.19;
printf("%lf\n", i);
}
printf("The decimal summ is: %lf\n",sum1);
getchar();
return 0;
}

Resources