In: Computer Science
Please, write a loop to print odd numbers an array a with pointers backwards. You can use a variable “size” for array size.
NOTE: If any changes are to be done in the code, or if there is any doubt feel free to put it in the comments , i will be there to solve the doubts,
Here is the complete c/c++ code:
//Inlcuding the required header files
#include <stdio.h>
#include <stdlib.h>
int main()
{
//Declare an array of size 10
int arr[10] = {3, 4, 2, 5, 1, 6, 7, 8, 9, 78};
//Define a size variable and it will store the number of elements in arr by doing 100/10 = 10
int size = sizeof(arr) / sizeof(arr[0]);
//Make a pointer point to the last element
int *ptr = arr + size;
//While the pointer is not at the start print the corresponding value if it is odd
while (ptr != arr)
{
if ((*ptr) % 2 == 1)
printf("%d ", *ptr);
//Decrement the pointer
ptr--;
}
//Now we are at the first position, print it if it is odd
if ((*ptr) % 2 == 1)
printf("%d", *ptr);
return 0;
}
Here is the image of the code to help understand the indentation
Here is the output of the above code, you can try experimenting with the array to see what results you get