Displaying arrays' elements and their respective indices in C program

 

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows 2003 Server Standard Edition

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info:

To do: Displaying arrays' elements and their respective indices using pointer notation

To show: The use of pointer arithmetic to access array elements and printing the data value and indices

 

 

// Demonstrates the use of pointer arithmetic to access array elements using pointer notation

#include <stdio.h>

#define MAX 10

 

void main(void)

{

// declare and initialize an integer array

int array1[MAX] = {0,1,2,3,4,5,6,7,8,9};

// declare a pointer to int and an int variable

int *ptr1, count;

// declare and initialize a float array

double array2[MAX] = {0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9};

// declare a pointer to float

double *ptr2;

 

// initialize the pointers, just an array name is the pointer to the

// 1st array element, both left value and right value of the expression are pointers types...

ptr1 = array1;

ptr2 = array2;

 

// print the array elements

printf("\narray1_data array2_data");

printf("\n-------------------------");

// iterate or loop the arrays and display the content...

for(count = 0; count < MAX; count++)

printf("\n%d\t\t%f", *ptr1++, *ptr2++);

printf("\n-------------------------\n");

}

 

Output example:

 

array1_data array2_data

-------------------------

            0             0.000000

            1             0.100000

            2             0.200000

            3             0.300000

            4             0.400000

            5             0.500000

            6             0.600000

            7             0.700000

            8             0.800000

            9             0.900000

-------------------------

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index