For Loop in C Programming Language (Vectors and Arrays)

We use the for loop in c programming language when we need repeat an instruction. This for loop is similar to while, but exists some differences:

  • For Loop in C:
    • run the code at least once.
  • While Loop in C:
    • only runs the code if the condition is true.

Syntax:

for(expression1;condition;expression2){
    instruction1;
    ...
    instruction3;
}

 

Explained Syntax:

  • Normally on expression1 we set a the start value of the variable;
  • Then we set the condition, the code will run until the condition is false;
  • In expression2 we set the value to increase the variable that we have previously declare;
  • After we write the initial syntax, we write the instruction/code that we want to execute.

 

Example

#include <stdio.h>
int main(int argc, char** argv) {

    int i;

    for(i=1;i<=10;i++)
       printf("%d\n", i);

    return (EXIT_SUCCESS);
}

Output

1
2
3
4
5
6
7
8
9
10

Example Explained

  • line4, we declare the integer variable i ;
  • line6, we set value variable i to 1;will execute the code while variable i is lower than 10; increase the variable value in 1;
  • line7, we print the variable i.

 

Vector

A vector is a set of data of the same type, which stores values in a continuous index. Example:

Examples of Vectors:

  • int vector[20];
    • this is a vector of type integer with 20 positions;
  • char caracter[10];
    • this is a vector of type char with 10 positions;
  • int vector[ ];

 

Example:

#include <stdio.h>
int main(int argc, char** argv) {
    //We set the type of variable integer with 20 positions
    int i, vector[20];
    //we store numbers from 1 to 20 in vector->vector
    for(i=0;i<20;i++){
       //vector[i], [i] represents the position on the vector, and stores the value of variable i
       vector[i] = i;
    }
    //then we go through the whole vector to print it
    for(i=0;i<20;i++)
       printf("%d", vector[i]);

    return (EXIT_SUCCESS);
}

 

Arrays

The arrays are similar to the vectors, except that in these we have rows and columns to store values.

Examples of arrays:

  • int array[3][4];
    • this is an array with 3 rows and 4 columns;

 

Example
#include <stdio.h>
int main(int argc, char** argv) {
    //We set the type of variable integer with 9 positions
    int i, num, j,array[9];
    //we store numbers that user input
    for(i=0;i<3;i++)
       for(j=0;j<3;j++){
          scanf("%d", &num);
          array[i][j] = num;
    } 
    //then we go through the whole vector to print it
    for(i=0;i<3;i++){
       for(j=0;j<3;j++)
          printf("%d ", array[i][j]);
    printf("\n");
    }
  

    return (EXIT_SUCCESS);
}

If user input numbers 1 2 3 4 5 6 7 8 9, the output will be:

1 2 3 

4 5 6 

7 8 9

Leave a Reply

Your email address will not be published. Required fields are marked *