Here is my C code:

#include<stdio.h> #include<conio.h> #include<stdlib.h> #include<time.h> const int N = 10; main(){ srand(time(NULL)); int a, b, c, d, i, k, A[N], K[N], j; for(i = 0; i < 10; i++){ A[i] = rand() % 100 - 50; } for(i = 0; i < 10; i++){ printf("%4d", A[i]); } printf("\n"); for(i = 0; i < 10; i++){ if(A[i] < 0){ for(j = 0; j < i; j++){ K[j] = A[i]; printf("%d", K[j]); } } } } 

What is wrong with him, why he ignores the first negative number and repeatedly displays the same

  • Try srand(time(NULL)); - alex-rudenkiy
  • But I have already written this - Elvin
  • hmm some kind of game, and try srand( (unsigned)time( NULL ) ); - alex-rudenkiy
  • the same result :( - Elvin
  • And you just try manually 0..5 put instead of time, see what happens - alex-rudenkiy

1 answer 1

You do something strange when copying a negative number found. You need to separate the copy and output of the new array.

Such an option will work. Run the code in ideone .

 #include<stdio.h> #include<stdlib.h> #include<time.h> const int N = 10; main(){ srand(time(NULL)); int i, j, A[N], K[N]; for(i = 0; i < 10; i++){ A[i] = rand() % 100 - 50; } for(i = 0; i < 10; i++){ printf("%4d", A[i]); } printf("\n"); for(i = 0, j = 0; i < 10; i++){ /* Ссли число мСньшС нуля */ if(A[i] < 0){ /* ΠΊΠΎΠΏΠΈΡ€ΡƒΠ΅ΠΌ Π΅Π³ΠΎ Π² Π½ΠΎΠ²Ρ‹ΠΉ массив */ K[j] = A[i]; /* ΡƒΠ²Π΅Π»ΠΈΡ‡ΠΈΠ²Π°Π΅ΠΌ индСкс для Π½ΠΎΠ²ΠΎΠ³ΠΎ массива */ j++; } } /* Π² этом мСстС j содСрТит Π΄Π»ΠΈΠ½Ρƒ Π½ΠΎΠ²ΠΎΠ³ΠΎ массива */ for(i = 0; i < j; i++) { printf("%4d", K[i]); } } 
  • I mean, how is it? What's the catch? I'm just very interested - alex-rudenkiy
  • @ alex-rudenkiy the problem is not in generating numbers, but in copying. - Mikhail Vaysman
  • What is the problem of copying? - alex-rudenkiy
  • And when you increase the value of j by 1 inside the cycle, you get the following: K [0], then K [1] and so on, do you increase both parameters (i and j) correctly? - Elvin
  • @Elvin i incremented at each iteration, and j only after copying. - Mikhail Vaysman