c - Nested for loop array random numbers -
so trying print out 7 random numbers , loop should not print out duplicates. when trying debug seems don't in nested loop if statement is.
i memory value printed out , random numbers duplicated.
i believe there wrong in 2nd nested loop cant figure out what, appreciate if can see issue , explain me what's happening nested 2nd loop, step step.
#include <stdio.h> #include <time.h> #define size 35 int main() { int number[size]; srand(time(null)); (int = 1; < 7; i++) { number[i] = rand() % 35 + 1; (int j = 0; j > i; j++) { if (number[i] == number[i]) printf("%d\n", number[i]); i--; } } (int = 0; < 7; i++) { printf("%d\n", number[i]); } getchar(); return 0; }
for starters loop
for (int j = 0; j > i; j++) will executed never because j initialized such way less i.
the program can following way
#include <stdlib.h> #include <stdio.h> #include <time.h> #define size 35 int main(void) { int number[size]; int n = 7; int = 0; srand( ( unsigned int )time( null ) ); while ( < n ) { int value = rand() % size + 1; int j = 0; while ( j < && number[j] != value ) j++; if ( j == ) number[i++] = value; } ( = 0; < n; i++ ) printf( "%d ", number[i] ); putchar( '\n' ); getchar(); return 0; } its output might be
10 21 16 17 26 25 34
Comments
Post a Comment