I am very new to C programming language, and I ran into a problem.
I need to write code that displays the number of times the numbers 3 and 6 appear consecutively
in a array[100] with random integers.
I have tried writing my code in different ways, however, whenever I run the code it doesn't execute along with the rest of the code. Here are my attempts.
Created another for loop and an if condition inside:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 100
#define MAX 990
#define MIN 100
int main(void) {
int index;
int array[SIZE];
int q;
srand(time(NULL));
for (index = 0; index < SIZE; index++){
array[index] = (rand() % (MAX - MIN + 1) + MIN) / 10;
printf("Índice [%i]: %i\n", index, array[index]);
}
for(index = 0; index < SIZE; index++){
if (array[index] == 3 && array[index + 1] == 6){
q++;
printf("Relatório: 3 e 6 foram encontrados consecutivamente %i vezes.", q);
}
}
return 0;
}
Removed the for loop and left the if statement alone:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 100
#define MAX 990
#define MIN 100
int main(void) {
int index;
int array[SIZE];
int q;
srand(time(NULL));
for (index = 0; index < SIZE; index++){
array[index] = (rand() % (MAX - MIN + 1) + MIN) / 10;
printf("Índice [%i]: %i\n", index, array[index]);
}
if (array[index] == 3 && array[index + 1] == 6){
q++;
printf("Relatório: 3 e 6 foram encontrados consecutivamente %i vezes.", q);
}
return 0;
}
I added the if condition in the first for loop, which was the only one to be executed when I clicked run:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 100
#define MAX 990
#define MIN 100
int main(void) {
int index;
int array[SIZE];
int q;
srand(time(NULL));
for (index = 0; index < SIZE; index++){
array[index] = (rand() % (MAX - MIN + 1) + MIN) / 10;
printf("Índice [%i]: %i\n", index, array[index]);
if (array[index] == 3 && array[index + 1] == 6){
q++;
printf("Relatório: 3 e 6 foram encontrados consecutivamente %i vezes.", q);
}
}
return 0;
}
What am I doing wrong and why didn't any of the solutions above work? How can I make it work?