Saturday, December 20, 2008

Let It Flow...

What is a function?

A function is a structure that has a number of program statements grouped as a unit with a name given to the unit. Function can be invoked from any part of the C++ program.


Features of Function:

To understand why the program structure is written separately and given a name, the programmer must have a clear idea of the features and benefits of function. This will encourage better understanding of function usage:


  • Use of Functions gives a Structured Programming Approach
  • Reduces Program Size:

The piece of code that needs to be executed, or the piece of code that is repeated in different parts of the program, can be written separately as a function and stored in a place in memory. Whenever and wherever needed, the programmer can invoke the function and use the code to be executed. Thus, the program size is reduced.


Having known about the function and its features let us see how to declare, define and call a function in a C++ program.


Declaring a Function:

It has been discussed that, in order for a variable to be used, it must be declared. Just like variables, it follows that function definitions must be declared. The general method of declaring a function is to declare the function in the beginning of the program.


The general format for declaring a function is


return_datatype function name(arguments);


Suppose we have a function named as exforsys which return nothing from the function it is declared as


void exforsys( );


This declared would inform the compiler that the presence of the function exforsys is there in the program. In the above the return type void tells the compiler that the function has no return value and also the empty braces ( ) indicate that the function takes no arguments.


Defining a function:

The definition is the place where the actual function program statements or in other words the program code is placed.


The general format of the function definition is as follows:


return_datatype functionname(arguments) //Declarator
{
program statements //Function Body
……..
……….
}


In the above the declarator must match the function declaration already made. That is the function name, the return type and the number of arguments all must be same as the function declaration made. In fact if arguments are declared and defined. The order of arguments defined here must match the order declared in the function declaration.


After the declarator the braces starts and the function body is placed. The function body has the set of program statements which are to be executed by the function. Then the function definition ends with } ending braces.


For example let us see how to define a function exforsys declared as void that prints first five integers.


void exforsys( )
{
int i;
for (i=1;i<=5;i++)
cout<< i;
}


The output of the function when it is called would be


12345


Calling the function:

The function must be called for it to get executed. This process is performed by calling the function wherever required.


The general format for making the function call would be as follows:


functionname();


When the function is called the control, transfers to the function and all the statements present in the function definition gets executed and after which the control, returns back to the statement following the function call.


In the above example when the programmer executes the function exforsys, he can call the function in main as follows:


exforsys();


Let us see a complete program in C++ to help the programmer to understand the function concepts described above:

#include
void main( )
{
void exforsys( ); //Function Declaration
exforsys( ); //Function Called
cout<<”\n End of Program”;
}


void exforsys( ) //Function Definition
{
int i;
for(i=1;i<=5;i++)
cout<< i;
}


The output of the above program is


12345

my Learnings of the Week

This week we just have an activity. . .

Our problem is to write a program containing a function that will change the five-digit number to its reverse form.

example:

☺inputed value: 54321
☺output: 12345



The Solution:

#include
#define p printf
#define s scanf
main()
{
int x;
clrscr();
p("enter a fine digit number:");
s("%d",&x);
reverse(x);
getch();
}

reverse(int c)
{
int a,b;
for (a=1;a<=5;a++)
{
b=c%10;
p("%d",b);
c=c/10
}
}

Teaching Ur Self

A Function Defined

First the definition: A function is a named, independent section of C code that performs a specific task and optionally returns a value to the calling program. Now let's look at the parts of this definition:

  • A function is named. Each function has a unique name. By using that name in another part of the program, you can execute the statements contained in the function. This is known as calling the function. A function can be called from within another function.
  • A function is independent. A function can perform its task without interference from or interfering with other parts of the program.
  • A function performs a specific task. This is the easy part of the definition. A task is a discrete job that your program must perform as part of its overall operation, such as sending a line of text to a printer, sorting an array into numerical order, or calculating a cube root.
  • A function can return a value to the calling program. When your program calls a function, the statements it contains are executed. If you want them to, these statements can pass information back to the calling program.

