Multiple Conditions in a for loop in C

Introduction

Multiple variables can be initialized as well as multiple conditions, and propagations can be made in a single ‘for’ loop by just using a comma ‘,’. In this article we will explore the use of Multiple Conditions in a for loop in C.

Example

Let us write a program to change values of 2 variables, ‘x’ and ‘y’, simultaneously from ‘1 to 5’ and ‘5 to 1’ respectively.

#include<stdio.h>
int main()
{
            int x,y;
            for(x=1,y=5; x<=5,y>=1; x++,y--)
            {
                        printf("x=%d\ty=%d\n",x,y);
            }
}

Output

Multiple Conditions in a for loop in C

Explanation

The above output is only possible when the initialisation, condition, and propagation steps of both variables were written in a single ‘for’ loop.

Note: ‘\t’ is used to generate a tab space like ‘\n’ gives a newline.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.