44
Computer Programming-I Page | 1 INPUT AND OUTPUT #include <iostream> Lines beginning with a hash sign (#) are directives for the preprocessor. They are not regular code lines with expressions but indications for the compiler's preprocessor. In this case the directive #include <iostream> tells the preprocessor to include the iostream standard file. This specific file (iostream) includes the declarations of the basic standard input-output library in C++, and it is included because its functionality is going to be used later in the program. int main () This line corresponds to the beginning of the definition of the main function. The main function is the point by where all C++ programs start their execution, independently of its location within the source code. It does not matter whether there are other functions with other names defined before or after it - the instructions contained within this function's definition will always be the first ones to be executed in any C++ program. For that same reason, it is essential that all C++ programs have a main function. The word main is followed in the code by a pair of parentheses (()). That is because it is a function declaration: In C++, what differentiates a function declaration from other types of expressions are these parentheses that follow its name. Optionally, these parentheses may enclose a list of parameters within them. The word main is followed in the code by a pair of parentheses (()). That is because it is a function declaration: In C++, what differentiates a function declaration from other types of expressions are these parentheses that follow its name. Optionally, these parentheses may enclose a list of parameters within them. Right after these parentheses we can find the body of the main function enclosed in braces ({}). What is contained within these braces is what the function does when it is executed. return 0; The return statement causes the main function to finish. return may be followed by a return code (in our example is followed by the return code 0). A return code of 0 for the main function is generally interpreted as the program worked as expected without any errors during its execution. This is the most usual way to end a C++ console program. 1. Write a program that displays a message and values of integer and character variables. #include <iostream.h> #include<conio.h> Int main() Prepared by: Miss Humera Gull Department of Information System, KKU

C++ practical

Embed Size (px)

Citation preview

Page 1: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 1

INPUT AND OUTPUT

#include <iostream>Lines beginning with a hash sign (#) are directives for the preprocessor. They are not regular code lineswith expressions but indications for the compiler's preprocessor. In this case the directive #include<iostream> tells the preprocessor to include the iostream standard file. This specific file (iostream)includes the declarations of the basic standard input-output library in C++, and it is included because itsfunctionality is going to be used later in the program.

int main ()This line corresponds to the beginning of the definition of the main function. The main function is the pointby where all C++ programs start their execution, independently of its location within the source code. Itdoes not matter whether there are other functions with other names defined before or after it - theinstructions contained within this function's definition will always be the first ones to be executed in anyC++ program. For that same reason, it is essential that all C++ programs have a main function.The word main is followed in the code by a pair of parentheses (()). That is because it is a functiondeclaration: In C++, what differentiates a function declaration from other types of expressions are theseparentheses that follow its name. Optionally, these parentheses may enclose a list of parameters withinthem.

The word main is followed in the code by a pair of parentheses (()). That is because it is a functiondeclaration: In C++, what differentiates a function declaration from other types of expressions are theseparentheses that follow its name. Optionally, these parentheses may enclose a list of parameters withinthem.Right after these parentheses we can find the body of the main function enclosed in braces ({}). What iscontained within these braces is what the function does when it is executed.

return 0;The return statement causes the main function to finish. return may be followed by a return code (in ourexample is followed by the return code 0). A return code of 0 for the main function is generally interpretedas the program worked as expected without any errors during its execution. This is the most usual way toend a C++ console program.

1. Write a program that displays a message and values of integer and character variables.

#include <iostream.h>

#include<conio.h>

Int main()

{

Int n = 10;

Char ch = ‘*’;

Cout<<”Testing output….”;

Cout<<n;

Cout<<ch;

Getch();

Return 0;

}

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 2: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 2

2. Write a program that adds two digit numbers and shows the sum on screen.

#include<iostream.h>

#include<conio.h>

Int main()

{

Clrscr();

Int n,m,res;

n = 24;

m = 41;

Res = n + m;

Cout<<n<<” + “<<m<<” = “<<res;

Getch();

Return 0;

}

3. Write a program to calculate and print the area of a square.

#include<iostream.h>

#include<conio.h>

int main()

{

Int height, width, area;

Height = 5;

Width = 4;

Area = height*width;

Cout<<”Area of Square = “<<area;

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 3: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 3

Getch ();

Return 0;

}