A program that uses a function to calculate the cube of a number.

Enter an integer value: 100
The cube of 100 is 1000000.
Enter an integer value: 9
The cube of 9 is 729.
Enter an integer value: 3
The cube of 3 is 27.
 
Demonstrates a simple function
   #include 
 
   long cube(long x);
 
   long input, answer;
 
   main()
   {
     printf("Enter an integer value: ");
     scanf("%d", &input);
     answer = cube(input);
     /* Note: %ld is the conversion specifier for */
     /* a long integer */
     printf("\nThe cube of %ld is %ld.\n", input, answer);
 
     return 0;
  }
 
  /* Function: cube() - Calculates the cubed value of a variable */
  long cube(long x)
  {
     long x_cubed;
 
     x_cubed = x * x * x;
     return x_cubed;
  }

Saturday, December 13, 2008

What???

What is an argument?

An argument is the value that is passed from the program to the function call. This can also be considered as input to the function from the program from which it is called.

How to declare a function passed with argument

Declaring a function:

The general format for declaring the function remains the same as before except the data type passed as arguments in functions are in the same order in which it is defined in function.

The format for declaring a function with arguments is:


return_datatype functionname(datatype1,datatype2,..);


In this example, the data types are the types of data passed in the function definition as arguments to the function. Care must be taken to mention the number of arguments and the order of arguments in the same way as in function definition.

For example, suppose a function named exforsys takes two integer values as arguments in its functions definition and returns an integer value. The function declaration of exforsys would be written:


int exforsys(int,int);


Function Definition:

The function definition has the same syntax as the function definition previously defined, but with added arguments. The general format for defining a function with arguments is written as:


return_datatype functionname(datatype1 variable1,datatype2 variable2,..)
{
………….
Program statements
………….
return( variable);
}


In the above example, the return data type defines the data type of the value returned by the function. The arguments are passed inside the function name after parentheses with the data type and the variable of each argument. Care must be taken to mention the number of arguments and the order of arguments in the same way as in function declaration.


For example, if the function exforsys takes two integer values x and y and adds them and returns the value z the function definition would be defined as follows:


int exforsys(int x,int y)
{
int z;
z=x+y;
return(z);
}


In the above program segment, a return statement takes the general format


return(variable) ;


This value specified in the return as argument would be returned to the calling program. In this example, the value returned is z, which is an integer value, the data type returned by the function exforsys is mentioned as int.


Calling the function:

The calling of function takes the same syntax as the name of the function but with value for the arguments passed. The function call is made in the calling program and this is where the value of arguments or the input to the function definition is given.


The general format for calling the function with arguments is


functionname(value1,value2,…);


In the above exforsys function suppose integer value 5 and 6 are passed, the function call would be as follows:


exforsys(5,6);


As soon as the function call exforsys is made the control, transfers to the function definition and the assignment of 5 to x and 6 to y are made as below.


int exforsys(int x,int y)


exforsys(5,6);


int b;
b = exforsys(5,6);


The above statement assigns the returned value of the function exforsys. The value z is then added to the value of x and y to the variable b. So, variable b takes the value 11.


Let us see the whole program to understand in brief the concept of function with arguments


The output of the above program would be


#include
int exforsys(int,int);
void main()
{
int b;
int s=5,u=6;
b=exforsys(s,u);
cout<<”\n The Output is:”<
}

int exforsys(int x,int y)
{
int z;
z=x+y;
return(z);
}

The Output is:11

This and That

FACTS on Functions and Structured Programming

By using functions in your C programs, you can practice structured programming, in which individual program tasks are performed by independent sections of program code. "Independent sections of program code" sounds just like part of the definition of functions given earlier, doesn't it? Functions and structured programming are closely related.

The Advantages of Structured Programming

Why is structured programming so great? There are two important reasons:

  • It's easier to write a structured program, because complex programming problems are broken into a number of smaller, simpler tasks. Each task is performed by a function in which code and variables are isolated from the rest of the program. You can progress more quickly by dealing with these relatively simple tasks one at a time.
  • It's easier to debug a structured program. If your program has a bug (something that causes it to work improperly), a structured design makes it easy to isolate the problem to a specific section of code (a specific function).

A related advantage of structured programming is the time you can save. If you write a function to perform a certain task in one program, you can quickly and easily use it in another program that needs to execute the same task. Even if the new program needs to accomplish a slightly different task, you'll often find that modifying a function you created earlier is easier than writing a new one from scratch. Consider how much you've used the two functions printf() and scanf() even though you probably haven't seen the code they contain. If your functions have been created to perform a single task, using them in other programs is much easier.

Planning a Structured Program

If you're going to write a structured program, you need to do some planning first. This planning should take place before you write a single line of code, and it usually can be done with nothing more than pencil and paper. Your plan should be a list of the specific tasks your program performs. Begin with a global idea of the program's function. If you were planning a program to manage your name and address list, what would you want the program to do? Here are some obvious things:

  • Enter new names and addresses.
  • Modify existing entries.
  • Sort entries by last name.
  • Print mailing labels.

With this list, you've divided the program into four main tasks, each of which can be assigned to a function. Now you can go a step further, dividing these tasks into subtasks. For example, the "Enter new names and addresses" task can be subdivided into these subtasks:

  • Read the existing address list from disk.
  • Prompt the user for one or more new entries.
  • Add the new data to the list.
  • Save the updated list to disk.

Likewise, the "Modify existing entries" task can be subdivided as follows:

  • Read the existing address list from disk.
  • Modify one or more entries.
  • Save the updated list to disk.

You might have noticed that these two lists have two subtasks in common--the ones dealing with reading from and saving to disk. You can write one function to "Read the existing address list from disk," and that function can be called by both the "Enter new names and addresses" function and the "Modify existing entries" function. The same is true for "Save the updated list to disk."

Already you should see at least one advantage of structured programming. By carefully dividing the program into tasks, you can identify parts of the program that share common tasks. You can write "double-duty" disk access functions, saving yourself time and making your program smaller and more efficient.

Saturday, December 6, 2008

This Week..

This week,we randomly go to our computer laboratory to have an activity. Instead, we were having our reporting inside our class room.

Nearly close to our reports:
include

struct person
{
char *name;
int age;
};

int main()
{
struct person p;
p.name = "Jenny Turbo";
p.age = 25;
printf("%s",p.name);
printf("%d",p.age);
return 0;
}
This week, we just have a reporting about the given assignment by group!!!
its about the Functions and Structured Programming in CHAPTER 10.

Our problem is to have a program that will display A!-Excellent if the grade enter is greater than or equal to 90. B!-Good if it is lesser than 90 but greater than or equal to 75 and C!-Poor otherwise.

Our Answer:
#include
#define p printf

#define s scanf
main()
{
int x;
clrsr();
p("enter a grade:");
s("%d",& x);
Equigrade();
getch();
}

Equigrade (int x)

{
if(x>=90)
p("A!-Excellent");

if(x<90>=75)
p
("B!-Good");

if(x<75)
("C!-Poor")
}


Thats all!!!

Let's Get Further...

Structure Members Initialization:

As with arrays and variables, structure members can also be initialized. This is performed by enclosing the values to be initialized inside the braces { and } after the structure variable name while it is defined.


For Example:



#include
struct Customer
{
int custnum;
int salary;
float commission;
};


void main( )
{
Customer cust1={100,2000,35.5};
Customer cust2;
cout <<”\n Customer Number: “< cout <<”; Salary: Rs.“< cout <<”; Commission: Rs.“< cust2=cust1;
cout <<”\n Customer Number: “< cout <<”; Salary: Rs.“< cout <<”; Commission: Rs.“<
}



The output of the above program is


Customer Number: 100; Salary: Rs.2000; Commission: Rs.35.5
Customer Number: 100; Salary: Rs.2000; Commission: Rs.35.5


