printf sum of all elements in a is dn 13 sumElements a size 14 printf sum of

Printf sum of all elements in a is dn 13 sumelements

This preview shows page 21 - 23 out of 33 pages.

11}12printf( "sum of all elements in a is %d\n",13sumElements ( a, size ) );14printf( "sum of first 5 elements in a is %d\n",15sumElements ( a, 5 ) );16printf( "sum of last 5 elements in a is %d\n",17sumElements ( a+5, 5 ) );18return0;19}2021// addssizemanyelementsofarraya22// assumption :thesizeofthearrayisatleastequaltosize23intsumElements (int*a,intsize ){24intsum = 0;25inti;26for(i = 0; i < size; i++ ) {27sum = sum + a[i];28}29returnsum;30}Seesum.candsum2.cfor this code and its version that passes int a[] as a parameter to the function.Something to Think About:DNHI: Modify the code above to check your answers to the following questions:1) What happens ifsumElements()function modifies the content of arraya? Do changes affect the array declared in 2) What happens if thesizeparamter passed to thesumElements()function exceeds the size of the declared arraya? Try it by
Image of page 21
CSCI-UA 201 Lecture 2: Introduction to C Programming Language Joanna Klukowska [email protected] char tmp; // 1 byte of storage int i; for (i = 0; i < size; i++) { // for every byte : swap the byte tmp = x[i]; x[i] = y[i]; y[i] = tmp; } } See swap generic.c for an example of use of this function. 5 Strings in C Two strings walk into a bar and sit down. The bartender says, ”So what’ll it be?” The first string says, ”I think I’ll have a beer quag fulk boorg jdkˆCjfdLk jk3s d#f67howe˜owmc63ˆDz x.xvcu” ”Please excuse my friend,” the second string says, ”He isn’t null-terminated.” A string in C is an array of characters terminated by a null character ( \ 0 ) . Every function that performs operations on strings uses that null character. A missing null character in a string is also the source of most errors (and jokes) related to strings in C. Whenever we have a double quoted string in a program it is stored as a string constant terminated by a null character. For example: printf("Hello World!\n"); Writing char h[] = "hello"; creates and array of 6 characters (yes, 5 letters + a null character). It is equivalent to writing char h[6]= "hello"; Note that the following lines will compile as well and sometimes even run without obvious problems (at first) char
Image of page 22
Image of page 23

You've reached the end of your free preview.

Want to read all 33 pages?

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture