Write a program which performs the following tasks:
a) Initialize an integer array of 10 elements in main( )
b) Pass the entire array to a function modify( )
c) In modify( ) multiply each element of array by 3
d) And display each element of array
Answers
Answer:
#include<stdio.h>
void modify(int *,int);
int main()
{
int i,arr[10]={1,2,3,4,5,6,7,8,9,10};
mod(&arr[0],10);
for(i=0;i<10;i++)
printf(" %d \n ",arr[i]);
return 0;
}
void modify(int *j,int n)
{
int i;
for(i=0;i<n;i++)
{
*j=*j*3;
j++;
}
output:
3
6
9
12
15
18
21
24
27
30
Explanation:
1) firstly give array size and elements
as arr[10]={ 1,2,3,4,5,6,7,8,9,10}
2) then paas entire array to function modify as
modify (&arr[0],10] or
modify (arr,10)
3) then in function modify access the elements using pointer as
void modify (int *j,int n)
4) then multiply that pointer with 3 as
*j=*j*3
5) the increment the pointer to other array element as
j++
6) then finally passing the array to main function
and printing the new array by using loop.
The code to perform the given take in C language is as follow:
#include <stdio.h>
void modify(int A[]) {
for(int i = 0; i < 10; i++) {
A[i] *= 3;
}
for(int i = 0; i < 10; i++) {
printf("%d ", A[i]);
}
}
int main()
{
int A[10] = {0, 1 , 2, 3, 4, 5, 6, 7, 8, 9};
modify(A);
return 0;
}
- Initially in the main() function, we have initialized an array A[ ] of 10 elements with numbers 0-9, using the statement
int A[10] = {0, 1 , 2, 3, 4, 5, 6, 7, 8, 9};
- Then we have invoked the modify() from main(), passing the array A[ ] as argument.
- In the modify() function, we multiply each element of the array with 3 by running a for loop.
- Finally in the modify() function, we run another for loop, this time to display the elements of the array.
- Hence, our desired task is achieved.
#SPJ3