Sie sind auf Seite 1von 21

2/17/2011

1
CONTROL STATEMENT
Selection, loop, and array structure.
(04 : 09)
5.1 Understand Program Controls
Without any logical control structure statement, the instructions were executed in the same
order in which they appeared within the program. Each instruction was executed once and
only once. Thus, these programs did not include tests to determine if certain conditions are
true or false, they did not require the repeated execution of groups of statements, and did not
involve the execution of individual groups of statements on a selective basis.
The ability to control the flow of your program, letting it make decisions on what code to
execute, is valuable to the programmer.
For examples, a realistic C program may require that a logical test be carried out at some
particular point within the program.
Branching - Depending on the outcome of the logical test, one of several possible
actions will then be carried out.
Selection A special kind of branching, in which one group of statements is
selected from several available groups.
Looping In addition, the program may require that a group of instructions be executed
repeatedly, until some logical condition has been satisfied. Sometimes
the required number of repetitions is known in advance and sometimes
the computation continues indefinitely until the logical condition becomes
true.
2/17/2011
2
a. if
A conditional branching statement
The if statement allows you to control if a program enters a section of code or
not based on whether a given condition is true or false. One of the important
functions of the if statement is that it allows the program to select an action
based upon the user's input. For example, by using an if statement to check a
user-entered password, your program can decide whether a user is allowed
access to the program.
The structure of an if statement is as follows:
if ( expression ) statement
The expression must be
placed in parentheses.
The statement will be executed only if
the expression has a nonzero value
true,
The statement can be either simple or
compound.
Often compound statement which may
include other control statements
2/17/2011
3
To have more than one statement execute after an if statement that
evaluates to true, use braces, like we did with the body of the main function.
Anything inside braces is called a compound statement, or a block. When
using if statements, the code that depends on the if statement is called the
"body" of the if statement.
For example:
if ( TRUE ) {
/* between the braces is the body of the if statement */
Execute all statements inside the body
}
Example Program : IF Statement
#include <stdio.h>
main ()
{ int age, yrs;
printf("Type in your age: ");
scanf ("%d", &age);
if (age < 18)
{ printf ("You cannot vote yet\n");
yrs = 18 - age;
printf("You can vote in %d years.\n", yrs);
}
if (age > 18)
{ printf ("You can vote now.\n");
}
Return 0;
}
The answers:
2/17/2011
4
b. if..else
The general form of if statement which includes the else clause is
if ( expression ) statement 1 else statement 2
If the expression has a nonzero value(true), the
statement 1 will be executed. Otherwise,
statement 2 will be executed.
Sometimes when the condition in an if statement evaluates to false, it
would be nice to execute some code instead of the code executed when
the statement evaluates to true. The "else" statement effectively says that
whatever code after it (whether a single line or code between brackets) is
executed if the if statement is FALSE.
# include <stdio.h>
main()
{
int yrs, age;
printf("Type a age: ");
scanf("%d", &age);
if (age < 18)
{ printf("You cannot vote yet\n");
yrs = 18 - age;
printf("You can vote in %d years. \n", yrs);
}
else
{
printf("You can vote now.\n", yrs);
}
return 0;
}
Example Program : IFElse
The answers :
2/17/2011
5
c. nested if
One property of if else statement is that they can be nested. This means
that if statement can be target of another if statement.
In a nested else statement is associate with nearest if statement. This
association can be change by used of code block. Also you should use
proper indenting in your program to make sure your remove any visual
ambiguity.
General representation of nested if in C can be
If (condition1) statement1;
If (condition2) statement2;
If (condition3) statement3;

else statement n+1


else statement n+2
else statement n+3
#include<stdio.h>
main()
{
int number;
printf("Type a number:");
scanf("%d", &number);
if(number>100)
printf("Large\n");
else if (number>0)
printf("Not large but positive\n");
else if (number==0)
printf("or zero\n");
else
printf("Negative \n");
return 0;
}
Example Program : Nested If
The answers :
2/17/2011
6
d. switch..case
Switch is a selection statement provided by C. It has a built in multiple
branch structure . The input value to the switch statement construct is a int or
char variable. Note that no float or any other data is allowed.
The input variable is compared against a group of integer constant.
All the statements in and after the case in which there is a match is executed
until a break statement is encountered or end of switch is reached.
We are also allowed to give a default case which will be executed if no other
statement match is found. Also use of standard indenting is recommended.
General representataion of switch in C can be -
switch ( input) {
case constant1:
Statement1;
break;
case constant2:
Statement2;
break;
...
Default:
Statement n;
break;}
#include<stdio.h>
main()
{
char ch;
printf("\n Enter character A, B or C: ");
ch=getchar();
switch(ch)
{
case 'A':
printf("You Entered A");
break;
case 'B':
printf("You Entered B");
break;
case 'C':
printf("You Entered C");
break;
default:
printf("You Did Not Entered A, B or C!\n");
}
return 0;
}
Example Program : Switch Case
Some of the answers:
2/17/2011
7
The switch branches on one value only, whereas the nested if-else tests multiple
logical expressions.
IF-ELSE can have values based on constraints where SWITCH can have
values based on user choice.
In the if - else, first the condition is verified, then it comes to else. Whereas in
the switch - case first it checks the cases and then it switches to that particular
case.
The if statement is used to select among two alternatives. It uses a boolean
expression to decide which alternative to be executed.
5.1.3 Write C program using looping statements.
Loops are used to repeat a block of code.
There are three types of loops:
a. do..while
b. while
c. for
d. nested loop
2/17/2011
8
a. do..while
DO..WHILE - DO..WHILE loops are useful for things that want to loop at least
once. The structure is
do {
} while ( condition );
Notice that the condition is tested at the end of the block instead of the
beginning, so the block will be executed at least once. If the condition is true,
we jump back to the beginning of the block and execute it again. A do..while
loop is almost the same as a while loop except that the loop body is
guaranteed to execute at least once. A while loop says "Loop while the
condition is true, and execute this block of code", a do..while loop says
"Execute this block of code, and then continue to loop while the condition is
true".
#include<stdio.h>
#include<string.h>
main()
{
char checkword[80] = "Rahsia";
char password[80] = "";
do{
printf("Enter password: ");
scanf("%s", &password);
}while(strcmp(password, checkword));
return 0;
}
Note : This example prompts users for a password and
continued to prompt them until they enter one that
matches the value stored in checkword.
Example Program : Do..While
The answer :
2/17/2011
9
b. while
The while statement is used to carry out looping operations, in which a group
of statement is executed repeatedly, until some condition has been sactisfied.
The general form of the while statement is
while ( condition ) { Code to execute while the condition is true }
Codes must include some feature that
eventually alters the value of the
expression, thus providing a stopping
condition for the loop.
#include<stdio.h>
main()
{
int x=0; /* Don' t forget to declare variables */
while(x<10) { /* While x isless than 10 */
printf("%d\n",x); /*Loop prints values 0 to 9*/
x++; /* Update x so the condition can be met eventually */
}
return 0;
}
The easiest way to think of the loop is that when it
reaches the brace at the end it jumps back up to the
beginning of the loop, which checks the condition
again and decides whether to repeat the block
another time, or stop and move to the next statement
after the block.
Example Program : While Statement
The answer:
:
2/17/2011
10
c. for
FOR is one of the iteration statement provided by C. It is the most popular of all
iteration statements because it provides unmatched flexibility and power to the
program.
Loops generated by for statement is are also called entry controlled or close ended
because the condition for iteration of loop is check at the staring of the loop and
loop will not execute even once if the condition will to satisfy even once.
for ( variable initialization; condition; increment)
Statement;
For statement declaration as shown above can be divided into 3 parts
1. Variable initialization In this we initialize the loop control value to a
starting value.
2. Condition In this evaluate the condition for the iteration of the loop and
loop repeat only when this is true.
3. Increment In this determine how the value of loop control value changes
with each iteration of the loop. It can be increment, decrement or any
mathematical expression.
Also statement in above form can be a single statement, block statement or at
blank statement.
Also note that each part is separated by a semi colon.
#include <stdio.h>
int main()
{
float meters, feet;
printf("Meters to feet\n\n");
for (meters = 0; meters < 10; meters++)
{
feet = meters/3.28;
printf("%.2f %.2f\n", meters, feet);
}
return 0;
}
Example Program 1: For Statement
The answer:
2/17/2011
11
#include <stdio.h>
main() /* display the numbers 0 through 9 */
{
int x = 0;
for (; x < 10; ) {
printf( "%d\n", x );
x++;
}
return 0;
}
This program is use a for statement in which two of the three expression are
omitted.
Example Program 2 : For Statement
The answer:
d. nested loop
These loops are the loops which contain another looping
statement in a single loop. These types of loops are used to
create matrix. Any loop can contain a number of loop
statements in itself. If we are using loop within loop that is
called nested loop. In this the outer loop is used for
counting rows and the internal loop is used for counting
columns.
2/17/2011
12
#include <stdio.h>
main( )
{
int n, count, loops, loopcount;
float x, average, sum;
/*read in the number of lists */
printf("How many lists ? ");
scanf("%d", &loops);
/* outer loop (process each list of numbers */
for (loopcount = 1; loopcount <= loops; ++loopcount)
{ /* initialize and read in a value for n */
sum= 0;
printf("\nList number %d\nHow many numbers ?", loopcount);
scanf("%d", &n);
/*read in the numbers */
for (count =1; count <=n; ++count)
{ printf("X= ");
scanf("%f", &x);
sum += x;
}
/* end inner loop */
/* Calculate the average and display the answer */
average = sum/n;
printf("\n The average is %f\n", average);
} /*end outer loop*/
return 0;
}
Example Program : Nested Loop
The answer:
Multiple loop control variable more than 1 loop control is used
#include <stdio.h>
main()
{
int i,j;
for (i=0,j=50; i<j; i++, j--) //print numbers 0 to 50
printf( "%d\n", i );
return 0;
}
The answer :
2/17/2011
13
5.1.4 Compare the differences between the various loop structures.
In While loop the condition is tested first and then the statements are
executed if the condition turns out to be true.
In do while the statements are executed for the first time and then the
conditions are tested, if the condition turns out to be true then the statements
are executed again.
A do while loop runs at least once even though the the condition given is false
In a while loop the condition is first tested and if it returns true then it goes in
the loop - entry control loop
In a do-while loop the condition is tested at the last - exit control loop
for - Statement for allowing us to repeat certain parts of the program until a
specified number of repetitions allow to determine the required number of
repetitions.
5.2 Understand Arrays
What is an array?
Array is a very basic data structure provided by every programming language.
Lets talk about an example scenario where we need to store ten employees
data in our C/C++ program including name, age and salary. One of the
solutions is to declare ten different variables to store employee name and ten
more to store age and so on. Also you will need some sort of mechanism to get
information about an employee, search employee records and sort them. To
solve these types of problem C/C++ provide a mechanism called Arrays.
An array is a data type which contains many variables of the same type.
Each element of the array is given a number by which you can access that
element.
For an array of 100 elements, the first element is 0 (zero) and the last is 99.
This indexed access makes it very convenient to loop through each element of
the array.
In C, all arrays are stored in contiguous memory locations.
The lowest address corresponds to the first element and the highest address to
the last element.
Arrays can be, single dimensional or multidimensional.
One of the most common uses of one-dimensional arrays is to represent
strings. These are stored as an array of characters, terminated by a null.
2/17/2011
14
5.2.1 Describe the steps to define an array.
a. Declaring array
b. Initializing array
c. Accessing array
d. Manipulating array
e. Passing array to function as a parameter
a. Declaring array
The general form of declaring a simple (one dimensional) array is
array_type variable_name[array_size];
in your C program you can declare an array like
int Age[10];
Here array type declares base type of array which is the type of each
element in array, it can be characters, integers, floating-point numbers, etc.
In our example array type is int and its name is Age. Size of the array is
defined by array size i.e. 10.
We can access array elements by index, and first item in array is at index 0.
First element of array is called lower bound and its always 0. Highest
element in array is called upper bound.
2/17/2011
15
Note: One good practice is to declare array length as a constant identifier. This
will minimise the required work to change the array size during program
development.
Considering the array we declared above we can declare it like
#define NUM_EMPLOYEE 10
int Age[NUM_EMPLOYEE];
In C programming language upper and lower bounds cannot be
changed during the execution of the program, so array length can be set
only when the program in written.
String in simplest term is a one dimensional array of characters
terminated by a null character (\n).
For safe use size of this string should be one greater than the maximum
size string going to be stored in this character array.
String in C is equavialent to a real world sentence made by
combination of various characters including spaces.
The general form of declaration of string variable is char name [size];
Also string manipulation can be done very easily using some
predefined function available in header <string.h>.
A character type array can also be initialized within a declaration always refer
as string.
Char text[] = California
2/17/2011
16
C source code below shows the general use of String.
#include<stdio.h>
#include<string.h>
main()
{
char enter[6] ="Enter";
char password[] = "Password";
char input[100] = "None";
while (1)
{
printf("\n %s %s: ", enter, password);
scanf("%s", &input);
if(strcmp(input, "MYPASSWORD"))
{
printf(" Incorrect Password\n");
}
else
{
printf("\n Welcome to the cyber world.....");
break;
}
}
return 0;
}
The answer:
b. Initializing array
The initializing values are enclosed within the curly braces in the
declaration and placed following an equal sign after the array name.
Initialisation of array is very simple in c programming. There are two
ways you can initialise arrays.
Declare and initialisearray in one statement.
Declare and initialisearray separately.
Look at the following C code which demonstrates the declaration and
initialisation of an array.
int Age [5] = {30, 22, 33, 44, 25};
int Age [5];
Age [0]=30;
Age [1]=22;
Age [2]=33;
Age [3]=44;
Age [4]=25;
2/17/2011
17
Array can also be initialised in a ways that array size is omitted,
in such case compiler automatically allocates memory to array.
int Age [] = {30, 22, 33, 44, 25};
All individual array elements that are not assigned explicit initial
values will automatically be set to zero.
Int digits[3] = {3, 6} the result on an element basic are as
follows.
digits[0] = 3, digits[1] = 6 and digits[2] = 0
c. Accessing array
To access an individual element of an array, use the name of the array name
followed by the index of the element in square are brackets. Array indices start
at 0 and end at size-1:
array_name[index];
For example, to store the value 75 in the third element of billy, we could write
the following statement:
billy[2] = 75;
and, for example, to pass the value of the third element of billy to a variable
called a, we could write:
a = billy[2];
2/17/2011
18
Here is how we can print the value of the second element in
the array:
#include <stdio.h>
int main()
{
short age[4];
age[0]=23;
age[1]=34;
age[2]=65;
age[3]=74;
printf("%d\n", age[1]);
return 0;
}
The answer:
#include <stdio.h>
int main()
{
short age[4];
age[0]=23;
age[1]=34;
age[2]=65;
age[3]=74;
printf("%d\n", *(age+1));
return 0;
}
The
output
same as
program
using
pointer to
access the
array.
d. Manipulating array
Each array element occupies consecutive memory locations and array name is a
pointer that points to the first element. Beside accessing array via index we can
use pointer to manipulate array.
This program helps you visualize the memory address each array elements and
how to access array element using pointer.
#include <stdio.h>
void main()
{
const int size = 5;
int list[size] = {2,1,3,7,8};
int* plist = list;
// print memory address of array elements
for(int i = 0; i < size;i++)
{
printf("list[%d] is in %d\n",i,&list[i]);
}
// accessing array elements using pointer
for(i = 0; i < size;i++)
{
printf("list[%d] = %d\n",i,*plist); /* increase memory address of pointer so it go to the next
element of the array */
plist++;
}
}
The answer:
2/17/2011
19
e. Passing array to function as a parameter
There are two ways to pass arguments from a function to
another functions : by value or by address.
Passing by value means that the value of the variable is
passed to the receiving function. C uses the passing by
value method for all non-array variables.
When u pass an array to another function, the array is
passed by address.
The receiving function then places its receiving parameter
array over the address passed. If the receiving function
changes one of the variables in the parameter list, the
calling functions argument changes as well.
#include <stdio.h>
void setArray(int array[], int index, int value)
{
array[index] = value;
}
int main(void)
{
int a[1] = {1};
setArray(a, 0, 2);
printf ("a[0]=%d\n", a[0]);
return 0;
}
Example Program : Passing array to function as a parameter
Function parameters of array type may at first glance appear to be an
exception to C's pass-by-value rule.
#include <stdio.h>
#include <string.h>
char change(char name[])
{
/*change the string stored at the address pointed to by name*/
strcpy(name, 12345");
return 0;
}
main()
{
char name[] = "Chris Williams.";
printf("You old password is %s", name);
change(name);
printf("\nFromnow, the password is %s.\n", name);
return 0;
}
Program 1
Program 2
The answer: The answer:
2/17/2011
20
5.2.2 Modify a 1-dimension array in C programme.
#include <stdio.h>
main()
{
int dayNum;
char *days[7];
days[0] = "Sunday";
days[1] = "Monday";
days[2] = "Tuesday";
days[3] = "Wednesday";
days[4] = "Thursday";
days[5] = "Friday";
days[6] = "Saturday";
printf("Enter a number from 1 to 7: ");
scanf("%d", &dayNum);
if (dayNum>=1 && dayNum<=7)
{ printf("That day is %s\n", days[dayNum-1]); }
else
{ printf("You didnt enter a good number.\n"); }
return 0;
}
The answer:
5.2.3 Write C programme using array.
#include <stdio.h>
main()
{
int my_array[5], count;
for(count=0;count <= 4;count++)
{
my_array[count] = count*2;
}
for(count=0;count <= 4; count++)
{
printf("Element %d is : %d\n", count, my_array[count]);
}
return 0;
}
Element 0 is : 0
Element 1 is : 2
Element 2 is : 4
Element 3 is : 6
Element 4 is : 8
The program's output would be:
2/17/2011
21
Multidimensional Arrays
The array we used in the last example was a one dimensional array. Arrays can
have more than one dimension, these arrays-of-arrays are called
multidimensional arrays. They are very similar to standard arrays with the
exception that they have multiple sets of square brackets after the array
identifier. A two dimensional array can be though of as a grid of rows and
columns.
*Just for information, multidimensional Arrays not in syllabus
#include <stdio.h>
const int num_rows = 7;
const int num_columns = 5;
int main()
{
int box[num_rows][num_columns];
int row, column;
for(row = 0; row < num_rows; row++)
for(column = 0; column < num_columns; column++)
box[row][column] = column + (row * num_columns);
for(row = 0; row < num_rows; row++)
{
for(column = 0; column < num_columns; column++)
{
printf("%4d", box[row][column]);
}
printf("\n"); }
return 0;
}
The answer :

Das könnte Ihnen auch gefallen