Tricky ok to set declared size but you cannot change

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: t declared size, but you cannot change array size at run-time! (size is often set by a #define directive) nums element 0 element 1 element 2 element 3 element 4 381 4107 932 40 212 9 Array Indexing Chosen array element==ordinary variable name[index] /* choose 1 element */ Index == an integer expression, used as `box#' or `element#' Example: for(i=0; i<5; i++) printf("%d,", nums[i]); produces > 381,4107,932,40,212, nums element 0 element 1 element 2 element 3 element 4 381 4107 932 40 212 10 Array Indexing Chosen array element==ordinary variable name[index] /* choose 1 element */ Index == an integer expression, used as `box#' or `element#' Another Example: for(i=0; i<5; i++) printf("%d,", nums[(i+2)%5]); produces > 932,40,212,381,4107 nums element 0 element 1 element 2 element 3 element 4 381 4107 932 40 212 11 Array Indexing Chosen array element==ordinary variable name[index] !!DANGER!! C won't catch a wild/wrong index !!! reading/writing to nums[-3], or nums[398], can corrupt your program, your data or someone else's! nums element 0 element 1 element 2 element 3 element 4 381 4107 932 40 212 12 Array Example #include <stdio.h> int main (void) { int simple[4]; int i; for (i=0; i<4; i++) /*fill array with odd integers*/ { simple[i] = 1 + 2*i; printf("simple[%d] = %d\n", i, simple[i]); } return 0; } Output: simple[0] simple[1] simple[2] simple[3] = = = = 1 3 5 7 13 #include <stdio.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; printf("Type scores: midterm, proj, final, quiz\n"); for(j=0; j<4; j++) { cnt = scanf(" %d",&score[j]); if(cnt!=1) // did we read in one integer? { // No! printf("\n Type 0-100 then RETURN, please!\n"); 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; } 14 #include <stdi...
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