# Skenz - How To Wiki

### Site Tools

cs:c_language:array_1

# Differences

This shows you the differences between two versions of the page.

 — cs:c_language:array_1 [2019/02/26 14:35] (current) Line 1: Line 1: + ====== Array (Example 1) ====== + **Concepts:​**\\ + Arrays, initialization and utilization + **Text:**\\ + Implement a C program that: + * after the declaration and the initialization of a vector of 10 elements + * finds and prints the first even number and its position in the array + + **Solution:​**\\ + ​ + /* Print the first even number and its position of a 10 elements array/​vector. */ + + #include <​stdio.h>​ + #define SIZE 10 + + int main(){ + + int vec[SIZE] = {1, 5, 3, 7, 10, 1, 2, 3, 4, 5}; + int i; + int found = 0; + + /* First solution */ + for(i=0; i​ + + **Comments:​**\\ + The program: + * after the initialization of an array of dimension //SIZE//, directly performed during the declaration:​ + + int vec[SIZE] = {1, 5, 3, 7, 10, 1, 2, 3, 4, 5}; + ​ + * it scans the array by using a //for// cycle until all the elements of the vector are analyzed (condition //​i<​SIZE//​) and until an even number is found (the variable //found// has a value different than  //0//, i.e., true). The variable //found// is set to //1// when the first even number is found in the vector. + + for(i=0; i​ + * the same exercise can be resolved equivalently by using the //while// statement: + + /* Second solution */ + i = 0; found = 0; + while ( i​ + * results are printed at the end of the program. It is important to notice that at the exit of both the //for// and the //while// cycle, the variable //i// is the next position of the first even number. For such reason, to print the first even element of the vector and its position the variables //​vec[i-1]//​ and //i-1// must be used, respectivelly. ​ + + if (found){ + printf("​EVEN NUMBER: %d (POSITION: %d)\n",​ vec[i-1], i-1); + } else { + printf("​No even number is present in array\n"​);​ + }  ​ + 