IZP/Cviko2_2/main.c

104 lines
2.2 KiB
C
Raw Permalink Normal View History

2024-09-26 22:20:42 +02:00
#include "types.h"
#include <stdio.h>
#define ARRAY_LENGTH 5
#define MERGED_ARRAY_LENGTH 2 * ARRAY_LENGTH
int* ask_for_numbers(){
static int p[ARRAY_LENGTH];
for (int i = 0; i < ARRAY_LENGTH; ++i) {
printf("Enter number (%d/%d):\n",i+1,ARRAY_LENGTH);
scanf("%d",&p[i]);
}
return p;
}
void read_print_array_reverse() {
//TODO 1. Read an array of numbers of length ARRAY_LENGTH from stdin.
int* p = ask_for_numbers();
//TODO 2. Print read array in reversed order to stdout.
for (int i = ARRAY_LENGTH - 1; i >= 0; --i) {
printf("%d ",p[i]);
}
return;
}
void read_print_array_max() {
int* p = ask_for_numbers();
//TODO 2. Find maximum value and print it to stdout.
int max = p[0];
for (int i = 1; i < ARRAY_LENGTH; ++i) {
if(p[i] > max){
max = p[i];
}
}
printf("The max of the numbers entered is %d",max);
return;
}
void read_print_array_avg() {
//TODO 1. Read an array of numbers of length ARRAY_LENGTH from stdin.
int* p = ask_for_numbers();
//TODO 2. Calculate average value and print it to stdout.
int all = 0;
for (int i = 0; i < ARRAY_LENGTH; ++i) {
all += p[i];
}
printf("The average value of the array is %.2f",(double)all/ARRAY_LENGTH);
return;
}
void read_print_array_merge() {
//TODO 1. Read 2 arrays of numbers, each of length ARRAY_LENGTH from stdin.
printf("ARRAY 1\n");
int* p = ask_for_numbers();
printf("ARRAY 2\n");
int* q = ask_for_numbers();
//TODO 2. To 3rd array of length MERGED_ARRAY_LENGTH copy first and
//second arrays respectively and resulting third array print to stdout.
int m[MERGED_ARRAY_LENGTH];
for (int i = 0; i < MERGED_ARRAY_LENGTH; ++i) {
if(i < ARRAY_LENGTH){
m[i] = p[i];
}
else{
m[i] = q[i-ARRAY_LENGTH];
}
}
for (int i = 0; i < MERGED_ARRAY_LENGTH; ++i) {
printf("%d ",m[i]);
}
printf("\n");
return;
}
#ifndef TEST_BUILD
int main(int argc, char *argv[]) {
printf("\n--read_print_array_reverse--\n");
read_print_array_reverse();
printf("\n--read_print_array_max--\n");
read_print_array_max();
printf("\n--read_print_array_avg--\n");
read_print_array_avg();
printf("\n--read_print_array_merge--\n");
read_print_array_merge();
return 0;
}
#endif