ESCAPE SEQUENCE

Escape sequences are special characters used in control string to modify the format of output. These characters are not displayed in the output. These characters are used in combination with backslash “\”. The backslash is known as escape character.

Different escape sequences used in c language are as follows:

Escape Sequence Purpose\a Alarm\b Backspace\f Form feed\n New line\r Carriage return\t Tab\’ Double quote\” Double quote

Cout<<”Hello \aWorld”; will display

Hello World

After displaying “Hello”, the computer will play beep and then print “World”.

4. Write a program to display the following output using single cout statement.

*

* *

* * *

* * * *

* * * * *

# include<iostream.h>

# include <conio.h>

Void main()

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 4: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 4

{

Cout<<”*\n**\n***\n****\n*****”;

Getch();

}

5. Write a program that inputs name, age and address from the user and displays it on the screen.

#include <iostream.h>

#include<conio.h>

Void main()

{

Char name[25], city[30];

Int age;

Cout<<”Enter your age:”;

Cin>>age;

Cout<<”Enter your name:”;

Cin>> name;

Cout<<”Enter your city:”;

Cin>>city;

Cout<<”Your name is “<<name;

Cout<<”Your city is “<<city;

Cout<<”Your age is “<<age;

Getch();

}

6. Write a program inputs two numbers, swaps the values and then displays them.

#include<iostream.h>

#include<conio.h>

Void main()

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 5: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 5

{

Int a, b, temp;

Cout<<”Enter the first number:”;

Cin>>a;

Cout<<”Enter the second number:”;

Cin>>b;

Cout<<”You input the numbers as “<<a<<” and “<<b<<endl;

Temp = a;

A = b;

B = temp;

Cout<<”The values after swapping are “<<a<<” and “<<b<<endl;

}

CONDITIONAL STRUCTURES

If Structure

Syntax

The syntax of if statement is as follows:

If (condition)

Statement;

The above syntax is used for single statement. A set of statements can also be made conditional. In this case, these statements are written in curly brackets {}. The set of statements is also called compound statements.

The syntax for compound statements in if statement is as follows:

If (condition)

{

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 6: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 6

Statement 1;

Statement2;

.

.

.

Statement n;

}

7. Write a program that inputs marks and displays “Congratulations! You have passed” if the marks are 60 or more.

#include<iostream.h>

#include<conio.h>

Int main()

{

Int marks;

Clrscr();

Cout<<”Enter your marks:”;

Cin>>marks;

If (marks>=60)

Cout<<”Congratulations! You have passed.”;

Getch();

}

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 7: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 7

8. Write a program that inputs two numbers and finds if both are equal.

#include<iostream.h>

#include<conio.h>

Int main()

{

Int a,b;

Clrscr();

Cout<<”Enter a number:”;

Cin>>a;

Cout<<”Enter a number:”;

Cin>>b;

If(a==b)

Cout<<”Both numbers are equal.”;

Getch();

Return(0);

}

9. Write a program that inputs two numbers and finds if second numbers is square of first number.

#include<iostream.h>

#include<conio.h>

Int main()

{

Int a,b;

Clrscr();

Cout<<”Enter a number:”;

Cin>>a;

Cout<<”Enter second number:”;

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 8: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 8

Cin>>b;

If(a*a==b)

Cout<<”second number is square of 1st number.”;

Getch();

Return(0);

}

10. Write a program that inputs marks of three subjects. If the average of marks is more than 80, it displays two messages ”You are above standard!” and “Admission granted!”

# include<iostream.h>

#include<conio.h>

Int main()

{

Int sub1,sub2,sub3;

Float avg;

Clrscr();

Cout<<”Enter marks of first subject:”;

Cin>>sub1;

Cout<<”Enter marks of second subject:”;

Cin>>sub2;

Cout<<”Enter marks of second subject:”;

Cin>>sub3;

Avg= (sub1+sub2+sub3)/3.0;

If(avg>80)

{

Cout<<”You are above standard!\n”;

Cout<<”Admission granted”;

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 9: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 9

}

Getch();

Return(0);

}

11. Write a program that inputs a number and finds whether the number is even or odd.

#include<iostream.h>

