Skip to content
GATEiit

GATE CSE 2019 Q37: Static counter r() used in for-loop init, condition, update and body

Syllabus topic: Programming in C

Question

Consider the following C program:

#include <stdio.h>
int r(){
    static int num=7;
    return num--;
}

int main(){
    for (r();r();r())
        printf("%d",r());
    return 0;
}

Which one of the following values will be displayed on execution of the programs?

Try it: multiple choice: exactly one correct option

Select one option
Wrong answer costs 2/3 mark in GATE.
Show answer and explanation

Answer: B (official GATE 2019 final answer key)

Concept used: A static local variable keeps its value between calls; post-decrement returns the old value; the for-loop runs init once, then condition, body, update repeatedly.

Concept notes

Loading notes…

First step: Trace num through each call in the order init, condition, body (printed), update, condition, ..., stopping when the condition call returns 0.

Full step-by-step solution

Loading…

Answer from the official final answer key. Found a mistake? Use Report issue and we will fix it.

More questions on Programming in C

Every PYQ on this topic →

Share this question

WhatsAppDownload image

Source: official GATE 2019 CS question paper and final answer key, organised by IIT Madras. Question paper · Answer key