I'm stuck on how to make a for loop that will alternate increments in a series. For example:
i x
2. 7
3. 12
4. 14
Where x is some combination of i. It first increments by 5, and then by 2 and then back to 5. I've tried using modulus to start an alternating series, but I can't seem to get the number to increase. Any ideas? Thank you.
Does it have to be a for loop? There's still the while loop.
int i = 0;
char switcher = 0; /*in this case it could also be a bool.*/
while(some statement)
{
switch(switcher)
{
case 0:
i+=5;
break;
case 1:
i+=2;
break;
}
switcher++;
if(switcher > 1)
switcher = 0;
//do something
}
You could easily add more different increments to that code.
It'd be best to use a while loop with a flag that keeps track of whether or not you need to increment by 2 or 5.
incrementFlag = true;
while(someCondition)
{
[code...]
if (incrementFlag)
i += 5;
else
i+=2
incrementFlag = !incrementFlag; // Alternate incrementing
}
Related
I have the following pattern to print in the C programming language.
BBBB
BAAB
BAAB
BBBB
I have tried the following code, but it's not working.
My code :
#include <stdio.h>
int main() {
// Write C code here
int i,j;
for(i=1;i<=4;i++)
{
for(j=1;j<=4;j++)
{
if ((i==1&&j>=i)||(i==4&&j<=i)){
printf("%c",65+1);
}
else{
printf("%c",65);
}
}
printf("\n");
}
return 0;
}
However, the pattern I am getting is the following.
BBBB
AAAA
AAAA
BBBB
The problem with your code is your special case will only fire on the first and fourth row. We can see this a little better if we space things out.
if(
(i==1 && j>=i) || // `i==1` only on the first row
(i==4 && j<=i) // `i==4` only on the fourth row
) {
printf("%c",65+1);
}
Every other iteration will use your else block that just prints A.
else {
printf("%c",65);
}
Note: 'A' is much easier to read than 65, and 'B' much easier than 65+1.
There's plenty of ways to do this. Here's one elegant way with a single loop.
We can observe that we want to print BBBB at the start and every third row. If we start iterating at 0 we can do this when i is divisible by 3. 0/3 has a remainder of 0. 3/3 has a remainder of 0. We use the modulus operator % to get the remainder.
for(int i = 0; i < 4; i++) {
if( i % 3 == 0 ) {
puts("BBBB");
}
else {
puts("BAAB");
}
}
This will continue to repeat the pattern if you extend the loop. 6/3 has a remainder of 0. 9/3 has a remainder of 0. And so on.
(You could also start with i=1 and check i%3 == 1, but get used to starting counting at 0; it makes a lot of things easier.)
I'm doing a final project right now and I have the following code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <ctype.h>
int main(void){
int day;
int year;
int month;
int daynum=0;
int days=365;
printf("\nPlease input what year you would like to meet\n");
scanf("%d",&year);
printf("\nPlease input what month you would like to meet\n");
scanf("%d",&month);
printf("\nPlease input what day you would like to meet\n");
scanf("%d",&day);
//Later in the code i have the following loop
int k=month;
do {
k--;
switch (k) {
case 0:
case 2:
case 4:
case 6:
case 7:
case 9:
case 11:
daynum=daynum+31;
printf("\nadded 31");
break;
case 1:
if (days==365) {
daynum=daynum+28;
}
else if (days==366) {
daynum=daynum+29;
}
printf("\nadded 28/29");
break;
case 3:
case 5:
case 8:
case 10:
daynum=daynum+30;
printf("\nadded 30");
break;
default:
printf("\nsomething went wrong");
}
}while(k>=0);
return 0;
}
I've tried essentially the same thing with a while and for loop but every time the only thing that shows up in the console is something went wrong. I even tried checking the value of k before the loop and it says it is equal to month. I've also tried setting k equal to a number and it works just fine with that, but i need it to equal month. I really have no idea whats wrong and any help would be appreciated.
The problem is that you're decrementing k at the beginning of the loop body, but checking it at the end of the loop. So on the last iteration you'll decrement it to -1, print the error message, and then stop the loop.
Change the condition to while(k > 0).
Well, I believe you now know the error as #Barmar wrote.
Anyway I add:
always, I mean always, check for the return of scanf(): there is no point in letting the program go if some of the values are not read. scanf() always returns the number of specifiers read, that things that starts with a single %. In your case it will be 1, 0 or -1.
about this
do {
k--;
switch (k) {
you can always switch(--k) with the same effect.
you could state the purpose of the code and provide at least one test value. If you are trying to get the number of days up to and including the user supplied one, you could have made it clear. I was just guessing.
note that Excel or Google sheets can operate on dates so it is a good free reliable check point.
a small change on the default label, like
printf("\n==> daynum is %d, k is %d and something went wrong\n", daynum, k);
would have print
==> daynum is 365, k is -1 and something went wrong
and it would be very helpful. Far better than just write something went wrong. make your program work for you.
you do not need a switch to compute always the same values. Use a table. And as the only change in days is in February just add the extra day there as we always do...
char days_in_month[] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
days_in_month[1] += ( year % 4 == 0 && year % 100 != 0 ) || year % 400 == 0; // 1 or 0
use the command line for the arguments. It is a bit boring enter the program name and then 3 parameters in 3 lines just to see a resulting number.
Honestly have no idea what was the issue with my code, but i moved this section of code further up and its working as intended now. Somewhere months was getting reset to 0 before the loop despite this being the first time i referenced it besides in printf statements. thank you to #dbush who helped me find out the issue.
I have a question that may be hard to understand -- but I will try my best to explain.
I'm programming the Simon Game in C. This implementation specifically read/writes to a hardware DAQ module that has a 4 LED display, and 4 corresponding toggle switches.
As per the rules of the Game, I've seeded and generated a random sequence of numbers between 0 and 3 (sequence length is arbitrarily 5). In the Game, if the player presses the wrong switch (i.e. blue is shown but you press green), the game ends and restarts.
The way I've set up the Game looks like this:
(I haven't included the code for function "blinkLED" here -- it turns the actual LED on/off.)
void runSimon(void){
int sequence[MAX_SEQ_LEN];
int i;
int count = 0;
// Seeds the random number generator.
srand((unsigned)time(NULL));
// Generate the random LED sequence & store it as an array.
for (i = 0; i < MAX_SEQ_LEN; i++){
sequence[i] = (rand() % NUM_LEDS);
}
// The game begins!
while (continueSuperLoop() == TRUE){
// Loop the game while the sequence length is less than the pre-defined maximum (currently it's 5).
while (count < MAX_SEQ_LEN){
for (i = 0; i <= count; i++){
// Blink the first 'count' LEDs in the sequence, one at a time.
blinkLED(sequence[i], 1, ONE_SEC);
//
//
//THE ISSUE SHOULD BE HERE (!)
//
// Monitors whether or not the player has made a mistake...if so, blink the red LED thrice, then restart the game.
if (digitalRead(sequence[ !i ] == SWITCH_ON)){
blinkLED(LED_1_R, 3, HALF_SEC);
Sleep(3 * ONE_SEC);
continue;
}
// Monitors whether or not the correct switch is being pressed -- waits for it to be released
while (digitalRead(sequence[i]) == SWITCH_ON){}
}
count++;
}
// If 'count' is equal to 'MAX_SEQ_LEN', the green LED blinks 3x to indicate the player has won .
if (count == MAX_SEQ_LEN){
blinkLED(LED_0_G, 3, HALF_SEC);
Sleep(3 * ONE_SEC);
}
}
}
Where I indicated an issue, I'm not sure how the "digitalRead(sequence[ ! i ]" behaves; I need this line to read every switch that's not supposed to be pressed.
I don't think the compiler understands what I'm trying to do here, though -- for example, if the first number in the sequence is 3 (representing the 4th LED), I need to specify that every other number (0, 1, 2) and its corresponding switch should not be pressed.
Would a solution be to store the current number in the sequence, having a set of four TRUE/FALSE flags for each LED, and monitoring the three non-current numbers and their corresp. switches to see if they are pressed?
I'm getting quite frustrated with writing this program. I'm pretty new to programming. Any help is appreciated.
I'm not sure I understand the rules of this game correctly but one thing that jumps out instantly is
digitalRead(sequence[ !i ]
I think you want
!digitalRead(sequence[ i ]
Also, you need to fix your game flow. Right now it's:
1. Light LED.
2. Check if user pressed the right button.
You need to wait for some time before checking a switch or wait for ANY switch to be pressed and see if it's the correct one. So something like this:
1. Light LED.
2. Wait for timeout or ANY switch to be pressed.
3. If timeout: error
4. else: check if switch that was pressed is correct.
In C, ! operator is a unary NOT. When applied to an integer i, it is equivalent to if (i == 0) return 1; else return 0;. Then you are using !i as an index for sequence array, so it will be either sequence[0] or sequence[1], and clearly this is not what you want. Also your == is inside of digitalRead call :)
I would suggest explicitly checking for every other button not to be pressed. Like this:
int isOtherPressed = 0;
for (ledId = 0; ledId < NUM_LEDS; ledId++) {
if (ledId != sequence[i] && digitalRead(ledId) == SWITCH_ON) {
isOtherPressed = 1;
}
}
if (isOtherPressed) {
// restart the game
}
However, I'm suspicious about the whole gameplay you have, but maybe it's just because I don't know how digitalRead works. For example, the way you use continue doesn't seem to stop the game. Maybe you meant break?
I have a matrix which has 1's,-1's and zeros.. say
state=[1; 1; -1; 1; -1; 0; 0; 0; 0; 0; 0; 0; 0; 1; 0; -1; 1; 0; -1.........];
Say -1 is the start of an event and 0 contributes to the length of it when its between (-1 and 1) as -1 remains the start and 1 is the end of event. But when 0 comes after a 1 that means it doesn't have any value to it as the event ended recently; can't take that into consideration.
So I need to get the number of such events that happened and also lengths of those events in the entire matrix for such events so my output would be
result=[2 10 2........]
and need the no of such events.
And in the above case I would exclude my first two indices which are 1's that doesn't contribute to anything.
It sounds simple but its been a while I got back to matlab. This is what I tried but it fails as it takes the zeros in between 1 and -1 as it should be excluded:
result=[find(state==-1)-find(state==1)];
which is wrong.
Your help is appreciated.
Follow these steps:
Find all starts and all ends.
For each start, find the end immediately after it.
Subtract each end found in step 2 minus each corresponding start, and don't forget to add 1.
The number of events is immediate from that.
The interesting part is step 2. bsxfun tests, for each combination of start and end, if the start is less than the end. Then the second output of max gives the index of the first true value for each start, if any; and its first output tells you if there really was some true value, (that is, if the found index is valid).
starts = find(state(:)==-1); % // step 1
ends = find(state(:)==1); % // step 1
[valid, next_end] = max(bsxfun(#lt, starts.', ends)); %'// step 2
result = ends(next_end(valid)) - starts(valid) + 1; % // step 3
number = numel(result); % // step 4
#include <stdio.h>
int main(){
int i = 0;
do {
i++;
printf("In while loop\n");
} while (i < 3);
}
output:
In while loop
In while loop
In while loop
Why the printf statement is executed three times?
As soon as the loop starts the value of i becomes 1, so the loop should run 2 times only but it is running 3 times, how?
Pseudo code:
i = 1
=> In while loop
i = 2
=> In while loop
i = 3
=> In while loop
exit from loop
The condition is checked only at the end, after printf.
The do-while loop tests the condition at the end, so the loop in your example will be executed 3 times with i = 1, 2, 3.
Your condition(i < 3) is checked at the end of the loop.
1st pass : i = 1 => "In while loop" printed => (i < 3) satisfied.increment i
2nd pass : i = 2 => "In while loop" printed => (i < 3) satisfied.increment i
3rd pass : i = 3 => "In while loop" printed => (i < 3) not true.exit from loop
Hope this helps!
The first time you hit the while after the first printf i is 1. The loop continues.
The second time you hit the while after the second printf i is 2. The loop continues.
The third time you hit the while after the third printf i is 3. The loop now ends.
You have hit printf three times.
The loop is starting with 'i=0' and then entering the loop with "i++" and becoming 'i=1' then the condition is checked over "i" so in the last loop when 'i=3' the loop is executed and then checked for "i<3".So the loop is repeated thrice.
The reason is u are using post increment.
{
int i = 0;
do {
i++; //first time - 0,second time - 1,third time - 2
printf("In while loop\n");
} while (i < 3);
}
Use pre increment or while instead of do-while to see the difference