#include<conio.h>

Int main()

{

Int n;

Clrscr();

Cout<<”Enter a number:”;

Cin>>n;

If(n%2==0)

Cout<<”The number is even.”;

If(n%2!=0)

Cout<<”The number is odd.”;

Getch();

Return(0);

}

12. Write a program that inputs three numbers and displays maximum number.

#include<iostream.h>

#include<conio.h>

Int main()

{

Int a,b,c,max;

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 10: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 10

Clrscr();

Cout<<”Enter first number:”;

Cin>>a;

Cout<”Enter second number:”;

Cin>>b;

Cout<<”Enter third number:”;

Cin>>c;

Max=a;

If(b>max)

Max=b;

If(c>max)

Max=c;

Cout<<”The maximum number is “<<max;

Getch();

Return(0);

}

13. Write a program that inputs three numbers and displays maximum number.

#include <iostream.h>

#include<conio.h>

Int main()

{

Int a,b,c,max;

Clrscr();

Cout<<”Enter first number:”;

Cin>>a;

Cout<<”Enter second number:”;

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 11: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 11

Cin>>b;

Cout<<”Enter third number:”;

Cin>>c;

Max=a;

If(b>max)

Max=b;

If(c>max)

Max=c;

Cout<<”The maimum number is”<<max;

Getch();

Return(0);

}

14. Write a program to input a number and determine whether it is positive, negative or 0.

#include <iostream.h>

# include <conio.h>

Int main()

{

Int n;

Cout<<”Enter a number”;

Cin>>n;

If(n>0)

Cout<<”The number is positive”;

If(n<0)

Cout<<”The number is positive”;

If(n<0)

Cout<<”The number is negative”;

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 12: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 12

If(n==0)

Cout<<”The number is zero”;

Return(0);

}

15. Write a program to input a number and determine whether it is positive, negative or 0;

#include<iostream.h>

#include<conio.h>

Int main()

{

Int n;

Cout<<”Enter a number”;

Cin>>n;

If(n>0)

Cout<<”The number is positive”;

If(n<0)

Cout<<”The number is negative”;

If(n==0)

Cout<<”The number is zero”;

Return(0);

}

‘If-else’ Structure

If else statement is another type of if statement. It executes one block of statement(s)

When the condition is true and the other when it is false. In any situation, one block is executed and the other is skipped. In if else statement:

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 13: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 13

Both blocks of statement can never be executed.

Both blocks of statements can never be skipped.

Syntax

Its syntax is as follows:

If(condition)

Statement;

Else

statement;

5. Write a program that inputs marks and displays “Congratulations! You have passed” if the marks are 60 or more.

#include<iostream.h>

#include<conio.h>

Int main()

{

Int marks;

Clrscr();

Cout<<”Enter your marks:”;

Cin>>marks;

If (marks>=60)

Cout<<”Congratulations! You have passed.”;

Else

Cout<<”Sorry! You are fail.”;

Getch();

}

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 14: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 14

6. Write a program that inputs a number and finds whether it is even or odd using if else structure.

#include<iostream.h>

#include<conio.h>

Int main()

{

Int n;

Clrscr();

Cout<<”Enter a number:”;

Cin>>n;

If(n%2==0)

Cout<<n<<”is even.”;

Else

Cout<<n<<”is odd.”;

Getch();

Return(0);

}

7. Write a program that inputs a year and finds whether it is a leap year and finds whether it is a leap year or not using else structure.

#include <iostream.h>

# include<conio.h>

Int main()

{

Clrscr();

Cout<<”Enter a year:”;

Cin>>y;

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 15: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 15

If(y % 4 == 0)

Cout<<y<<”is a leap year.”;

Else

Cout<<y<<”is not a leap year.”;

Getch();

Return(0)

}

Multiple ‘if-else-if’ Structure

If-else-if statement can be used to choose one block of statements from many blocks of statements. It is used when there are many options and only one block of statements should be executed on the basis of a condition.

Syntax

The syntax of this structure is:

If(condition)

{

Block 1;

}

Else if (condition)

{

Block 2;

}

Else if (condition)

{

Block 3;

}

.

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 16: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 16

.

.

Else

{

Block n;

}

8. Write a program that inputs test score of a student and displays his grade on the following criteria:

