Elementary programming with c einternational

Page 289

Session 17 Strings Concepts

scanf(“%d”, &num[ctr]);

} sum = sum_arr(num); /* Invokes the function */ printf(“\nThe sum of the array is %d”, sum); }

int sum_arr(int num_arr[]) /* Function definition */ { int i, total; for(i=0,total=0;i<5;i++) /* Calculates the sum */ total+=num_arr[i]; return total; /* Returns the sum to main() */ }

A sample output of the above program is: Enter number 1: 5 Enter number 2: 10 Enter number 3: 13 Enter number 4: 26 Enter number 5: 21 The sum of the array is 75

17.4 Passing Strings to Functions Strings, or character arrays, can also be passed to functions. For example, the following program accepts strings into a two-dimensional character array. Then, the array is passed to a function that determines the longest string in the array. Example 9: #include <stdio.h> void main() { char lines[5][20]; int ctr, longctr=0; int longest(char lines_arr[][20]); /* Function declaration */ for(ctr = 0; ctr < 5; ctr++) /* Accepts string values into the array */ Elementary Programming with C

Version 1.1 © Aptech Limited

page 279 of 356


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.