Advertisement
tdulik

C Random Number Generator

Nov 24th, 2020 (edited)
488
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.32 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. void printArray(int * a, int size) {
  5.     for (int i=0; i<size; i++) {
  6.         printf("%d", a[i]);
  7.         if (i==size-1) putchar('\n');
  8.         else printf(", ");
  9.     }
  10. }
  11. int product (const int * v1, const int * v2, unsigned int size) {
  12.     int result=0;
  13.     for (unsigned i=0; i<size; i++) {
  14.         result = result + v1[i]*v2[i];
  15.     }
  16.     return result;
  17. }
  18. int main(int argc, char * argv[])
  19. {
  20.     srand(time(NULL));
  21.     int size=2;
  22.     if (argc>1) {
  23.         int a=atoi(argv[1]);
  24.         if (a>0) size=a;
  25.     }
  26.     int * array1, * array2;
  27.  
  28.     int status;
  29.     do {
  30.         array1=malloc(size * sizeof(int));
  31.         array2=malloc(size * sizeof(int));
  32.         if (array1 == NULL || array2==NULL) {
  33.             fputs("Memory allocation error!", stderr);
  34.             return EXIT_FAILURE;
  35.         }
  36.         for (int i=0; i<size; i++) {
  37.             array1[i] = rand() % 200 - 100;
  38.             array2[i] = rand() % 200 - 100;
  39.         }
  40.         //printArray(array1, size);
  41.         //printArray(array2, size);
  42.         printf("Scalar product= %d\n", product(array1, array2, size));
  43.         puts("Let's try again - enter a new size!");
  44.         status = scanf("%d", &size);
  45.         free(array1);
  46.         free(array2);
  47.     } while (status>0);
  48.     return 0;
  49. }
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement