You are on page 1of 29

C Programming

Branching, Looping and


Logical expressions
ME 325
Spring, 2007
C function reference
http://www.cprogramming.com/function.
html
Overview
• Relational Operators
• Branching
• Scanf
• Loops
• Arrays
• Strings
Concept of TRUE or FALSE
• A true statement is one that evaluates
to a nonzero number. A false statement
evaluates to zero.

• When you perform comparison with the


relational operators, the operator will
return 1 if the comparison is true, or 0
if the comparison is false.
– The check 0 == 2 evaluates to 0.
– The check 2 == 2 evaluates to a 1.
Relational Operators
• > greater than 5 > 4 is TRUE
• < less than 4 < 5 is TRUE
• >= greater than or equal 4 >= 4 is
TRUE
• <= less than or equal 3 <= 4 is
TRUE
• == equal to 5 == 5 is
TRUE
• != not equal to 5 != 4 is TRUE
Boolean Operators
• Logical operators are usually used with
conditional statements which we will
cover shortly. The outcome of these
operation is true of false.
• The two basic logical operators are:
– && for logical AND
– || for logical OR.
• Single & and | have a different meaning
for bitwise AND and OR operation.
Truth Table
And operator ( A & B = C)
A B C
1 1 1
0 0 0
0 1 0
1 0 0
Or operator ( A | B = C)
1 1 1
0 0 0
1 0 1
0 1 1
If Statements
if (conditional_1)
{
...block of statements executed if conditional_1 is
true...
}
else if (conditional_2)
{
...block of statements executed if conditional_2 is
true...
}
else
{
If Example
#include <stdio.h>
int main()
{
int x;

printf(“\nEnter a value for x: “);


scanf(“%d”,&x);
if(x%2==0) /* remainder is zero, then even */
printf(“\nx=%d, is ** EVEN NUMBER **”,x);
else
printf(“\nx=%d, is ** ODD NUMBER **”,x);
return 0;
}
This program prompt the user for a number, scanf, and check if
remainder is 0 then it output EVEN, else it is ODD.
The scanf() function reads input from STDIN, next slide
int scanf(const char
*format,... )
• The scanf() function reads input from STDIN, according to the
given format, and stores the data in the other arguments. It
works a lot like printf(). The format string consists of control
characters, whitespace characters, and non-whitespace
characters. The control characters are preceded by a % sign,
and are as follows:
– %c single character
– %d an integer
– %f floating-point number
– %s string
– ….
Example
int x,y;
float f;
scanf(“%f”,&f);
scanf(%d %d”,&x,&y);
/* read the user input as float and store in f variable
read the user input as space separated integers and store in x and y
Switch Statement
switch (expression)
{
case const_expression_1:
...block of statements...
break;
case const_expression_2:
...block of statements...
break;
default:
...block of statements..
break;
}
The appropriate block of statements is executed
according to the value of the expression, compared
with the constant expressions in the case statement.
Loops
• Loops are used to repeat a block of
code. Being able to have your program
repeatedly execute a block of code is
one of the most basic but useful tasks
in programming.

• There are three types of loops: for,


while, and do..while. Each of them has
their specific uses.
FOR Loop
• for loops are the most useful type. The
syntax for a for loop is
for ( variable initialization; condition; variable
update )
{
Code to execute while the condition is true
}

The variable initialization allows you to either declare a variable


and give it a value or give a value to an already existing
variable.
Second, the condition tells the program that while the conditional
expression is true the loop should continue to repeat itself
The variable update section is the easiest way for a for loop to
For loop example
#include <stdio.h>
int main()
{
int x;
/* The loop goes while x < 10, and x increases by one every loop*/
for ( x = 0; x < 10; x++ )
{
/* Keep in mind that the loop condition checks the conditional statement
before it loops again. consequently, when x equals 10 the loop breaks.
x is updated before the condition is checked. */
printf( "%d\n", x );
}
getchar();
return 0;
}
WHILE loops
while ( condition )
{
Code to execute while the condition is
true
}

The true represents a boolean expression which could


be
while(x == 1) or while ( x != 7 ) (x does not equal
7).
It can be any combination of boolean statements that
are legal.
While loop example
#include <stdio.h>
int main()
{
int x = 0; /* Don't forget to declare and initialize variables */
while ( x < 10 )
{
/* While x is less than 10 */
printf( "%d\n", x );
x++; /* Update x so the condition can be met eventually */
}
getchar();
return 0;
}
DO..WHILE loops
• DO..WHILE loops are useful for things
that want to loop at least once.

do
{
Code to execute at least once
} while ( condition );
Do … while Example
#include <stdio.h>
int main()
{
int x;
x = 0;
do
{
/* "Hello, world!" is printed at least one time even though the condition is
false*/
printf( “Hello, world!\n” );
} while ( x != 0 );
getchar();
return 0;
}
Break and Continue
• Two keywords that are very important
to looping are break and continue.

– The break command will exit the most


immediately surrounding loop regardless of what
the conditions of the loop are. Break is useful if
we want to exit a loop under special
circumstances.

– continue is another keyword that controls the


flow of loops. If you are executing a loop and hit a
continue statement, the loop will stop its current
iteration and begin to execute again from the top.
Break Example
#include <stdio.h>
int main()
{
int x=0;
while(1=1)
{
if(x>=5)
break;
x++;
print(“x=%d\n”
}
return 0;
}
This program will loop and print the value of x, when x>=5 then it breaks
the loop and exit
Continue Example
#include <stdio.h>
int main()
{
int x=0;
for(x=0;x<10;x++)
{
if(x==2 || x==4)
continue;
print(“x=%d\n”
}
return 0;
}

This program will loop and print the value of x, except when x=2 or
x=4, then stop the iteration and continue with t next iteration.
Arrays
• An array lets you declare and work with
a collection of values of the same type.
For example, you might want to create
a collection of five integers. One way to
do it would be to declare five integers
directly:
– int a, b, c, d, e;
• An easier way is to declare an array of
five integers:
– int a[5];
Array, Cont.
• The five separate integers
inside the previous array are
accessed by an index.
• All arrays start at index zero
and go to n-1 in C. Thus, int
a[5]; contains five elements.
For example:
– int a[5];
• a[0] = 12; a[1] = 9; a[2] = 14;
a[3] = 5; a[4] = 1;
Array, Cont.
• One of the benefits of array indexing is
that you can use a loop to manipulate
the index. For example, the following
code initializes all of the values in the
array to 0:
int a[5];
int i;
for (i=0; i<5; i++)
a[i] = 0;
Array Example
#include <stdio.h>
#include <stdlib.h>

#define MAX 10 /* Define a constant MAX */

int main()
{
int a[MAX];
int i,rtotal=0;
/* fill array */
for (i=0; i < MAX; i++)
a[i]=2*i;
printf("a[i]\t value \t rtotal \n -------------------------------------\n");
for (i=0; i < MAX; i++)
{
rtotal+=a[i];
printf("a[%d]\t%d\t%d\n",i,a[i],rtotal);
}
system("pause");
return 0;
}
Output of the Array Example
Strings
• A string in C is simply an array of
characters. The following line declares
an array that can hold a string of up to
99 characters.
– char str[100];
– str[0] is the first character of the string,
str[1] is the second character, and so on.
str[99]=0 or ‘\0\?
– Because C uses null-terminated strings,
which means that the end of any string is
marked by the ASCII value 0 (the null
Array declaration /
initializing
• char str[15];
• char course[6]={‘M’,’E’,’3’,’2’,’5’,’\0’};
• char course[]=“ME325”;
• int x[3]={5,6,8};

The above declare a


str of 14 characters
Course=“ME325”;
x[0]=5; x[1]=6; x[2]=8;
String Example
#include <stdio.h>
#include <stdlib.h>

int main()
{
char course[]="ME325";
int i=0;

printf("Course: %s\n\n",course);
printf("index\tchar\tcode\n");
for (i=0; i < 6; i++) /* fill array */
printf("%d\t%c\t%d\n",i,course[i],course[i]);

system("pause");
return 0;
}
This example will print the sentence Course: ME325 then a table showing each
character as character and ASCII code

You might also like