Test Score Grade

>=90 A

80-89 B

70-79 C

60-69 F

#include<iostream.h>

#include<conio.h>

Int main()

{

Int score;

Clrscr();

Cout<<”Enter you test score:”;

Cin>>score;

If(score>=90)

Cout<<”Your grade is A.”;

Else if(score>=80)

Cout<<”Your grade is B.”;

Else if(score>=70)

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 17: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 17

Cout<<”Your grade is C.”;

Else if(score>=60)

Cout<<”Your grade is D.”;

Else

Cout<<”Your grade is F.”;

Getch();

Return(0)

}

LOOPING STRUCTURES

‘While’ Loop

While loop is the simplest loop of C++ language. This loop executes one or more statements while the given condition remains true. It is useful when the number of iterations is not known in advance.

Syntax

The syntax of while loop is as follows:

While(condition)

Statement;

Compound Statement

Syntax

While(condition)

{

Statement 1;

Statement 2;

.

.

.

Statement n;

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 18: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 18

}

9. Write a program that displays “Pakistan” for five times using while loop.

#include <iostream.h>

#include<conio.h>

Int main()

{

Int n;

n=1;

While (n<=5)

{

Cout<<”Saudi Arabia”<<endl;

n++;

}

Getch();

}

10. Write a program that displays counting from 1 to 10 using while loop.

#include<iostream.h>

#include<conio.h>

Int main()

{

Int n;

N=1;

Clrscr();

While(n<=10)

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 19: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 19

{

Cout<<n<<endl;

N++;

}

Getch();

Return();

}

11. Write a program that displays first five numbers and their sum using while loop.

#include<iostream.h>

#include<conio.h>

Int main()

{

Int c, sum;

Clrscr();

C=1;

Sum=0;

While(c<=5)

{

Cout<<c<<enl;

Sum=sum +c;

C=c+1;

}

Cout<<”Sum is”<<sum;

Getch();

Return(0);

}

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 20: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 20

12. Write a program that displays first five numbers with their squares using while loop.

# include<iostream.h>

# include<conio.h>

Int main()

{

Int n;

N=1;

Clrscr();

While(n<=5)

{

Cout<<n<<” “<<n*n<<endl;

N++;

}

Getch();

Return(0);

}

13. Write a program that inputs a number from the user and displays a table of that number using while loop.

#include<iostream.h>

#include<conio.h>

Int main()

{

Int n,c;

Clrscr();

C=1;

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 21: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 21

Cout<<”Enter a number:”;

Cin>>n;

While(c<=10)

{

Cout<<n<<” * “<<c<<” = “<<n*c<<endl;

C=c+1;

}

Getch();

Return(0);

}

14. Write a program that inputs a number from the user and displays the factorial of that number using while loop.

# include<iostream.h>

#include<conio.h>

Int main()

{

Long int n,c,f;

Clrscr();

C=1;

F=1;

Cout<<”Enter a number:”;

Cin>>n;

While(c<=n)

{

F=f*c;

C=c+1;

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 22: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 22

}

Cout<<”Factorial of “<<n<<”is”<<f;

Getch();

Return(0);

}

15. Write a program that uses a while loop to enter a number from the user and then display it. The loop is terminated when the user enters -1.

#include<iostream.h>

#include<conio.h>

Int main()

{

Int n;

Clrscr();

N=1;

While(n!=-1)

{

Cout<<”Enter a number:”;

Cin>>n;

Cout<<”You entered “<<n<<enl;

}

Cout<<”End of program”;

Getch();

Return(0);

}

‘do-while’ Loop

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 23: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 23

Do-while is an iterative control in C++ language. This loop executed one or more statements while the given condition is true.

In this loop, the condition comes after the body of the loop. It is an important loop in a situation when the loop body must be executed at least once.

Syntax

The syntax of while loop is as follows:

Do

{

Statement 1;

Statement 2;

:

:

:

Statement n;

}

While(condition);

16. Write a program that displays back-counting from 10 to 1 using do-while loop.

# include<iostream.h>

# include<conio.h>

Int main()

{

Int c;

Clrscr();

C=10;

Do

{

Cout<<c<<endl;

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 24: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 24

C=c-1;

}

While(c>=1);

Getch();

Return();

}

