I'm a beginner at C and can't find the answer to this anywhere because I don't know how to word it so I'm just going to ask a question.
I understand basic looping but what I want to do is make a small program where the output is this using only loops:
12345
1234
123
12
1
my code so far
int x;
int y = 1;
for (x=1; x<=5; x++)
{
while(y<=5)
{
printf("%d", y);
y++;
}
}
this is what I have so far and don't know where to go next, if anyone could help I'd be grateful.
Close. Your outer loop needs to count down, not up, and your inner loop needs to count from 1 to x.
int x, y;
for (x=5; x>=1; x--)
{
for (y=1;y<=x;y++)
{
printf("%d", y);
}
printf("\n");
}
This is another solution using just a FOR loop with Integer Division. Try:
#include <stdio.h>
int main(void){
int n= 12345, i;
for(i=n;i>0;i/=10){
printf("%d\n",i);
}
return 0;
}
You have to see the pattern you want and apply it in the loops to get it.
You need the output 12345 1234 123 12 1. So, the first iteration should start at 1 and go till 5, second should start at 1 and go till 4, and so on..
So, the outer loop should give the end limits for the inner loop, and the inner one should always start with 1.
Try
for (x=5; x>=1; x--)
{
y = 1; // because the number always start with 1
while(y<=x)
{
printf("%d", y);
y++;
}
printf("\n"); //to go to next line
}
For fun: another approach that simply divides each loop. But use best answer
int main(void) {
int x = 12345;
do {
printf("%d\n", x);
x /= 10;
} while (x);
return 0;
}
Output
12345
1234
123
12
1
Another solution is to use integer division and use one single loop:
int x = 12345;
// repeat this loop as long as x != 0
while (x)
{
printf("%d\n", x);
x /= 10; // x = x/10;
}
You need to make 2 changes to your outer loop in order to get the expected output.
for (x=1; x<=5; x++) should be for (x=1; x<=5; x--) because your program will count up to 5 the first time, 4 the second time, 3 the third time, etc..
You should include printf("\n") so a new line is printed after each sequence is output.
You need to make 1 change to your inner loop as well:
Instead of y <= 5 you should say y <= x because x will always be equal to the last number that you want to print since you're decrementing it in the outer loop.
Related
I am trying to create a Dice Roll game where the user can roll up to 6 dice at a time. I am attempting to accomplish this by integrating pointers into my code. I am getting an output, with the desired amount of rolls as given by the user, but the output is incorrect. It is printing a pattern instead of printing random numbers. Any help is appreciated.
How many dice would you like to roll?
user input: 4
output: 3 0 3 0
How many dice would you like to roll?
user input: 5
output: 4 0 4 0 4
#include <stdio.h>
#include <stdlib.h>
void tossDie(int []);
int main() {
int diceArray[6] = { 0 };
int num = 0;
int x;
do {
printf("\nHow many dice would you like to roll? Please enter here: ");
scanf_s("%d", &num);//user enters amount of dice they want to roll)
if (num < 1 || num > 6) {
printf("\n\nPlease enter a number between 1 and 6.\n\n");
}
} while (num < 1 || num > 6);
tossDie(diceArray);
//print dice roll numbers
for (x = 0; x < num; x++) {
printf("%d ", diceArray[x]);
}
return 0;
}
void tossDie(int numbers[]){
int randomNum;
int x;
srand(time(NULL));
randomNum = (rand() % 6) + 1; //random # between 1 - 6
for (x = 0; x < 6; x++){
numbers[x] += randomNum;
x++;
}
};
Move srand(time(NULL)); to main(). Only needed once.
Only call x++ only per loop, not twice, to assigned all 6 elements of the array.
Move randomNum = (rand() % 6) + 1; to inside for loop to get different values.
Check return value of scanf_s("%d", &num); against 1, before using num.
Tip: Use an auto-formatter to save time and improve code presentation.
Design: I'd expect tossDie(int numbers[]) to also receive a num to indicate numbers[] width.
Before I answer, please note that I don't program in C, so there may be some language-specific things that I am missing.
In your tossDie() function, you set the value of randomNum once, but don't reassign it after that. Therefore, your output should return the same number for all values in the array, like such:
Input: 5
Output: 3 3 3 3 3
To fix that, you should put the variable declaration in the for loop (if you want to use a variable at all).
Additionally, you initialise the random variable every time you run the method. Instead, you should declare it once, in the main method.
Also, there's a little issue in this block of code:
for (x = 0; x < 6; x++){
numbers[x] += randomNum;
x++;
}
};
You increase x twice in here: both in the first line and the third line. Instead, you should delete the x++ in the third line and have just the x++ in the first line.
Let me know if you have further questions or if there are still problems.
Please could someone help with this - I am completely new to coding and just started the cs50 course, I really am struggling to understand most of the course. I've scraped through this lab but I keep getting this error message "population.c:22:17: error: variables 'y' and 'x' used in loop condition not modified in loop body [-Werror,-Wfor-loop-analysis]
for (n = 0; y < x; n++)". I've tried to look through similar questions on here and apply those solutions, none of which have worked. Could someone please help?
My code is below
#include <cs50.h>
#include <stdio.h>
int main(void)
{
// TODO: Prompt for start size
int x,y,n ;
do
{
x = get_int("Start size: ");
}
while ( x < 9);
// TODO: Prompt for end size
do
{
y = get_int("end size: ");
}
while (y < x);
// TODO: Calculate number of years until we reach threshold
for (n = 0; y < x; n++)
{
n = x + x/3 - x/4;
}
printf("Years: %i", n);
// TODO: Print number of years
}
for (n = 0; y < x; n++)
{
n = x + x/3 - x/4;
}
This loop keeps executing while y is less than x. However, the only variable that changes inside the loop is n. x and y remain unchanged.
So either this loop will never run, or it will run forever.
It would really help to know what the goal of the exercise is.
What we know from what you’ve posted is that the initial value of x must be greater than or equal to 9 and that the initial value of y must be greater than or equal to x.
Based on that alone, we know your loop will never execute since y < x will not be true. Based on the calculation involving x and the comment about reaching a threshold, I strongly suspect your loop is supposed to be written as
for ( n = 0; x < y; n++ )
{
x = x + x/3 - x/4;
}
If you input even numbers, only the odd numbers will be printed until it reaches 0. (0 will not be printed). For example, if you input 10, the output would be 9, 7, 5, 3, 1.
This is what I came up with. I'm wondering what should I decrement x by to get the desired output.
int x;
scanf("%d", &x);
while (x >= 0) {
printf("%d", x);
x = x - 2;
}
I'm wondering what should I decrement x by to get the desired output.
Subtracting 2 is fine, as long as you always start from an odd number. So you could change the loop into something like this:
for ( int i = x % 2 ? x : x - 1; // Is x odd? good.
// Otherwise, start from the previous one.
i > 0;
i -= 2 ) {
printf("%d\n", i);
}
int x, n;
printf("Give N: ");
scanf("%d", &n);
printf("odd numbers from 1 to %d are: \n", n);
x=n;
while(x<=n && x>0)
{
if(x%2!=0)
{
printf("%d\n", x);
}
x--;
}
return 0;
}
Your code was almost correct (indeed, it is a pity that you have selected as the correct question such a bad response) I will show you where is your error:
int x;
scanf("%d", &x);
if (x % 2 == 0) /* if the number is even */
x = x - 1; /* decrement it to convert it in an odd number */
while (x >= 0) {
printf("%d", x);
x = x - 2;
}
The thing is that you start your question with exactly that assert (if you input even numbers...)
Another problem is that you don't say what should happen when you introduce an odd number. Anyway, the code printed it, and all the odd numbers until we reach 0.
Why your code is better than the selected one? because your code only wastes time in the loop with the valid results, and doesn't get into the loop to decide that it has nothing to do. This saves a lot of loop executions (almost half of them) which, if your number is very large, can do your program a lot more efficient.
I'm trying to debug my program with a nested loop to print out all the values in a 2d array. I was getting some unexpected behavior from the loop so i commented out some things and added a simple printf.
`int u = 0;
int y = 0;
char m = 'm';
for (u; u < 12; u++)
{
printf("\n");
for (y; y < 5; y++)
{
//transition[u][x] = &m;
printf("o"); //this nested loop isnt working????
//printf("%c", *transition[u][y]);
}
}`
Clearly this should print 12 rows of 5 'o's. But instead it is only printing out one row of 5 'o's followed by 11 newlines.
Edit: Thanks a lot! Silly mistake, I failed to realize that y would not set itself back to 0 on the second run through the loop. I guess overlooked this because I'm too used to Java initializing and setting the increment variable within the loop statement.
Your for initial statement doesn't mean anything:
for (y; y < 12; y++)
The first statement is just y. Which has no side effects so you are not actually resetting y to 0 after first innermost loop. So from next iteration of outer loop, y == 5 and the inner loop is not executed at all.
You should do
for (y = 0; y < 12; y++)
You are not resetting y on your inner loop; try for (y = 0; y < 5; y++).
This will reset y at the beginning of each loop.
p.s. This is really more of a code review question
By looking at your question i assume that you are trying to print 5 o's in a line with 12 o's.
try this
for(u=0;u<12;u++)
{
for(y=0;y<5;y++)
{
printf("o");
}
printf("\n");
}
I am trying to understand the for loop better. I have the following variables:
x = 1
y = 10
I want to increment x and double it ten times with a for loop to have the following output: 1, 2, 4, 8, 16, etc.
This is what I have, but it is not quite doing the trick:
int x = 1;
int y = 10;
for (int i = 0; i < y; i++)
{
x *= 2;
}
printf("%d\n", x);
Do I need another variable to do this?
It looks fine to me. If you want it to print at each iteration, you need to move the printf into the loop.
Also, your code will only work in C99 or with GCC's default extensions since you have int i inside the for loop.
If you want it to display a running count then you should place printf inside the for-loop, so it gets executed with each iteration.
Do I need another variable to do this?
No. You could actually remove a variable - y. It is unneeded and you can specify 10 directly in the loop's conditional:
int i = 0;
int x = 1;
for (i = 0; i < 10; i++)
{
x *= 2;
printf("%d\n", x);
}
I want to increment x and double it ten times with a for loop to have the following output: 1, 2, 4, 8, 16, etc.
Your example contradicts your requirement. Incrementing an integer and doubling it would look produce 1, 4, 6, 8, 10, 12, 14...n. They are simply multiples of two. Your example produces powers of two, i.e.,
int x;
for( x = 0; x < 10; ++x )
{
printf("%d\n", pow(2, x) );
}
for (int i = 0; i < y; i++)
{
x *= 2;
printf("%d\n", x);
}
Think you want the printf statement inside the for loop... between the { and the }.
int x = 1;
int y = 10;
int i = 0;
int main() {
for(i = 0; i < y; i++) {
x *= 2;
printf("%d\n", x);
}
return 0;
}
Output:
2
4
8
16
32
64
128
256
512
1024
your answer contradict with your source code,if you want to print 1,2,4,8,16,... you will get first element 2, because you are multiplying every iteration 2 times than its value, you do not need to use extra variable,moreover you can remove y,put directly 10 and use printf statement inside {}.hope it will help
if you know that you have to increment it for only 10 times. Then why to use extra variable ? use this....
for(x = 1; x<=1024; x*=2)
{
printf("%d ",x);
}