Introduction to Programming in C

Index   |   Using VC++
 
Introduction
Basic Output
Variables
4 Conditionals
Loops
Example 1
More on Conditionals
Further Exploration
Algorithm Design
10 Arrays
 
< Previous

Conditionals

Next >
  • Create a project called If.
  • Create a source file called main.c.
  • Type in (or copy/paste) the following code:
  • #include <stdio.h>
    
    /* This program shows the use of a conditional
       statement (if) and the two styles of comments
       supported by the C language. */
    int main()
    {
    	int temp;	// temperature
    
    	temp = 85;
    
    	printf("It is %d degrees outside.\n", temp);
    	if (temp > 70)
    	{
    		printf("%d degrees is warm.\n", temp);
    	}
    
    	return 0;
    }
    
  • Save your file.
  • Build your program (F7).
  • Check the Output window for errors.
  • Run your program (Ctrl-F5).

Explanations

  • A comment is text added for a human reader; it is ignored by the compiler. This example shows both styles.
    • The first comment style is to enclose text between /* and */, as shown by the comment before the main() function. Comments using this style can appear on multiple lines, or in the middle of a line of code; once the */ is reached, the compiler will begin processing again.
    • The second comment style is to use // followed by text, as shown following the declaration of the variable temp. In this case, the comment continues until the end of the line. There is no way to close this style of comment before the end of the line, and each commented line needs to begin with //.
  • The if statement enables the program to make a decision -- if the expression in the parentheses is true, the block of code following the if is executed. If the expression is false, that block (the braces { } and the code inside them) is skipped.
  • In this case, since temp is 85, and since 85 is greater than 70, the expression is true, and the "warm" message is printed.
  • Note that there is no semicolon at the end of the if expression! The line with the if is the first part of a statement (which is completed by the block following it).
  • By convention, statements inside the braces are indented (for readability).
  • Comparison operators are:
    < less than
    >greater than
    <=less than or equal to
    >=greater than or equal to
    ==equal to (note that a single = will not work!)
    !=not equal to

Definition

Boolean Expression
An expression that evaluates to either true or false; typically a comparison. The contents of the parentheses in an if statement should be a Boolean expression.

Exercises

  • Initialize the temperature (temp) to 50 (instead of 85) and run the program again. In this case, since 50 is less than 85, the if statement is false, so the block of text containing the "warm" message is skipped.
  • What would you expect to happen for temperature values of 69, 70, and 71? Try those values and see if your predictions are correct.
  • Make the "warm" message show when the temperature is 70. There are (at least) two ways to do this; can you figure them out? Which one seems more logical to you?

Changes

Make the following changes to your program:

  • You can have multiple statements in the block corresponding to an if. Add the code below (gray text is existing code). Be sure to keep the code nicely indented for readability. Then build, check for errors, and run the program (be sure to set temp to a value that will make the if expression true).
  • if (temp > 70)
    {
    	printf("%d degrees is warm.\n", temp);
    	printf("Let's go hiking!\n");
    }
    
  • If you want to do something when the Boolean expression in the if statement is false, just add an else clause and a corresponding block of code (shown below).
    • When the Boolean expression in the if is true, the block following the if will be executed and the block following the else will be skipped.
    • When the Boolean expression in the if is false, the block following the if will be skipped and the block following the else will be executed.
    Add the code below, then build, check for errors, and run the program. Test it with different temperature values.
  • if (temp > 70)
    {
    	printf("%d degrees is warm.\n", temp);
    	printf("Let's go hiking!\n");
    }
    else
    {
    	printf("%d degrees is cool.\n", temp);
    }
    
  • You can input a value from the user. Make the following 3 edits, shown below:
    • Add the #define line. It must be before the #include line. (This is only necessary for VC++ users; if you are using the Mac OS X tools, or another Windows compiler, you probably won't need this (although it is harmless to leave it in); it suppresses a warning about using scanf, which Microsoft has deprecated in favor of its safer version, scanf_s. We'll stick with scanf for compatibility with other tools.)
    • Comment out "temp = 85;". We'll input the value instead of setting it here.
    • Add the two new statements (calls to printf and scanf). The printf statement is a prompt to let the user know what the program is expecting. scanf is another function, one that will input from the keyboard; again, %d indicates a decimal (base 10) integer value. The & in front of temp is important -- it allows scanf to change the value of the variable temp.
    Build, check for errors, and run the program. Once this code is added, you don't need to change code and rebuild in order to test with different values for temp!
  • #define _CRT_SECURE_NO_DEPRECATE
    
    #include <stdio.h>
    
    /* This program shows the use of a conditional
       statement (if) and the two styles of comments
       supported by the C language. */
    int main()
    {
    	int temp;	// temperature
    
    	// temp = 85;
    	printf("What is the temperature? ");
    	scanf("%d", &temp);
    
    	printf("It is %d degrees outside.\n", temp);
    	if (temp > 70)
    	{
    		printf("%d degrees is warm.\n", temp);
    		printf("Let's go hiking!\n");
    	}
    	else
    	{
    		printf("%d degrees is cool.\n", temp);
    	}
    
    	return 0;
    }
    
  • You can nest one if statement inside another. Add the code below, then build, check for errors, and run the program. Test it with different values.
  • if (temp > 70)
    {
    	printf("%d degrees is warm.\n", temp);
    	if (temp > 100)
    	{
    		printf("In fact, that's really hot!\n");
    	}
    	printf("Let's go hiking!\n");
    }
    

Exercise

  • Nest an if statement in the else block to show a message that it's freezing when it's 32 degrees or less.

When you are done working with this project, select File/Close Solution.

Summary

  • Text enclosed between /* and */ is a comment, and is not processed by the compiler.
  • Text after //, until the end of the line, is a comment.
  • Programs can make decisions using if statements, optionally followed by else statements.
  • Values can be input using the scanf function.
< Previous Next >