Rejack

[Lec. #7] Exc. 1

Mar 12th, 2024 (edited)
597
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.88 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h> // must use to use malloc or the program will crash
  3.  
  4. void inputArray(int* arr, int n);
  5. void printArray(int* array, int n);
  6.  
  7. int main()
  8. {
  9.     printf("How many numbers do you want:\n");
  10.  
  11.     int input; scanf_s("%d", &input);
  12.  
  13.     if (input <= 0) {
  14.         printf("Invalid input. Please enter a positive number.\n");
  15.         return 1;
  16.     }
  17.    
  18.     int *arr = malloc(input * sizeof(int));
  19.    
  20.     if (arr == NULL)
  21.     {
  22.         printf("Memory allocation failed.\n");
  23.         return 1;
  24.     }
  25.  
  26.     inputArray(arr, input);
  27.     printArray(arr, input);
  28.  
  29.     free(arr);
  30.     return 0;
  31. }
  32.  
  33. void inputArray(int* arr, int n)
  34. {
  35.     printf("Enter %d integers\n", n);
  36.  
  37.     for (int i = 0; i < n; i++) {
  38.         scanf_s("%d", &arr[i]);
  39.     }
  40. }
  41.  
  42. void printArray(int* arr, int n)
  43. {
  44.     printf("\nValues are: ");
  45.  
  46.     for (int i = 0; i < n; i++) {
  47.         printf("%d%s", arr[i], (i == n - 1) ? "." : ", ");
  48.     }
  49.  
  50.     printf("\n\n");
  51. }
Advertisement
Add Comment
Please, Sign In to add comment