In the above example, the structure variable can be assigned to each by using assignment operator ‘=’. The programmer must consider that only structure variables of the same type can be initialized. If a programmer tries to initialize two structure variables of different types to each other it would result in compiler error.


It is wrong to initialize as:


Customer cust1;
cust1= {100,2000,35.5};


Nesting of structures:

Nesting of structures is placing structures within structure. How to declare nesting of structures? How to access structure members in case of nesting of structures?


For Example:



#include
struct course
{
int couno;
int coufees;
};

struct student
{
int studno;
course sc;
course sc1;
};

void main( )
{
student s1;
s1.studno=100;
s1.sc.couno=123;
s1.sc.coufees=5000;
s1.sc1.couno=200;
s1.sc1.coufees=5000;
int x = s1.sc.coufees + s1.sc1.coufees;
cout<< “\n Student Number: ”< cout<<”\n Total Fees: Rs.”<< x;
}



The output of the above program is


Student Number: 100
Total Fees: Rs.10000


In the above example, the structure course is nested inside the structure student. To access such nested structure members, the programmer must use dot operator in the above case twice to access the nested structure members.


In the above example:


s1.sc.couno


s1 is the name of the structure variable. sc is the member in the outer structure student. couno is the member in the inner structure course. This is how nested structure members are accessed.

One more important feature of C++ structure is it can hold both data and functions. This is in contrast to C where structures can hold only data. Though C++ structures can hold both data and functions, most classes are used for the purpose of holding both data and functions and structures are used to hold data.

Saturday, November 29, 2008

Structure and function...

For the continuation of our lesson in structure and function of programming...

I also learned about the following:

<#include

  • sqrt(x)
  • fabs(x) - calculates the absolute value of a number
  • ceil(x) - ceil (11.25)=12
  • floor(x) - floor(11.25)=11
  • sin(x)
  • cos(x)
  • tan(x)
  • pow(x)

C Program Structure

A C program basically has the following form:

  • Preprocessor Commands
  • Type definitions
  • Function prototypes -- declare function types and variables passed to function.
  • Variables
  • Functions

We must have a main() function.


A function has the form:


type function_name (parameters)
{
local variables

C Statements

}

If the type definition is omitted C assumes that function returns an integer type. NOTE: This can be a source of problems in a program.

So returning to our first C program:


/* Sample program */

main()
{

printf( ``I Like C \n'' );
exit ( 0 );

}
NOTE:
  • C requires a semicolon at the end of every statement.
  • printf is a standard C function -- called from main.
  • \n signifies newline. Formatted output -- more later.
  • exit() is also a standard function that causes the program to terminate. Strictly speaking it is not needed here as it is the last line of main() and the program will terminate anyway.

Let us look at another printing statement:
printf(``.\n.1\n..2\n...3\n'');

The output of this would be:


.
.1
..2
...3




For What???

C++ Structure

What is a Structure?

Structure is a collection of variables under a single name. Variables can be of any type: int, float, char etc. The main difference between structure and array is that arrays are collections of the same data type and structure is a collection of variables under a single name.


How to declare and create a Structure

Declaring a Structure:

The structure is declared by using the keyword struct followed by structure name, also called a tag. Then the structure members (variables) are defined with their type and variable names inside the open and close braces { and }. Finally, the closed braces end with a semicolon denoted as ; following the statement. The above structure declaration is also called a Structure Specifier.

Example:


Three variables: custnum of type int, salary of type int, commission of type float are structure members and the structure name is Customer. This structure is declared as follows:



In the above example, it is seen that variables of different types such as int and float are grouped in a single structure name Customer.

Arrays behave in the same way, declaring structures does not mean that memory is allocated. Structure declaration gives a skeleton or template for the structure.

After declaring the structure, the next step is to define a structure variable.


How to declare Structure Variable?

This is similar to variable declaration. For variable declaration, data type is defined followed by variable name. For structure variable declaration, the data type is the name of the structure followed by the structure variable name.

In the above example, structure variable cust1 is defined as:



What happens when this is defined? When structure is defined, it allocates or reserves space in memory. The memory space allocated will be cumulative of all defined structure members. In the above example, there are 3 structure members: custnum, salary and commission. Of these, two are of type in and one is of type float. If integer space allocated by a system is 2 bytes and float four bytes the above would allo9acter 2bytes for custnum, 2 bytes for salary and 4 bytes for commission.

For example:

A programmer wants to assign 2000 for the structure member salary in the above example of structure Customer with structure variable cust1 this is written as:


chapter 10_con't

This blog is the continuation of my last blog. . .

This is my additional learnings. . .

Type of functions

Void Functions – which does not return any value when invoked.

Function that returns a value once invoked.

Actual and Formal Parameters

Actual Parameters are the variables found in the function call whose values will be passed to the formal parameters of the called function.

Formal Parameters are the variables found in the function header that will receive from the actual parameters.


That's all. . .

Sunday, November 23, 2008

Chapter 10_discussion

In our discussion this week, we are finished with our lesson about looping! And we are now in Chapter 10 which is about the Functions and Structured Programming This includes the following facts:

- In functions and structured programming, it is a C Program that is composed at least one function which is the main() function and it executes the program that begins with main() and also ends with the main() function. It is also composed of other functions aside from main() function.

- The functions are defined as the “building blocks of C” in which all program activity occurs. It is also called as a subprogram or subroutine. It performs a task, operation or computation then may return to the calling part of the program. Other functions can be executed by the program through a “function call”. This function call is used to call a function to execute C statements found inside the function body.

The General form of a Function

function_type function_name (parameters list)

{

body of the function;

}

Where:

= function_type specifies the type of value that the function will return.

= function_name is any valid identifier name which will name the function.

= Parameters list is a comma separated list of variables that receive the values when the function is called.

= body of the function is composed of valid c statements that the function will execute.

- The types of functions include the Void Functions which does not return any value when invoked and the Functions that return a value once invoked.

- In parameters list, there are two kinds; the actual parameters are the variables found in the function call whose values will be passed to the formal parameters of the called functions and the Formal Parameters are the variables found in the function header that will receive from the actual parameters.

Call by Value – in this method, the values of the actual parameters are passed to the formal parameters. The changes that will happen to the values of the formal parameters inside the function will not affect the values of the actual parameters.

Pass by Value – in this method, the actual parameters pass their value to the formal parameters. The changes that will happen to the values of the formal parameters inside the function will affect the values of the actual parameters.

<#include

= sqrt(x)

= fabs(x) - calculates the absolute value of a number

= ceil(x) - ceil (11.25)=12

= floor(x) - floor(11.25)=11

= sin(x)

= cos(x)

= tan(x)

= pow(x,y)


This are one of the facts that is important in this chapter! ♥

My Learnings of the Week

For this week we've taking up about FUNCTIONS AND STRUCTURED PROGRAMMING...

  • A c program is composed of at least one function definition, that is the main() function.
  • Execution of the program begins with main() and also ends with the main() function.
  • However, a C program can also be composed of other functions aside from the main().
  • The c program presented in previous slide is composed of 3 functions: the main function, the function greet1 and the function greet2.
  • Therefore we can say that we can create a program that is composed of other function aside from the main function.

Example:

#include

main()

{
clrscr( );

printf (“Hi”);

greet1( );

greet2( );

getch( );

}

greet1 ( )

{

printf ( “Hello”);

}

greet2 ( )

{

printf (“How are you”);

}

Output:

Hi! Hello! How are you?

Functions

  • Functions are the building blocks of C in which all program activity occurs.
  • A function is also called a subprogram or subroutine. It is a part of a C program that performs a task, operation or computation then may return to the calling part of the program.
  • Other functions aside from the main( ) can only be executed by the program through a “function call”.
  • Note: Function call is a C statement that is used to call a function to execute C statements found inside the function body.
  • Going back to the example, greet1( ); is an example of a function call, calling the function greet ( ).

Type of Functions

  • Void Functions – which does not return any value when invoked.
  • Function that returns a value once invoked.

Actual and Formal Parameters

  • Actual Parameters are the variables found in the function call whose values will be passed to the formal parameters of the called function.
  • Formal Parameters are the variables found in the function header that will receive from the actual parameters.

Call by value

  • In the method call by value, the values of the actual parameters are passed to the formal parameters.
  • Changes that happen to the values of the formal parameters inside the function will not affect the values of the actual parameters.

Pass by value or Call by reference

  • The actual parameters also pass their value to the formal parameters.
  • But the changes that happen to the values of the formal parameters inside the function will affect the values of the actual parameters.
  • This is because the actual address of the variables is passed using the address of operator (&) together with the pointer operator (*).

Saturday, November 22, 2008

I Found Something!

Concepts of Arrays in C++

In this C++ Tutorial you will learn about Concepts of Arrays in C++, What is an array?, How to access an array element, Declaration of Array and How to Access Array Elements.


What is an array?

An array is a group of elements of the same type that are placed in contiguous memory locations.


How to access an array element?

You can access an element of an array by adding an index to a unique identifier.


For example


Suppose Exforsys is an array that has 4 integer values in it that is of int data type, then Exforsys is internally represented as:



0


1


2


3


Exforsys
Data Type : int







.
Declaration of Array:

Just like variables, We have to declare arrays before using them. The general syntax for declaring an array is


data type array name[number of elements];


In the above example the declaration of array Exforsys would be written as:


int Exforsys[4];


One of the key points when declaring arrays is the number of elements defined in the array argument must be a constant value. The size of the array must be known before its execution. This relates to the concept of dynamic memory allocation in C++ which will be covered later in the tutorial.


After declaration the next step is the initialization of array values.


Initialization of array:

If a programmer wants to initialize an array elements it can be done by specifying the values enclosed within braces { }.


For example, using the array Exforsys, if a programmer wants to initialize integer values 10, 20, 30, 40 respectively to each of the array positions it can be written.


int Exforsys[4] = {10,20,30,40};


So the above array would take values as below



0


1


2


3


Exforsys
Data Type : int


10


20


30


40





One interesting fact is that the size of the array element can also be left blank, in which case the array takes the size of the array as the number of elements initialized within { }.


For example if the array takes the form as


int Exforsys = {10,20,30,40,50};


Then the size of the array Exforsys is 5 which is the number of elements initialized within { }.


Now the next step is to know how to access the array elements.


How to Access Array Elements:

Just like variable sit is possible to access any element of the array for reading or modifying.


The general format for accessing arrays:


array name[index]


For example in the above example of array initialized with


int Exforsys[4] = {10,20,30,40};


When a programmer wants to access the 30 this can be written:


Exforsys[2]


Note that the array starts with index 0 and hence to access third element namely 30 one has to write array name with index 2.

Let us see the whole concept with a example:

#include <iostream.h>
int Exforsys[ ] = { 10,20,30,40,50};
int i, outp=0;
void main()
{
for(i=0;i<5;i++)
{
outp=outp+ Exfosys[i];
}
cout<< outp;
}

.
The output of the above program is:


150

Sunday, November 16, 2008

This week we don't have a session with our teacher Mr. Ernie Balbuena because I am one of the Science Investigatory Project Regional DepEd-Intel Contestant. But based on my classmates, our lesson is still about looping or interative satements. . . ♥

Saturday, November 15, 2008

Just Finding Out New...

C++ Tutorials

Created by Bjarne Stroustrup of AT&T Bell Labs as an extension of C, C++ is an object-oriented computer language used in the development of enterprise and commercial applications. Microsoft’s Visual C++ became the premier language of choice among developers and programmers.

