Untitled
unknown
c_cpp
9 months ago
2.8 kB
5
Indexable
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <locale.h>
#include <string>
#include <iostream>
const int N1 = 5;
const int N2 = 5;
void fill_array(int* arr, int size)
{
for (int i = 0; i < size; i++)
{
arr[i] = rand() % 100 - 50;
}
}
int* find_last_negative(int* arr, int size)
{
int* last_negative = NULL;
for (int i = 0; i < size; i++)
{
if (arr[i] < 0)
{
last_negative = &arr[i];
}
}
return last_negative;
}
double find_avg(int* start, int* end)
{
double sum = 0;
int count = 0;
for (int* ptr = start; ptr <= end; ptr++)
{
sum += *ptr;
count++;
}
return (count > 0) ? sum / count : 0;
}
void print_array(int* arr, int size)
{
for (int i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}
int main()
{
setlocale(LC_ALL, "RU");
srand(time(NULL));
int A[N1], B[N2];
fill_array(A, N1);
fill_array(B, N2);
int* last_neg_A = find_last_negative(A, N1);
int* last_neg_B = find_last_negative(B, N2);
double avg_A = (last_neg_A != NULL) ? find_avg(last_neg_A + 1, &A[N1 - 1]) : 0;
double avg_B = (last_neg_B != NULL) ? find_avg(last_neg_B + 1, &B[N2 - 1]) : 0;
int choice;
printf("select an action:\n");
printf("1. show arrays A and B\n");
printf("2. show the last negative elements in arrays A and B\n");
printf("3. show avg value of the second part of arrays A and B\n");
printf("0. exit\n");
while (1)
{
printf("enter the action number: ");
scanf_s("%d", &choice);
switch (choice)
{
case 1:
printf("array A: ");
print_array(A, N1);
printf("array B: ");
print_array(B, N2);
break;
case 2:
{
std::string mes_A = "the last negative element in the array is A: ";
std::string mes_B = "the last negative element in the array is B: ";
std::cout << (last_neg_A ? mes_A + std::to_string(*last_neg_A)
: "there are no negative elements in array A.") << std::endl;
std::cout << (last_neg_B ? mes_B + std::to_string(*last_neg_B)
: "there are no negative elements in array B.") << std::endl;
break;
}
case 3:
printf("avg value of the second part of the array A: %.2f\n", avg_A);
printf("avg value of the second part of the array B: %.2f\n", avg_B);
break;
case 0:
printf("exiting\n");
return 0;
default:
printf("wrong choice, try again..\n");
}
}
return 0;
}Editor is loading...
Leave a Comment