Credits

Monday, February 9, 2009

Conditional Statements

C and C++ accept conditional statements through if statement. There are different forms of this depending on your solution. C++ takes its structures from C. Thus, conditional and loop structures among others are similarly written.

The syntax is:

form 1
if (condition)
statement_if_true;

form2:
if (condition)
{
/*Do these actions here if the condition is true.
Use the curly braces if you have more than one statement to execute*/
statement1;
statement2;
;
statementn;
}

form 3:
if (condition)
statement_if_true;
else
statement_if_false;

form 4:
if (condition)
{statements_if_true;}
else
{statements_if_false;}

Check this sample program to input name and birth date.



[+/-] show/hide



#include stdio.h /*the stdio.h must be enclosed in <> */
main( )
{ char firstname[15];
char lastname[15];
int birthyear;
int currentyear;
int age;

clrscr();
printf("\nPlease enter your firstname: ");
scanf("%s",&firstname);
printf("\nPlease enter your lastname");
gets(lastname);
printf("\nPlease enter the current year: ");
scanf("%d",&currentyear);
printf("\nPlease enter your birth year: ");
scanf("%d",&birthyear);
age=currentyear-birthyear;
printf("\nHello %s %s",firstname,lastname);
printf("\You are %d years old\n",age);
if (age>18)
printf("You are qualified to vote!);
else
printf("You are still underage. Go to your mommy!");
getche();
}

What is the output of this code?
Translate these codes into Bloodshed C++.

AddThis