As a procedural programming language, C++ uses program structures such as i/o (input/output), assignment statement, iterative statements, conditional statements and subprograms. Data structures of C++ include integer, real, char, arrays, structs and pointers.

Employment opportunities are numerous and well paid for C++ programmers and developers looking to work in the field of Software Engineering or as an IT Professional. Oftentimes, C++ Professionals will also be familiar with C, Linux, Unix, Java, .NET and VB (Visual Basic). Developers working with C++ can expect to participate in a variety of programming opportunities: developing systems for trading applications for an Investment Bank, developing cutting edge software applications for groundbreaking new technologies (Smartphone, PDA, etc.) to creating applications for 3-D Imaging Software or spectroscopic systems.

C++ Tutorials available in this section include explanations for simple to more advanced concepts of C++ in detail with sample coding information. A new programmer or developer interested in learning about C++ programming language and finding out why C++ is one of the most widely used programming languages for creating large-scale applications can utilize the tutorials and articles on C++ made available in this section.

Out of Class...

For this week, we didn't tackle any any lesson since I and my co-contestants in Intel-Philippines are busy with our research entries...But according to my classmates we we're still in iterative statements..

Research:

Iteration may be performed over an arithmetic progression of integers or over any finite enumerated structure. Iterative statements may be nested. If nested iterations occur over the same enumerated structure, abbreviations such as for x, y in X do may be used; the leftmost identifier will correspond to the outermost loop, etc.

do-while

The do-while statement is a post-test loop, meaning that the evaluation of the escape condition is only done after the code inside the loop has been executed. This means that the body of the loop is always executed at least once before the expression is evaluated.


while

The while statement is a pretest loop. This means the evaluation of the escape condition is done before the code inside the loop has been executed. Because of this, it is possible that the body of the loop is never executed.


for

The for statement is also a pretest loop with the added capabilities of variable initialization before entering the loop and defining postloop code to be entered.


for-in

The for-in statement is a strict iterative statement. It is used to enumerate the properties of an object.

Sunday, November 9, 2008

learnings of the week

In last week’s discussion, we tackled about the iterative statements or commonly known as loops. This allows a set of instruction to be executed or performed several until conditions are met. It can be predefined as in the loop, or open ended as in while and do-while.


There are three types of Iterative Statements
1. The For statements
2. The While statements
3. The Do-While statements


The For statements

The For statement or for loop is considered as a predefined loop because the number or times it iterates to perform its body is predetermined in the loop’s definition. The For loop contains a counter whose values determine the number of times the loop iterates. The iteration stops upon reaching the number of times specified in the loop.


The general form of the for statement is:
for (initialization; condition; increment)
{
statement_sequence;
}

Where:
for is a reserve word in C Initialization is an assignment statement that is used to set the loop’s counter.
Condition is a relational boolean expression that determines when the loop will exit.
Increment defines how the loop’s counter will change each time the loop is separated.
Statement sequence may either be a single C statement or a block of C statements that make up the loop body.



The While statement


The while statement or while loop is an open-ended or event-controlled loop. The while loop iterates while the condition is TRUE (1). When it becomes FALSE (0), the program control passes to the line after the loop code.

The general form of the while statement is:

while (condition)
{
statement_sequence;
}


The Do-While statement


The second type of open-ended or event-controlled loop is the do-while statement or do-while loop.

The general form of the do-while statement is:

do
{
statement_sequence;
} while (condition);

= = = END = = =

Saturday, November 8, 2008

first learnings of the week

This week we tackled about Iterative statements (loops). What is iterative statement?


Iterative statements (loops) allow a set of instruction to be executed or performed several until condition are met. It can be predefined as in the loop, or open ended as in while and do-while.

Types of Iterative Statements

1. The For statements

2. The While statements

3. The Do-While statements



♥ The For statements ♥

The For statement or for loop is considered as a predefined loop because the number or times it iterates to perform its body is predetermined in the loop’s definition.
The For loop contains a counter whose values determine the number of times the loop iterates. The iteration stops upon reaching the number of times specified in the loop.
The general form of the for statement is:

