Introduction to Computer Science

Loop for examples

Printing "Hello" 5 times on 5 lines

int i;
for (i = 1; i <= 5; i ++){
    printf("Hello \n");
}

Evaluation of 0+1+2+3+...+n using loop for

int n, i;
int sum = 0;
scanf("%d", &n);
for (i = 1; i <= n; i ++){
    sum += i;
}
printf("the sum of integers between 0 and %d equals %d ", n, sum);

Evaluation of n! using loop for

int n, i;
int factorial = 1;
scanf("%d", &n);
for (i = 2; i <= n; i ++){
    factorial *= i;
}
printf("the %d! = %d ", n, factorial);

Evaluation of sum of even numbers between 0 and the input value using loop for

int n, i;
int sumEven = 0;
scanf("%d", &n);
for (i = 2; i <= n; i += 2){
    sum += i;
}
printf("the sum of even integers between 0 and %d equals %d ", n, sumEven);

What is the output of the following fragment?

int i, j, result = 0;
for (i = 1, j = 2; (i + j) <= 8; i++, j+=2){
    result += i*j;
}
printf("%d", result );

What is the output of the following fragment?

int i, j, result = 0;
for (i = 10, j = 12, k = 1; (i + j) >= 15; i -= 3, j -= 5, k ++){
    result *= i + j + k;
}
printf("%d", result );

What is the output of the following fragment?

int i;
for (i = 0; ++i <= 5; ){
    printf("%d\n", i);
}

What is the output of the following fragment?

int i = 0;
for ( ; i++ <= 5; printf("%d\n", i)){
    /* empty loop body */
}