You are here:

C/What would the following print?

Advertisement


Question
Hi, Joseph, I've come across this program the other day, and I just can't get the answer for this one, please help.

Here is the program, it asks me what would the output be:
#include <stdio.h>

void print_letter2(void);

int ctr;
char letter1 = 'X';
char letter2 = '=';

int main(void) {
 for(ctr = 0; ctr < 10; ctr++) {
    printf("%c", letter1);
    print_letter2();
 }   
 return 0;
}

void print_letter2(void) {
 for(ctr = 0; ctr < 2; ctr++)
   printf("%c", letter2);
}

At first, I simply thought it would print X== 10 times on the same line. However, the answer is that X== will keep printing forever, and it does seem to do that except I don't know how it happened.

Answer
Hi, Angela.

The problem is that you have declared a global variable called ctr and used this in both loops.  The code execution will go something like this:

   ctr = 0 (start of first loop)
   printf X (body of first loop)
   ctr = 0 (start of second loop)
   printf = (body of second loop)
   ctr = 1 (increment of second loop)
   printf = (body of second loop)
   ctr = 2 (increment of second loop)
   ctr = 3 (increment of first loop)
   printf X (body of first loop)
   ctr = 0 (start of second loop)
   ... see we've hit the infinite loop part here

If you use separate counter variables for each loop, then you would see the desired behavior.

Let me know if you have further questions! :)

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Joseph Moore

Expertise

I've been programming in one form or another since my brother taught me BASIC when I was 6. I've been programing professionally since I was 20, first web development with HTML, JS, DHTML, CSS, etc., then I became a video game developer, writing code in C, C++, C#, SQL, assembly, and various scripting languages. I've even written my own scripting languages, custom designed for the games I was making. I also dabble in Java, PHP, and Perl. I've worked on pretty much every aspect of game development, including graphics, audio, gameplay, tool, UI, input, animation, and physics.

Experience

I've been writing C code for 12 years, both on my own in my spare time and professionally.

Organizations
IGDA

Education/Credentials
Bachelor of Science in Game Design and Development, Full Sail University, Winter Park, FL

Awards and Honors
Salutatorian and Advanced Achiever Awards at Full Sail; Independent Games Festival Student Showcase winner, 2004; Featured article on Gamasutra about an experimental game developed in 2004

©2012 About.com, a part of The New York Times Company. All rights reserved.