15035042008 int score4 j cnt double grade type

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: o.h> Array Example int main (void) { const double percent[4] = {0.15,0.35,0.42,0.08}; int score[4], j, cnt; double grade; >Type scores: midterm, proj, final, quiz: > zbbr printf("Type scores: midterm, proj, final, quiz\n"); > Type 0-100 then RTN, please! for(j=0; j<4; j++) { > 89 cnt = scanf(" %d",&score[j]); 72 > if(cnt!=1) // did we read98 one integer? > in { // No! > 31 printf("\n Type 0-100 then RETURN, please!\n"); > Final score is j = j-1; // (don't count this try) } } for(j=0,grade=0; j<3; j++) // Compute final grade { grade += (double)score[j] * percent[j]; } printf("\n Final Score is %g\n",grade); return 0; } 15 ?Math on entire Array? NO! Each element of an array acts just like an ordinary variable: int elvis[5], jimi[5]; for(j=0; j<5; j++) { elvis[j] = j*10; } elvis[3] = 8; printf(" %d\n", elvis[2] + 1); OK to compute with single array element, But NO whole-array expressions allowed! elvis=0; or jimi=elvis; (you MUST index the array to set its value) . 16 Summary: Arrays Variable== a place-holder in memory Variable for just one stored value Array == a place-holder in memory for MANY values, sequentially stored and indexed Array elements all of one type (e.g. char, float...), Array size is always constant, never variable, Access array element by its index # In C, index for array always begins at zero, zero C won't prevent an out-of-bounds index!!! 17 Summary: Arrays Before you can use an array, you must: 1) Declare array (set it's type, name, and size), and int elvis[5]; elvis[0] = 381; elvis[2] = 932; elvis[4] = 212; elvis Si*. <;r5 elvis[1] = 4107; elvis[3] = 40; Initially, array holds garbage! element 0 element 1 element 2 element 3 element 4 k79] as4$ p@#$ 18 Summary: Arrays Before you can use an array, you must: 2) Initialize all elements, either like this... elements (set all its values--otherwise it holds `garbage') int elvis[5]; elvis[0] = 381; elvis[2] = 932; elvis[4] = 212; elvis elvis[1] = 4107; elvis[3] = 40; element 0 element 1 element 2 element 3 element 4 381 4107 932 40 212 19 Summary: Arrays Before you can use an array, you must: 2) Initialize all elements, or like this: elements (set all its values--otherwise it holds `garbage') int elvis[5] = {381,4107,932,40,212}; elvis[0] = 381; elvis[2] = 932; elvis[4] = 212; elvis elvis[1] = 4107; elvis[3] = 40; element 0 element...
View Full Document

This note was uploaded on 10/05/2011 for the course COMPUTER S 110-1 taught by Professor Tumblin during the Spring '11 term at Northwestern.

Ask a homework question - tutors are online