Search⌘ K
AI Features

Solution Review: Multiply Array Elements by 3

Explore how to multiply each element in an integer array by 3 using pointer arithmetic and loops in C. Understand how arrays provide base addresses and how pointer increments access subsequent elements. Learn to use pointers to directly modify array contents in place.

We'll cover the following...

Solution

Press ...

C
# include <stdio.h>
void modifyArray ( int *arr, int n ) ;
int main( )
{
int i ;
static int array[ ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } ;
printf ( "\nOriginal Array is:\n" ) ;
for ( i = 0 ; i < 10 ; i++ )
printf ( "%d ", array[ i ] ) ;
modifyArray ( array, 10 ) ;
printf ( "\n\nModified Array is: \n" ) ;
for ( i = 0 ; i < 10 ; i++ )
printf ( "%d ", array[ i ] ) ;
return 0 ;
}
void modifyArray ( int *arr, int n )
{
// Declares a variable i
int i ;
// for loop to traverse the array
for ( i = 0 ; i < n ; i++ )
{
// Multiply current element by 3
*arr = *arr * 3 ;
// Move to the next element
arr++ ;
}
}

Explanation

We ...