Write a program that asks the users to enter a value for array size “n” and fill
ID: 3820131 • Letter: W
Question
Write a program that asks the users to enter a value for array size “n” and fill up the array with n integers. Then reverse the array and print it on the screen. You are required to do the following in your program: 1) Create an array of 10 elements.
2) “n”, the array size, should be greater than zero and less than 10
3) Each element of the array should be positive and divisible by 3
4) Array should be reversed within itself. i.e. you must not create another array to place the elements in reverse order
I have this code so far:
#include <stdlib.h>
#include <stdio.h>
void printArray(int *array, int size) {
printf("the array is: ");
printf("[");
for (int i = 0; i < size - 1; i++) {
printf("%i, ", array[i]);
}
if (size >= 1) printf("%i", array[size - 1]);
printf("] ");
}
int main(void) {
int count;
printf("Enter the size of the array: ");
scanf_s("%d", &count);
int *array = malloc(count * sizeof(*array));
printf("Enter the elements of the array: ");
for (int i = 0; i < count; i++) scanf_s("%d", &array[i]);
printArray(array, count);
free(array);
getchar();
getchar();
}
I need help with reversing the array. Step number 4 please.
Explanation / Answer
#include <stdlib.h>
#include <stdio.h>
void printArray(int *array, int size) {
printf("the array is: ");
printf("[");
for (int i = 0; i < size - 1; i++) {
printf("%i, ", array[i]);
}
if (size >= 1) printf("%i", array[size - 1]);
printf("] ");
}
void reverse(int *array, int size)
{
int *start=array;
int *end=array+size-1;
while(start<=end)
{
int t=*start;
*start=*end;
*end=t;
start++;
end--;
}
}
int main(void) {
int count;
printf("Enter the size of the array: ");
scanf("%d", &count);
int *array = (int*)malloc(count * sizeof(int));
printf("Enter the elements of the array: ");
for (int i = 0; i < count; i++) scanf("%d", &array[i]);
printArray(array, count);
reverse(array, count);
printArray(array, count);
free(array);
getchar();
getchar();
}
================================
Output:
akshay@akshay-Inspiron-3537:~/Chegg$ g++ rversearr.cpp
akshay@akshay-Inspiron-3537:~/Chegg$ ./a.out
Enter the size of the array:
3
Enter the elements of the array:
1
2
3
the array is:
[1, 2, 3]
the array is:
[3, 2, 1]
==================================================
Please rate my answer
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.