17. Write a program that gets starting and ending point from the user and displays all odd numbers in the given range using do-while loop.

#include<iostream.h>

#include<conio.h>

Int main()

{

Int c,s,e;

Clrscr();

Cout<<”Enter starting number:”;

Cin>>s;

Cout<<”Enter ending number:”;

Cin>>e;

C=s;

Do

{

If(c%2!=0)

Cout<<c<<endl;

C=c+1;

}

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 25: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 25

While(c<=e);

Getch();

Return();

}

18. Write a program that reads the current state of a telephone line. The user should enter w for working state and d for dead state. Any other input should be invalid. Use do-while loop to force the user to enter a valid input value.

# include <iostream.h>

# include<conio.h>

Int main()

{

Char s;

Clrscr();

Do

{

Cout<<”Enter the current state of phone (\’w\’ for working \’d\’ for dead”;

Cin>>s;

}

While(s!= ‘w’ && s!=’d’);

Getch();

Return 0;

}

Pretest and Posttest in Loops

A pretest is a condition that is used to test for the completion of loop at the top of loop. In this type of loop, the statements inside the loop body can never execute if the terminating condition is false the first time it is tested.

Example

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 26: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 26

Following is an example of pretest condition. The statement in the body of loop cannot be executed if the condition is false.

N=0

While(n==0)

{

Loop body

}

A posttest is a condition that is used to test for the completion of loop at the bottom of loop. It means that the statements in the loop will always be executed at least once.

Example

Following is an example of posttest condition. The statements in the body of loop will be executed at least once even if the condition is false.

Do

{

Loop body

}

While(n==0)

‘for’ Loop

for loop executes one or more statement for a specified number of times. This loop is also called counter-controlled loop. It is the most flexible loop. That is why, it is the most frequently-used loop by the programmers.

Syntax

The syntax of for loop is as follows:

For(initialization;condition;increment/decrement)

{

Statement 1;

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 27: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 27

Statement2;

:

:

Statement n;

}

Initialization It specifies the starting value of counter variable. One or many variables can be initialized in this part. To initialize many variables, each variable is separated by comma.

Condition The condition is given as a relational expression. The statement is executed only if the given condition is true. If the condition is false, the statement is never executed.

Increment/decrement This part of loop specifies the change in counter variable after each execution of the loop. To change many variables, each variable must be separated by comma.

Statement Statement is the instruction that is executed when the condition is true. If two or more statements are used, these are given in braces {}. It is called the body of the loop.

Write a program that displays counting from 1 to 5 using for loop.

# include<iostream.h>

# include<conio.h>

Int main()

{

Int n;

For(n=1;n<=5;n++)

Cout<<n<<endl;

Getch();

}

Write a program that inputs table number and length of table and then displays the table using for loop.

# include<iostream.h>

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 28: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 28

#include<conio.h>

Int main()

{

Int tab,len,c;

Cout<<”Enter number for table:”;

Cin>>tab;

Cout<<”Enter length of table:”;

Cin>>len;

For(c=1;c<=len;c++)

Cout<<tab<<” * “<<c<<” = “<<tab*c<<endl;

Getch();

Return 0;

}

‘continue’ Statement

The continue statement is used in the body of the loop. It is used to move the control to the start of the loop body. When this statement is executed in the loop body, the remaining statements of current iteration are not executed. The control directly moves to the next iteration.

Example

# include<iostream.h>

#include<conio.h>

Int main()

{

Int x;

For(x=1;x<=5;x++)

{

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 29: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 29

Cout<<”Hello world!\n”;

Continue;

Cout<<”Knowledge is power.”;

Getch();

Return 0;

}

‘break’ Statement

The break statement is used in the body of the loop to exit from the loop. When this statement is executed in the loop body, the remaining iterations of the loop are skipped. The control directly moves outside the body and the statement that comes after the body executed.

Example

#include<iostream.h>

#include<conio.h>

Int main()

{

Int x;

For(int x=1; x<=5; x++)

{

Cout<<”Questioning\n”;

Break;

Cout<<”Gateway to knowledge”;

}

Cout<<”Bye”;

Getch();

Return 0;

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 30: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 30

}

ARRAYS

An array is a group of consecutive memory locations with same name and type. Array is a collection of different adjacent memory locations. All these memory locations have one collective name and type. The memory locations in the array are known as elements of array. The total number of elements in the array is called its length.

Each element in the array is accessed with reference to its position of location in the array. This position is called index or subscript. Each element in the array has a unique index. The index of first element is p and the index of last element is length-1. The value of the index Is written in brackets along with the name of array.

Arrays are used to store a large amount of similar kind of data. Suppose the user wants to store the marks of 100 students and declare 100 variables. It is time-consuming process to use these variables individually. This process can be simplified by using array. An array of 100 elements can be declared to store these values instead of 100 individual variables.

Advantages/Uses of Arrays

Some advantage of arrays are as follows:

Arrays can store a large number of values with single name.

Arrays are used to process many values easily and quickly.

The values stored in an array can be sorted easily.

A search process can be applied on arrays easily.

Declaring One Dimensional Array

A type of array in which all elements are arranged in the form of a list is known as one-dimensional array. It is also called single-dimensional array or linear list. It consists of one column or one row. The process specifying array name, length and data type is called array declaration.

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 31: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 31

Syntax

The syntax of declaring one-dimensional array is as follows:

Data-type identifier[Length];

Data-Type It indicates the data types of the values to be stored in the array.

Identifier It indicates the name of the array.

Length It indicates total number of elements in the array. It must be a literal constant or symbolic constant.

Example:

Int marks[5];

Loops have as purpose to repeat a statement a certain number of times or while a condition is fulfilled.

The while loop

Its format is:

while (expression) statement

and its functionality is simply to repeat statement while the condition set in expression is true.For example, we are going to make a program to countdown using a while-loop:

// custom countdown using while#include <iostream.h>#include<conio.h>int main (){int n;cout << "Enter the starting number > ";cin >> n;while (n>0) {cout << n << ", ";--n;}cout << "FIRE!/n";return 0;}

Enter the starting number > 88, 7, 6, 5, 4, 3, 2, 1, FIRE!

When the program starts the user is prompted to insert a starting number for the countdown. Then the while loopbegins, if the value entered by the user fulfills the condition n>0 (that n is greater than zero) the block that followsthe condition will be executed and repeated while the condition (n>0) remains being true.The whole process of the previous program can be interpreted according to the following script (beginning inmain):

1. User assigns a value to n2. The while condition is checked (n>0). At this point there are two posibilities:

* condition is true: statement is executed (to step 3)* condition is false: ignore statement and continue after it (to step 5)

3. Execute statement:

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 32: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 32

cout << n << ", ";--n;(prints the value of n on the screen and decreases n by 1)

4. End of block. Return automatically to step 25. Continue the program right after the block: print FIRE! and end program.

When creating a while-loop, we must always consider that it has to end at some point, therefore we must providewithin the block some method to force the condition to become false at some point, otherwise the loop willcontinue looping forever. In this case we have included --n; that decreases the value of the variable that is beingevaluated in the condition (n) by one - this will eventually make the condition (n>0) to become false after a certainnumber of loop iterations: to be more specific, when n becomes 0, that is where our while-loop and our countdownend.Of course this is such a simple action for our computer that the whole countdown is performed instantly withoutany practical delay between numbers.

1. Write a program that displays “King Khalid University” for five times using while loop.

#include <iostream.h>

#include<conio.h>

Int main()

{

Int n;

n=1;

While (n<=5)

{

Cout<<”King Khalid University”;

n++;

}

Getch();

Return 0;

}

2. Write a program that displays counting from 1 to 10 using while loop.

#include<iostream.h>

#include<conio.h>

Int main()

{

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 33: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 33

Int n;

N=1;

While(n<=10)

{

Cout<<n;

N++;

}

Getch();

Return();

}

3. Write a program that displays first five numbers and their sum using while loop.

#include<iostream.h>

#include<conio.h>

Int main()

{

Int c, sum;

c=1;

sum=0;

While(c<=5)

{

Cout<<c<<endl;

Sum= sum+c;

C=c+1;

}

Cout<<”sum is “<<sum;

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 34: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 34

Getch();

Return();

}

4. Write a program that displays first five numbers with their squares using while loop.

#include<iostream.h>

#include<conio.h>

Int main()

{

Int n;

N=1;

While(n<=5)

{

Cout<<n<<” “<<n*n<<endl;

N++;

}

Getch();

Return();

}

5. Write a program that inputs a number from the user and displays a table of that number using while loop.

#include<iostream.h>

#include<conio.h>

Int main()

{

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 35: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 35

Int n, c;

c=1;

cout<<”Enter a number:”;

cin>>;

While(c<=10)

{

Cout<<n<<”*”<<c<<”=”<<n*c<<endl;

C=c+1;

}

Getch();

Return();

}

6. Write a program that inputs a number from the user and displays the factorial of that number using while loop.

#include<iostream.h>

#include<conio.h>

Int main()

{

Long int n, c, f;

c=1;

f=1;

cout<<”Enter a number:”;

cin<<n;

While(c<=n)

{

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 36: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 36

F=f*c;

C=c+1;

}

Cout<<”Factorial of “<<n<< “is”<<f;

Getch();

Return 0;

}

The do-while loopIts format is:

do statement while (condition);

Its functionality is exactly the same as the while loop, except that condition in the do-while loop is evaluated afterthe execution of statement instead of before, granting at least one execution of statement even if condition isnever fulfilled. For example, the following example program echoes any number you enter until you enter 0.

// number echoer#include <iostream>#include<conio.h>int main (){unsigned long n;do {cout << "Enter number (0 to end): ";cin >> n;cout << "You entered: " << n << "\n";} while (n != 0);return 0;}

Enter number (0 to end): 12345You entered: 12345Enter number (0 to end): 160277You entered: 160277Enter number (0 to end): 0You entered: 0

The do-while loop is usually used when the condition that has to determine the end of the loop is determined withinthe loop statement itself, like in the previous case, where the user input within the block is what is used todetermine if the loop has to end. In fact if you never enter the value 0 in the previous example you can beprompted for more numbers forever.

7. Write a program that displays back-counting from 10 to 1 using do-while loop.

#include<iostream.h>

#include<conio.h>

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 37: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 37

Int main()

{

Int c;

N=1;

While(n<=10)

{

Cout<<n;

N++;

}

Getch();

Return();

}

The for loop

Its format is:

for (initialization; condition; increase) statement;

and its main function is to repeat statement while condition remains true, like the while loop. But in addition, thefor loop provides specific locations to contain an initialization statement and an increase statement. So thisloop is specially designed to perform a repetitive action with a counter which is initialized and increased on eachiteration.

It works in the following way:

1. initialization is executed. Generally it is an initial value setting for a counter variable. This is executedonly once.

2. condition is checked. If it is true the loop continues, otherwise the loop ends and statement is skipped(not executed).

3. statement is executed. As usual, it can be either a single statement or a block enclosed in braces { }.4. finally, whatever is specified in the increase field is executed and the loop gets back to step 2.

// countdown using a for loop#include <iostream># include<conio.h>int main (){for (int n=10; n>0; n--) {cout << n << ", ";}cout << "FIRE!/n";return 0;}

10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!

Prepared by: Miss Humera Gull Department of Information System, KKU

Page 38: C++ practical

C o m p u t e r P r o g r a m m i n g - I P a g e | 38

The initialization and increase fields are optional. They can remain empty, but in all cases the semicolon signsbetween them must be written. For example we could write: for (;n<10;) if we wanted to specify no initializationand no increase; or for (;n<10;n++) if we wanted to include an increase field but no initialization (maybe becausethe variable was already initialized before).Optionally, using the comma operator (,) we can specify more than one expression in any of the fields included ina for loop, like in initialization, for example. The comma operator (,) is an expression separator, it serves toseparate more than one expression where only one is generally expected. For example, suppose that we wanted toinitialize more than one variable in our loop:

for ( n=0, i=100 ; n!=i ; n++, i-- ){// whatever here...}

n starts with a value of 0, and i with 100, the condition is n!=i (that n is not equal to i). Because n is increased byone and i decreased by one, the loop's condition will become false after the 50th loop, when both n and i will beequal to 50.

Prepared by: Miss Humera Gull Department of Information System, KKU