- Write the function int READDIM() that reads and returns a strictly positive integer less than 50;
- Write the function void READARRAY(int Arr[], int N) that reads N integers of the array Arr;
- Write the function void DISPLAY(int Arr[], int N) that displays N integers of the array Arr;
- Write the function void REVERSE(int Arr[], int N, int M) that reverses the order of appearance of the elements of the array Arr that are in position multiple of M;
- Using all the above written functions, write a main function that reads the effective dimension N of an array by calling READDIM, then lls the array using READARRAY, then displays the array using DISPLAY, then reads a positive integer M strictly less than N, then reverses the elements of the array that are in position multiple of M using REVERSE, then displays the array using DISPLAY.
Running example:
Difficulty level
This exercise is mostly suitable for students
#include<conio.h>
#define SIZE 50
int READDIM()
{
int n;
do
{
printf("Enter the dimension : ");
scanf("%d", &n);
} while (n <= 0 || n>SIZE);
return n;
}
void READARRAY(int Arr[], int N)
{
int i;
printf("Enter %d elements : ", N);
for (i = 0; i<N; i++)
scanf("%d", &Arr[i]);
}
void DISPLAY(int Arr[], int N)
{
int i;
for (i = 0; i<N; i++)
printf("%d ", Arr[i]);
}
void REVERSE(int Arr[], int N, int M)
{
int i, j, aux;
//last multiple of M
j = M*((N -1 ) / M);
i = 0;
while (i < j)
{
aux = Arr[i];
Arr[i] = Arr[j];
Arr[j] = aux;
i += M;
j -= M;
}
}
void main()
{
int N, M;
int A[SIZE];
N = READDIM();
printf("\nReading array (enter %d integer)\n", N);
READARRAY(A, N);
printf("\nArray before modification\n");
DISPLAY(A, N);
do {
printf("\n\nEnter a value for M: ");
scanf("%d", &M);
} while (M<0 || M >= N);
REVERSE(A, N, M);
printf("\nArray after modification\n");
DISPLAY(A, N);
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
2 players Game - version 2