I was looking at the following question from Let us C. While my code seems to work, I wonder if there is a cleaner more organized way I can do this. A way with less variables or fewer lines of code. Here is the problem given:
Write a program which performs the following tasks:
- initialise an integer array of 10 elements in main()
- pass the entire array to a function modify()
- in modify() multiply each element of array by 3
- return the control to main() and print the new array elements in main()
Here is what I have:
Code:
#include <stdio.h>
int main ()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int *i, l;
int modify();
i = &arr[0];
//printf("%d", *i);
modify (i);
for ( l = 0 ; l < 10 ; l++)
{
printf("\nHere is the array after modification %d\n", *i);
i++;
}
}
int modify (int *j)
{
int k;
for ( k=0 ; k < 10; k++)
{
*j = (*j) * 3;
//printf ("\nHere is what is in arr%d \n", *j);
j++;
}
}
Here is the output:
Here is the array after modification 3
Here is the array after modification 6
Here is the array after modification 9
Here is the array after modification 12
Here is the array after modification 15
Here is the array after modification 18
Here is the array after modification 21
Here is the array after modification 24
Here is the array after modification 27
Here is the array after modification 30