for (initialization; condition; increment)
{
statement_sequence;
}

Where:
for is a reserve word in C
Initialization is an assignment statement that is used to set the loop’s counter.
Condition is a relational boolean expression that determines when the loop will exit.
Increment defines how the loop’s counter will change each time the loop is separated.
Statement sequence may either be a single C statement or a block of C statements that make up the loop body.
▼ Example:
Write a program that will print the numbers 1 to 10 using a for statement.

#include
int x;
main()
{
for (x=1; x<=10; x++)
printf (“%d\n”,x);
getch();
}
sample output:
1
2
3
4
5
6
7
8
9
10
♥ The While statement ♥
The while statement or while loop is an open-ended or event-controlled loop.
The while loop iterates while the condition is TRUE (1).
When it becomes FALSE (0), the program control passes to the line after the loop code.
The general form of the while statement is:

while (condition)
{
statement_sequence;
}
▼ Example:
Write a program that will print the numbers 1 to 10 using while statement.
#include
x;
main()
{
x=1;
while (x<=10)
{ printf (“%d\n”,x);
x++;
}
getch();
}
output:
1
2
3
4
5
6
7
8
9
10

♥ The Do-While statement ♥
The second type of open-ended or event-controlled loop is the do-while statement or do-while loop.
The general form of the do-while statement is:
do
{
statement_sequence;
} while (condition);

▼ example:
Write a program that will get the average of all integers from 1 to 10 using do-while loop.

#include
int x, sum;
float average;
main()
{
sum = 0;
x++;
do
{
sum = sum + x;
x++;
}while (x<=10) average = sum / 10.00;
printf (“the computed average is %.2f\n”, average);
getch();
}
Output: The computed average is 5.50.
This is our new lesson in our TLE subject. . .

Iterative statements(Loops)...what is it???

Iterative statements(Loops)...

what is it???...

Iterative statements(Loops)

-allow a set of instruction to be executed or performed several until condition are met. It can be predefined as in the loop, or open ended as in while and do-while.

-a type of control structure. It allows the repetition of a block of statements according to a condition.


Types of Iterative Statements:

I. The For statements

II. The While statements

III. The Do-While statements


The For statements

-The For statement or for loop is considered as a predefined loop because the number or times it iterates to perform its body is predetermined in the loop’s definition.

-The For loop contains a counter whose values determine the number of times the loop iterates. The iteration stops upon reaching the number of times specified in the loop.

The general form of the for statement is:

for (initialization; condition; increment)

{

statement_sequence;

}

Where:

-for is a reserve word in C

-Initialization is an assignment statement that is used to set the loop’s counter.

-Condition is a relational boolean expression that determines when the loop will exit.

-Increment defines how the loop’s counter will change each time the loop is separated.

-Statement sequence may either be a single C statement or a block of C statements that make up the loop body.


The While statement
-
The while statement or while loop is an open-ended or event-controlled loop.

-The while loop iterates while the condition is TRUE (1).

-When it becomes FALSE (0), the program control passes to the line after the loop code.


The general form of the while statement is:

while (condition)

{

statement_sequence;

}

where:

-While is a reserved word in C

-Condition is a relational expression that determines when the loop will exit.

-Statement_sequence may either be a single C statement or a block of C statements that make up the loop body.


The Do-While statement

-The second type of open-ended or event-controlled loop is the do-while statement or do-while loop.

The general form of the do-while statement is:

do

{

statement_sequence;

} while (condition);


Where:

-While and do are reserved words in C Condition is a relational expression that determines when the loop will exit.

-Statement_sequence may either be a single C statement or a block C statements that make up the loop body.

-Do-While is a variation of the while statement which checks the condition at the bottom / end of the loop.

-This means that a do-while loop “always executes at least once”.

-In the do-while loop, when the condition evaluates to TRUE (1), the loop body will be executed, but when FALSE (0), program control proceeds to the next instruction after the do-while loop.