Académique Documents
Professionnel Documents
Culture Documents
FUNDAMENTALS OF
COMPUTER PROBLEM SOLVING
Topic 3:
Selection Control Structure (Part 2)
Objectives
Nested selection
Switch statement
C-string functions
The Nested if
Syntax:
if (condition1)
if (condition2)
Statement1
else
Statement2
if (x < 7)
if (x > 5)
cout << “x is 6”;
The Nested if
The Nested if
Re-write:
if (x < 7)
{
if (x > 5)
cout << “x is 6”;
}
The Nested if
Syntax:
switch (expression)
{
case value1: statement1;
break;
case value2: statement2;
break;
…
case valueN: statementN;
break;
default: default statement; //optional
}
Switch Structures
switch (choice)
{
case 1 : do something;
break;
case 2 :
case 3 : do something;
do something;
break;
default: do something else;
}
Switch Structures
}
The statement(s) with the match get executed
Switch Structures
switch (choice)
• break is typically used
{ between cases to avoid
case 1 : do something; fall through
break;
case 2 : • The default statement
case 3 : do something; is executed if the
do something; value of the switch
break; expression is NOT
default : do something; found among switch
} labels
// next statement
Switch Structures
Example :
strlen()
#include <iostream.h>
#include <string.h>
int main ()
{
char str1[]="Sample string";
char str2[40];
char str3[40];
strcpy (str2,str1);
strcpy (str3,"copy successful");
cout << "str1: "<< str1 << "\nstr2: " <<
str2 << "\nstr3: " <<str3;
return 0;
}
String Library Function
Example
#include <iostream.h>
#include <string.h>
int main ()
{
char str1[20];
char str2[20];
strcpy (str1,"To be ");
strcpy (str2,"or not to be");
strcat (str1, str2);
cout << str1;
return 0;
}
String Library Function
Example
#include <iostream.h>
#include <string.h>
int main()
{
char fruit_1[] = "apple";
char fruit_2[80];
if (strcmp (fruit_1,fruit_2) == 0)
cout<< "Same fruit!";
else
cout << "Different fruit!";
return 0;
}
String Library Function
Example
#include <iostream.h>
#include <string.h>
int main()
{
char name[40];
Artis Song
[1 ] As Long As You Love Me
[A] Backstreet Boys
[2] I Want It That Way
[1] This I Promise You
[B] N SYNC
[2] Bye Bye Bye
Test Yourself 2
Artist Song
Backstreet Boys Larger Than Life
N SYNC Bye Bye Bye
Boyzone Picture Of You
Thank You
END