I have been trying to solve the problem set 1 in CS50, language C. I've come to this point, but I got stuck in here. I want my code to ask for a new input while(n>=9 || n<=0) but it ends there, instead of asking for a new input. I have already tried return n; but it didn't work at all. You can see the console and the results.
When I asked my code to return 0; I thought it would be asking for a new input. But as it can be seen, it ended up. What I want is it to ask for a new input, instead of stop working.
This is my first time and post in here, so I hope I have described my problem good enough.
#include <stdio.h>
#include <cs50.h>
int main(void)
{
int n = get_int("Number: ");
while(n>=9 || n<=0)
{
return 0;
}
int i;
for(i=0;i<n;i++)
{
int a;
for(a=n-1;a>i;a--)
{
printf(" ");
}
int y;
for(y=0;y<=i;y++)
{
printf("#");
}
printf("\n");
}
}
As others suggested, return 0 is an action that terminates the current function you are in, and returns said value. I don't know what is your level of knowledge of C, I'll try to put less informations possible here. Just know that if you write return inside your main(){} block, the program will ignore all the following code and end the program if that return is executed.
Now as to how to get your desired result
I want my code to ask for a new input while(n>=9 || n<=0)
it seems you just need to put your statement inside the while loop:
int n=0;
while (n>=9 || n<=0)
{
n = get_int("Number: ");
}
in this case you need to declare int n outside the loop since you will use it later. (I initialized it as 0 to let the program enter the loop).
If you have studied and are able to use "do while" loops, it may be your best choice here. If your program needs to ask for input, and keep asking until input is no longer in the range (n >= 9 || n <= 0) you might want to try
int n=0;
do
{
n = get_int("Number: ");
} while (n>=9 || n<=0)
This will execute the block of code once for sure, then checks if the while condition is met and loops again. The outcome is you get the statement executed once and then until the condition is no longer met.
Put your code inside while loop to ask it whenever (n >= 9 || n <= 0) because right now whenever n is greater or equal 9 or less or equal 0 your your program will end because return 0 ends actual function and in your case it is main() function
Related
My professor wants use to ONLY use while loops and call 2 different functions, which I have done. I am really stuck on how to tweak this so that if I put in, say, 16, that it will list 16 to 0 on separate lines, as well as 0 to 16 again on separate lines. I can do this with recursion very well for some reason, but without being able to do that, I am lost on how to make this work.
My computing class is learning with C language, so that is what my code is written in.We are also not required to validate input and are under the assumption that the user is entering valid input (a positive integer). Any tips are well appreciated! Thank you.
#include <stdio.h>
void loop_down_to_zero(int number);
void loop_up_to_int(int number);
int main(int argc, char* argv[])
{
printf("please enter a positive integer:");
int number;
number = ("%d" >= 0);
loop_down_to_zero(number);
loop_up_to_int(number);
scanf("%d", &number);
printf("****\n");
return 0;
}
void loop_down_to_zero(int number)
{
while ( number > 0 )
{
loop_down_to_zero(number - 1);
printf("\n%d", number-1);
}
}
void loop_up_to_int(int number)
{
while ( number >= 0 )
{
loop_up_to_int(number+ 1);
printf("%d\n", number+1);
}
return;
}
This is not C
number = ("%d" >= 0);
At least not any meaningful C.
Replace it by the actual input-reading a few lines later,
scanf("%d", &number);
So that you have a meaningful number for the calls to the functions.
That should solve you immediate blocking point.
Then have a look at the hint at your next problem, provided as a comment by arvind:
"Also your number is positive and you're incrementing it so, while ( number >= 0 ) doesn't make any sense." You probably want something including (current_number <= number).
Then for a recursion solutin use if instead of while.
Then to get you started on a non-recursive solution, actually change within the loop body the variable you are testing inside the loop condition;
otherwise you have a guaranteed endless loop killing your programs functionality.
(I intentionally do not give a complete solution, according to the compromise described here, How do I ask and answer homework questions? The asker-side of which OP has well honored in my opinon.)
I'm trying to output the same amount of printf statements in both loops and i have to use for and while . Unfortunately i get a endless loop for my second loop. What I'm i doing wrong in my second loop?
#include <stdio.h>
#define _CRT_SECURE_NO_WARNINGS
int main()
{
int x,c,v,b;
printf("Please enter a number between 1 and 25 \n");
scanf_s("%d",&x,&c);
for (x != 0; x--;)
{
printf("I'd rather be doing something else \n");
}
while (c!=0 ) {
printf("Programming is easy");
c--;
}
}
scanf_s("%d",&x,&c);
in this scanf you are getting only one value.
Here variable c is getting some garbage value and because of that it may be running for a long time which you are thinking as endless loop.
Use
scanf_s("%d %d",&x,&c);
As per as for loop syntax.
for(variable initialization; condition; variable update)
in your code you have already having value of variable x.
Condition checking x != 0
Variable update x--
so it should have to be
for( ; x != 0; x--)
EDIT:
How would i make the user prompt to enter a series of numbers until the user enters a -1 to stop.?
Simple code you can use is.
scanf("%d,&a);
while(a != -1)
{
//do work here
//
//
//-----
scanf("%d,&a);
}
I'm just starting learning C but I really don't know what am I doing wrong. I wrote this code, and it was supposed to stop reading numbers when it receives a negative number. I have wasted a lot of time trying to figure out what it is wrong, and I still don't know what it is.
#include<stdio.h>
int main(){
const int qtd = 3;
float ent[qtd];
int i = qtd;
printf("Digite os numeros\n");
do{
scanf("%f", &ent[i]);
i--;
}while (ent[i] >= 0 && i >= 1);
printf("\n\n\n\nPressione 'Enter' para sair");
fflush(stdin);
getchar();
return 0;
}
The problem is with the index of ent that you check for being negative. It's ent[i], but it is after i has been decremented, so you are reading the location that has not been written yet by scanf.
To fix the problem, change the code to use the prior location, i.e.
do {
...
} while (ent[i+1] >= 0 && ...);
There are several other problems with your code, all coming from the assumption that array indexes start at 1. In C, however, the initial index is zero, not one, so the correct check should be
do {
...
} while (ent[i+1] >= 0 && i >= 0);
In addition, i should be initialized to int i = qtd-1; to avoid writing past the end of allocated array.
What I want to do is reverse a string of numbers that the user enters. what happens is it compiles and runs till i hit enter after the scanf. then I get some Microsoft runtime error... what's going wrong???
NOTE: this is homework, but i've got the logic figured out. what baffles me is this error.
#include <stdio.h>
int main()
{
unsigned int giveStr = 0;
char* charIt;
printf("Enter a number to be reversed.\t");
scanf("%d", &giveStr);
fflush(stdin);
sprintf(charIt, "%d", giveStr);
revStr(giveStr);
getchar();
return 0;
}
revStr(unsigned int n)
{
char buffer[100];
int uselessvar, counter = 0;
for (; n > 0;)
{
uselessvar = sprintf(&buffer[counter], "%d", n);
counter++;
}
for (counter = 0; counter > 0;)
{
printf("%c", buffer[counter]);
counter--;
}
return 0;
}
EDIT: flushing stdin for newlines :/ and also image here just not with that program. with mine.
You are trying to access memory which is not allocated in:
sprintf(charIt, "%d", giveStr);
Change char* charIt; to char charIt[50]; and all should be well (well, at least the segmentation fault part)
Also... pass charIt to revStr, as charIt contains the string with our number.
Then, a simple for loop in revStr will do the trick (what was the purpose of the second one, anyway?)
void revStr(char *giveStr)
{
int counter;
for (counter = strlen(giveStr)-1; counter >= 0; counter--)
{
printf("%c", giveStr[counter]);
}
printf("\n");
}
This will print each char our char representation has from the last one till the first one. You should read more on for loops.
For your home work problem, if you have the K&R book, turn to section 3.5 and read it thoroughly.
Note the functions reverse() and itoa(). They should give you a pretty good idea on how to solve your problem.
How does your program get out of the for (; n > 0;) loop? Won't counter simply increase until you get a bus error?
ED:
Respectfully, I think the claim that "i've got the logic figured out" is a little optimistic. :^) Doubtless someone will post the way it should have been done
by the time I'm done writing this, but it's probably worth drawing attention to what went wrong (aside from the memory allocation problems noted elsewhere):
Your first loop, "for (; n > 0;)", is strange because you're printing the entire number n into the buffer at counter. So why would you need to do this more than once? If you were selecting individual digits you might, but you're not, and obviously you know how to do this because you already used "sprintf(charIt, "%d", giveStr);". [Aside: giveStr isn't a great name for an unsigned integer variable!]
Your second loop also has strange conditions: you set counter to 0, set the condition that counter > 0, and then decrease counter inside. This obviously isn't going to loop over the characters in the way you want. Assuming you thought the first loop was character-by-character, then maybe you were thinking to loop down from counter-1 to 0?
So I have only ever programmed in c++, but I have to do a small homework that requires the use of c. The problem I encountered is where I need a loop to read in numbers separated by spaces from the user (like: 1 5 6 7 3 42 5) and then take those numbers and fill an array.
the code I wrote is this:
int i, input, array[10];
for(i = 0; i < 10; i++){
scanf("%d", &input);
array[i] = input;
}
EDIT: added array definition.
any suggestions or hints would be very highly appreciated.
Irrespective of whatever is wrong here, you should quickly learn to NEVER write code that does not check the return value from any API call that you make. scanf returns a value, and you have to be interested in what it says. If the call fails, your logic is different, yes?
Perhaps in this case it would tell you what's going wrong. The docs are here.
Returns the number of fields
successfully converted and assigned;
the return value does not include
fields that were read but not
assigned. A return value of 0
indicates that no fields were
assigned.
This code working good.
If your numbers is less than 10, then you must know how many numbers is before you start reading this numbers, or last number must be something like 0 to terminate output then you can do while(true) loop, but for dynamically solution you must read all line into string and then using sscanf to reading numbers from this string.
You need the right #include and a proper main. The following works for me
#include <stdio.h>
int main(void) {
/* YOUR CODE begin */
int i, input, array[10];
for (i = 0; i < 10; i++) {
scanf("%d", &input);
array[i] = input;
}
/* end of YOUR CODE */
return 0;
}
i'm not a c programmer but i can suggest an algorithm which is to use scanf("%s",&str) to read all the input into a char[] array then loop over it and test using an if statment if the current char is a space, if it is then add the preceeding number to the array