Jump to content

Programming Fundamentals/Loops/C

From Wikiversity

loops.c

[edit | edit source]
// This program demonstrates While, Do, and For loop counting using
// user-designated start, stop, and increment values.
//
// References
//     https://en.wikibooks.org/wiki/C_Programming

#include "stdio.h"

int get_value(char *name);
void while_loop(int start, int stop, int increment);
void do_loop(int start, int stop, int increment);
void for_loop(int start, int stop, int increment);

int main() {
    int start;
    int stop;
    int increment;
    
    start = get_value("starting");
    stop = get_value("ending");
    increment = get_value("increment");
    while_loop(start, stop, increment);
    do_loop(start, stop, increment);
    for_loop(start, stop, increment);
    return 0;
}

int get_value(char *name)
{
    int value;
    
    printf("Enter %s value:", name);
    scanf(" %d", &value);

    return value;
}

void while_loop(int start, int stop, int increment) {
    printf("While loop counting from %d to %d by %d:\n", 
        start, stop, increment);
    
    int count;
    
    count = start;
    while (count <= stop) {
        printf("%d\n", count);
        count = count + increment;
    }
}

void do_loop(int start, int stop, int increment) {
    printf("Do loop counting from %d to %d by %d:\n", 
        start, stop, increment);
    
    int count;
    
    count = start;
    do {
        printf("%d\n", count);
        count = count + increment;
    } while (count <= stop);
}

void for_loop(int start, int stop, int increment) {
    printf("For loop counting from %d to %d by %d:\n", 
        start, stop, increment);
    int count;
    
    for (count = start; count <= stop; count += increment) {
        printf("%d\n", count);
    }
}

Try It

[edit | edit source]

Copy

See Also

[edit | edit source]