وثيق

وثيق
شبكة الكترونية
‏إظهار الرسائل ذات التسميات برمجة. إظهار كافة الرسائل
‏إظهار الرسائل ذات التسميات برمجة. إظهار كافة الرسائل

الجمعة، 27 مارس 2015

c++ تطبيق عملي

PROGRAM 1: To demonstrate cout and comments
#include<iostream>                    //PREPROCESSOR
using namespace std; // to avoid use of std::
int main( )                                // FUNCTION WITH RETURN TYPE VOID
{                               //  is comment
cout<<"WELCOME TO KING KHALID UNIVERSITY"<<endl;  
// cout IS AN OBJECT IN C++, endl  IS END OF LINE,
cout<<"ABHA"<<endl;                       //; IS CALLED TERMINATOR.
return 0;
}

PROGRAM 2: To demonstrate cin,  cout  (int, float,char)
#include<iostream>
using namespace std;
int main( )
{
     int a;
     float b;
     char c;
     cout<<"ENTER AN INTEGER"<<endl;
     cin>>a;
     cout<<"ENTER A FLOAT"<<endl;
     cin>>b;
     cout<<"ENTER A CHARECTER"<<endl;
     cin>>c;
     cout<<"INTEGER= "<<a<<"\tFLOAT= "<<b<<"\tCHARECTER= "<<c<<endl;
return 0;
}

PROGRAM 3:          To find Sum and Average of two numbers.
#include<iostream>
using namespace std;
int main( )
{
     float a,b;
     float sum,avg;
     cout<<"ENTER TWO NUMBERS"<<endl;
     cin>>a>>b;
     sum = a + b;
     avg = sum/2;
     cout<<"SUM = "<<sum<<"\n AVARAGE = "<<avg<<endl;
     return 0;
}

PROGRAM 4:          Program to find Sum and Average of three numbers.
#include<iostream>
using namespace std;
int main( )
{
     float  a,b,c;
     float sum,avg;
     cout<<"ENTER THREE NUMBERS"<<endl;
     cin>>a>>b>>C;
     sum = a + b + c;
     avg = sum/3;
     cout<<"SUM = "<<sum<<"\n AVARAGE = "<<avg<<endl;
     return 0;
}

PROGRAM 5:          Program to find area of a circle.
#include<iostream>
using namespace std;
int main( )
{
     float  r,area;
     const float pi=3.147;
     cout<<"ENTER RADIUS OF CIRCLE"<<endl;
     cin>>r;
     area = pi*r*r;
     cout<<"AREA OF CIRCLE = "<<area<<endl;
     return 0;
}

PROGRAM 6:          Program to find area of a rectangle.
#include<iostream>
using namespace std;
int main( )
{
     int len, wid, area;
     cout<<"ENTER LENGTH OF RECTANGLE"<<endl;
     cin>>len;
     cout<<"ENTER WIDTH OF RECTANGLE"<<endl;
     cin>>wid;
     area = len*wid;
     cout<<"AREA OF RECTANGLE = "<<area<<endl;
     return 0;
}


PROGRAM 7:          Program to find area of a square.
#include<iostream>
using namespace std;
int main( )
{
     int side, area;
     cout<<"ENTER SIDE OF SQUARE"<<endl;
     cin>>len;
     area = side*side;
     cout<<"AREA OF SQUARE = "<<area<<endl;
     return 0;
}

Program 8: To display the Pay slip of an employee
#include<iostream>
using namespace std;
int main ()
{
     double GSal,NSal,ded,basic,da;
     const double Housing=1000.00, TA=500.00;
     cout<<"Enter Basic Salary\n";
     cin>>basic;
     cout<<"Enter Deduction Amount\n";
     cin>>ded;
     da=basic*0.2;
     GSal=basic+da+Housing+TA;
     NSal=GSal-ded;
     cout<<"\t\t\t\tBasic       :\t"<<basic<<endl;
     cout<<"\t\t\t\tDA          :\t"<<da<<endl;
     cout<<"\t\t\t\tHousing          :\t"<<Housing<<endl;
     cout<<"\t\t\t\tTravelling  :\t"<<TA<<endl;
     cout<<"\t\t\t\tGross salary     :\t"<<GSal<<endl;
     cout<<"\t\t\t\tDeduction   :\t"<<ded<<endl;
     cout<<"\t\t\t\tNet Salary  :\t"<<NSal<<endl<<endl<<endl;
     return 0;
}






Program 9:   To find the greater and smaller numbers.
#include<iostream>
using namespace std;
int main()
{
     int a,b;
     cout<<"Enter two numbers\n";
     cin>>a>>b;
     if(a>b)
           cout<<a<<" is greater "<<b<<" is smaller";
     else
           cout<<b<<" is greater "<<a<<" is smaller";
     return 0;
}

Program 10:            To find  if a given number is Odd or Even
#include<iostream>
using namespace std;
int main()
{
     int num;
     cout<<"Enter a number\n";
     cin>>num;
     if(num%2==0)
           cout<<num<<" is an Even Number\n";
     else
           cout<<num<<" is an Odd Number\n";
     return 0;
}

Program  11:  To find the Grade of a student
 #include<iostream>
using namespace std;
int main()
{
     int mark;
     char grade;
     cout<<"Enter mark"; 
     cin >> mark;
     if(mark >= 90 && mark <= 100 )
           grade='A';
          if(mark >= 80 && mark <= 89 )
grade='B';
     if(mark >= 70 && mark <= 79 )
           grade='C';
     if(mark >= 60 && mark <= 69 )
           grade='D';
     if(mark < 60 )
           grade='F';
     cout<<"Mark"<<"\t"<<"Grade"<<endl;
     cout<<mark<<"\t"<<grade<<endl;
     return 0;

}


Program 12:            To check the day of week by using SWITCH-CASE
#include<iostream>
using namespace std;
int main()
{
int x;
cout<<"Enter number"<<endl;
cin>>x;
switch(x)
{
case 1:
     cout<<"Saturday"<<endl;
     break;
case 2:
     cout<<"Sunday"<<endl;
     break;
case 3:
     cout<<"Monday"<<endl;
     break;
case 4:
     cout<<"Tuesday"<<endl;
     break;
case 5:
     cout<<"Wednesday"<<endl;
     break;
case 6:
     cout<<"Thursday"<<endl;
           break;
case 7:
     cout<<"Friday"<<endl;
           break;
default:
     cout<<"Error"<<endl;
}
return 0;
}






Program 13: To print natural numbers from 1 to 30 using for loop
#include <iostream>
using namespace std;
int main()
{
     int i;
     for (i=1;i<=30;i++)
     {
cout<<i<<endl;
     }   
return 0;
}

Program 14:            Print natural numbers from 1 to 30 using while loop
#include<iostream>
using namespace std;
int main()
{
     int  a=1;
     while(a<=30)
           {
            cout<<a<<endl;
            a++;
            }
return 0;
    
}

Program 15:            To print natural numbers from 1 to 30 using do while loop
#include<iostream>
using namespace std;
int main()
{
     int  a=1;
     do
        {
         cout<<a<<endl;
         a++;
         }
     while(a<=30);
return 0;
}




Program 16: To find the Factorial of Number using do while loop
#include<iostream>
using namespace std;
int main()
{
     int n, i=1,fact=1;
     cout<<" enter the number ";
     cin>>n;
     if(n>=0)
     {
           do
           {
                fact=fact*i;
                i++;
           }
           while(i<=n);
           cout<<"fact="<<fact<<"\n";
     }
return 0;
}

Program 17: To demonstrate a one dimensional integer array
#include <iostream>
using namespace std;
int main()
{
     int sample[10];
     int t;
     for(t = 0; t < 10; t++)
           sample[t] = t;
     for(t = 0; t < 10; ++t)
           cout << sample[t] << ' ' ;
    
     return 0;
}













Program 18: To demonstrate a one dimensional character array
#include <iostream>
#include <stdlib.h> //for newer compilers, include <cstdlib>
using namespace std;
int main()
{
     char name[32];
     cout << "What's your name?" << endl;
     gets(name); // read a string from the key board.
     cout << "Hello! " << name << "!"  << endl;
     return 0;
}
Program 19: To demonstrate a two dimensional integer array
#include <iostream>
using namespace std;
int main()
{
  int sqrs[10][2] = {
            {1, 1},
      {2, 4},
      {3, 9},
      {4, 16},
      {5, 25},
      {6, 36},
      {7, 49},
      {8, 64},
      {9, 81},
      {10, 100}
  };
  int i, j;
  cout << "Enter a number between 1 and 10: ";
  cin >> i;
  // look up i
  for(j = 0; j < 10; j++)
    if(sqrs[j][0] == i) break; // break from loop if i is found
  cout << "The square of " << i << " is " ;
  cout << sqrs[j][1] << endl;
  return 0;

}

الخميس، 26 مارس 2015

حصريا || تعلم لغة C++

Algorithms and flow charts

Algorithms:
Sequence of precise instructions which leads to a solution is called an algorithm.

Flow chart:
Flow chart is the symbolic representation of algorithm.

Symbols used in flow chart

Sl.No Name Symbol Usage
1 Ellipse Start/Stop
2 Rectangle Expressions
3 Parallelogram   Input (Read)  /  Output(Print)
4 Rhombus Conditional checking
5 Arrow Flow of solution
6 Circle Connector
7 Elongated Hexagon   Continue
8 Rectangle with bars
  Procedure / Function call


Write an algorithm and draw the flow chart to add two numbers


Algorithm:

1. Start
2. Read a, b
3. Calculate c=a + b
4. Print c
5. Stop
Flow chart:



 
Write an algorithm and draw the flow chart to find the area of circle

Algorithm:

1. Start
2. Read  r
3. Calculate A=3.14 * r * r
4. Print A
5. Stop
Flow chart:













Write an algorithm and draw the flow chart to find the circumference of circle

Algorithm:

1. Start
2. Read  r
3. Calculate c= 2*3.14 * r
4. Print c
5. Stop
Flow chart:




Write an algorithm and draw the flow chart to find the factorial of a number

Algorithm:   Flow chart:


1. Start
2. Read  n
3. Assign f=1 and i=1
4. if n<=0 or i>n then go to step 9
5. else go to step 6
6. Calculate f = f * i
7. Calculate i = i +1
8. go to step 4
9. Print f
10. Stop
















Write an algorithm and draw the flow chart to find roots of binomial equation

Algorithm:   Flow chart:

1. Start
2. Read  a,b,c
3. if a=0 then go to 8
4. else go to step 5
5. Calculate r1=(-b+sqrt(b*b–4*a*c))/(2*a)
6. Calculate r2=(-b-sqrt(b*b-4*a*c))/(2*a)
7. Print  r1,r2
8. Stop



























Program Design
A creative process of designing program. Program design process can be divided into two phases.
1. Problem solving phase- it means to write algorithm in English to solve problems.
2. Implementation phase- producing final program from algorithm  Layout of program design
  Problem solving phase Implementation phase



Origin of C++ /History

1. The first language is BCPL (Beginners Computer Programming Language)
2. B language developed from BCPL by Ken Thompson (The Originator of UNIX).
3. In 1970 Dennis Ritchie developed C language from B language at AT&T Bell Laboratories
4. C language is a high level language but it has many of the features of low level language so it can be used for writing system programs.
5. In 1980 Bjarne Stroustrup developed C++ language from C language at AT& T Bell Laboratories
6. C++ is an Object Oriented Programming Language (OOP).

Layout of C++ program

Include directive tells the compiler where to find information about
#include<iostream.h> certain items that are used in your program int main( ) Shows main function
{ Beginning
Statement_2; Declaration of variables and executable C++
…… statements
Statement_Last;
return 0; Return value for the function
Testing and debugging
A mistake in a program is usually called a bug. The process of eliminating bugs is called debugging. Testing takes place in both phases of program design.

Compiling and Running C++
Language Translators
The translator generally converts source code into object code. Source code source code is any collection of statements or declarations written in some humanreadable computer programming language.
Object code
The object code contains a sequence of instructions that the processor can understand.

Types of Translators
1. Assembler
2. Compiler
3. Interpreter
Assembler
Translator which translates assembly language source code into object code.

Compiler
Translator which translates high level language source code into object code as a whole and entire object code will be saved for future purpose. Interpreter
Translator which translates high level language source code into object code line by line.

Compilation and execution of C++
1. Compilation pass1 (Phase 1) – Lexical/Syntax/Semantic Analysis of source code                       ->Intermediate code will be generated.
2. Compilation Pass2 (Phase 2/Code generation Phase) ->Intermediate code to Object code.
3. Execution – Linker will attach object code of routines -> Executable code will be generated.
 - Loader will load the executable code from hard disk into main memory for        execution.













C++ Basics

C++ Character Set
Character set includes the basic building blocks of a language. C++ character set consists of:
a) Numeric Character Set: which includes numbers form 0 to 9.
b) Alphabetic Character Set: which includes the upper-case and lower-case alphabets of English language that are A to Z and a to z.
c) Special Character Set: Some examples are # , ; , :
d) Escape Character Set: are used for formatting the output. It always starts with a back slash ( \ ). Some Examples are \n, \t, \b, \a

Tokens
The smallest individual unit in a program is known as token. C++ has the following tokens:
a) Keywords
b) Identifiers
c) Literals
d) Punctuators
e) Operators
Keywords
Reserved words or Key Words are those words which are reserved for a specific purpose.
Some Examples are: for, do, while
Identifiers (user defined words)
Words that are not reserved are called user defined words or identifiers. User defined words must follow the rules like:
a) Can be composed of alphabets (A-Z or a-z), numbers (0 to 9) and underscore  “_”
b) The first character must be an alphabet or an underscore “_”.
c) Identifier must be unique.
d) Blank Spaces are not allowed.

Examples: RNO, r_no, Z, A1234_BC


Variables
A value which may vary during program execution is called a variable. Each Variable has a unique name and a value.
There are different types of variables and are:-
a) Character variable   (To store characters)
b) Integer variable (To store whole numbers)
c) Float variable (To store floating point numbers)
d) Boolean variable (To store two values true/false)
Variable declaration
Type of variable  variable_name1, variable_name2,…. ;
Example : - int a,b;
Variable initialization
Type of variable  variable_name=value;
Example : - int a=10;
Literals (Constant)
Literals or constants are data items that never change their value during a program run.
Two types are:
i) Numeric Constant ii) Non Numeric constant   Examples: -   const float  pi=3.14;                     const char pi=’∏’;
Punctuators
The following characters are used as punctuators (also known as separators) in C++.
[    ]    (    )    {     }  ,   ;   :   *   …   =   #
Operators
Operators cause the compilers to take some action. Operators work on operands (data). Operators are classified as:-


(i) I/O operators
The input operator(>>) is used to read value from standard input and output operator(<<) is used to direct a value to standard output.
(ii) Assignment Operator: Equal sign (=) is used for assignment operator. It is used to assign values to variables. For Example:
RNO = 103;  
(iii) Arithmetic Operators: are used to perform arithmetic operations. For Example:

Plus ‘+’ used for addition purpose
Minus ‘-‘ used for subtraction purpose
Division ‘/’ used for division purpose
Multiplication ‘*’ used for multiplication purpose
Modulus ‘%’ used to find the remainder

(iv) Unary operators /Increment (++) and Decrement (--) Operators: are used to increment or decrement a variable value by one. For example
Examples : a++ , a-- , ++a
(v) Relational Operators: are used for the comparison of variables. These include:

Name Symbol
less than   <
Greater than   >
less than or equal to   <=
Greater than or equal to   =>
equal to   ==
not equal to !=

(vi) Logical operators: are used to for logical combination, disjunction or negation of variables. These include:
  Logical AND (&&): used for logical combination.
  Logical OR (||): used for logical disjunction.
  Logical NOT (!): used for logical negation.
(vii) Conditional operator
   Conditional operator (? :) that stores a value depending upon a condition
(viii) sizeof  operator   sizeof operator returns the length (in bytes) of the variable
(ix) Comma operator
  A comma operator is used to string together several expressions.     Example:  b= (a=3, a+1)               b has the value 4
(x) Compound operators
C++ allows the assignment to combine with other operators.
Examples: Z+=5; which is equal to Z=Z+5;
(xi) Bitwise operators
& (And) , | (Or), ! (Not)

The Priority of Operations
If an expression has two or more operators then there is a certain order in which the operations are performed by the computer. It is referred as order of precedence.
All parentheses are evaluated first and  parenthesis are used to change the priority order
++ (post increment), -- (post decrement)
++ (pre increment), -- (pre decrement) , sizeof , ! (not),- (unary minus), + (unary plus)
* (multiply) , / (divide), % (modulus)
+ (add), -(subtract)
< (less than) , <= (less than or equal), > (greater than) , >= (greater than or equal)
= = (equal), ! = (not equal)
&& (logical AND)
|| (logical OR)
? : (conditional operator)
= (assignment operator)
, (comma operator)
  Highest

Examples:    i) 4+3*3-6=7          ii) 5+5%3=7           iii) (8*5%3)*5+10=15

Data types
Data types are means to identify the type of data and associated operations of handling it.
C++ data types are of two types.
(i) Fundamental  data types
(ii) Derived data types

(i) Fundamental  data types
Fundamental data types are those that are not composed of other data types.

Name Data Type Size Range
Char Character 1 Byte -128 to 127
unsigned char Unsigned Character 1 Byte 0 to 255
int Integer 2 Bytes -32768 to 32767
short int Short Integer 2 Bytes -32768 to 32767
signed int Signed Integer 2 Bytes -32768 to 32767
unsigned int Unsigned Integer 2 Bytes 0 to 65535
long int Long Integer 4 Bytes -2147483648 to
2147483647
float Floating Point 4 Bytes -3.4E+38 to 3.4E+38
double Double Floating Point 8 Bytes -1.7E+308 to 1.7E+308
long double Long Double Floating
Point 10 Bytes -1.7E+308 to 1.7E+308

(ii) Derived data types
From the fundamental types other types can be derived by using the declaration operators. Examples: arrays, function, pointer

Expression
Expressions are the valid combination of operators, constants and or variables.
Example: X = X + 5;
 


Conversion of Mathematical Expressions into C++ Expressions
Mathematical Expressions C++ Expressions

A÷B+C
  A / B + C    

A÷(B+C)

  A / ( B + C )

A÷B+C÷D

  A / B + C / D    

A2  +B2

C2
  ( A * A + B * B ) / ( C * C )

2
a × x + b× x +c
  a * x * x  +  b * x  + c

2
√ B – 4 × A ×C
  sqrt ( B * B – 4 * A * C )

2 A

  sqrt ( ( B1 + B2 ) / ( 2 * A ) )

Comments
Comments are used to clarify or explain the purpose of the C++ program.  Comments are ignored by the compiler during execution. There are two styles for  using comments:
1. Old Style:   /* Explanation here */
2. New Style:    // Explanation here.



Statements
A statement is an instruction or group of instructions that carry out certain action. It is used to evaluate an expression or to control the sequence of execution. Statements can be divided into two types:
1- Simple Statement
2- Structure Statement
1. Simple Statement: Consists of an expression to be evaluated, followed by a semicolon.  
Example:
x = 5;
 cout<<”Hello World”;  (for display)  cin>>a;  (for reading)
2. Structure Statement can be further divided into three types:
a. Compound Statements: Are written in a pair of braces. For Example:
{
pi = 3.14159;
  circumference =  2.0 * pi * radius;   area = pi * radius * radius;
}
b. Selection Statements: Are used to choose among alternative courses of actions.
For Example:   if , if else , nested if , switch
c. Iteration Statements: Are used to perform an action repeatedly while some  
condition remains true.
 For Example:
for , while , do while
 
Conditional construct
C++ allows execution of a statement or a set of statements based on a given condition. There are four types of conditional constructs.
1. Simple if
2. If else
3. If else if ladder
4. Nested if

Syntax

Construct
  Syntax
  Example

Simple if if (Condition)
Statement;
  if (a> b)
cout<<”a is larger”;

if (Condition)
         {
Statement 1;
Statement 2;
          } if (a> b)
{ cout<<”a is larger”; cout<<”b is smaller”;
}
If else
  if (Condition) Statement 1; else
Statement 2;
            if (a> b)
cout<<”a is larger”; else
cout<<”b is larger”;
if (Condition)
         {
Statement 1;
Statement 2;
          } else
         {
Statement 3;
Statement 4;
          }
  if (a> b)
{ cout<<”a is larger”; cout<<”b is smaller”;
} else { cout<<”b is larger”; cout<<”a is smaller”;
}
if else if ladder if (condition1) Statement 1; else if (condition 2 Statement 2; else
Statement 3;
    if (a>0) cout<<”Positive Number”; else if (a= =0) cout<<”Zero”; else cout<<”Negative Number”;
Nested if   if (condition1)
{
if (condition 2)  Statement 1; else
Statement 2;
}
else if (condition 3 Statement 3; else
Statement 4; Outer if/ enclosed if
Inner if/ nested if
  if (a>b) { if (a>c) cout<<”a is the largest”; else cout<<” c is the largest”;
} else if (b>c) cout<<” b is the largest”; else cout<<” c is the largest”;


Write a program to check whether the given number is odd or even.

#include<iostream.h>
void main( )
{ int a,b;
cout<<”Enter two numbers”; if (a%2= =0) cout<<”Even number”;
else
cout<<”Odd number”;
}

Write a program to read the mark of your course and display the grade.
#include<iostream.h> void main( )
{ int mark; cout<<”Enter mark”; cin>>mark; if (mark>=95) cout<<”A+”; else if(mark>=90) cout<<”A”; else if(mark>=85) cout<<”B+”; else if(mark>=80) cout<<”B”; else if (mark>=75) cout<<”C+”; else if (mark>=70) cout<<”C”; else if(mark>=65) cout<<”D+”; else if(mark>=60) cout<<”D”; else cout<<”F”;
}

Menu driven programs

switch case statement
C++ has a built in multiple branch selection statement called switch. This statement successively tests the value of an expression against a list of constants. When a match is found, the statement associated with that condition is executed.
Syntax switch(index)
{ case index1: statement1;
  break;
case index2: statement2;
  break;
.
:
:
:
case index n: statement n;
  break;
default:          statement def;
}

Write a program using switch statement to display name of 7 days.

#include<iostream.h> void main()
{ int x;
cout<<"Enter number"<<endl; cin>>x; switch(x) { case 1:
  cout<<"Saturday"<<endl;   break; case 2:
  cout<<"Sunday"<<endl;   break;
case 3:
  cout<<"Monday"<<endl;   break; case 4:
  cout<<"Tuesday"<<endl;   break; case 5: cout<<"Wednesday"<<endl; break;
case 6: cout<<"Thursday"<<endl; break;
case 7: cout<<"Friday"<<endl; break;
default:
  cout<<”Error”;
}
}

Write a program to do all arithmetic operations using switch case.

#include<iostream.h> void main( ) { int a,b; char optr; float c;
cout<<”Enter two numbers”; cin>>a>>b; cout<<”Enter operator”; cin>>optr;

switch(optr) { case ‘+’:  c=a+b;
  break;
case ‘-‘: c=a-b;
  break;
case ‘*’ c=a*b;
  break;
case ‘/’: c=a/b;
  break;
case ‘%’: c=a%b;
  break;
default: c=0;
  cout<<”Error”;
} cout<<”The result”<<c;
}
 
Write a program to read the colors of rain bow and display it.
 
#include<iostream.h> void main( ) {
int clr;
cout<<”VIBGYOR”;
cout<<”\n see the above mnemonic and enter the no”; cin>>clr; switch(clr) { case 1:
  cout<<"Violet"<<endl;   break; case 2:
  cout<<"Indigo"<<endl;   break;
case 3:
  cout<<"Blue"<<endl;   break; case 4:
  cout<<"Green"<<endl;   break; case 5:
cout<<"Yellow"<<endl; break;
case 6:
cout<<"Orange"<<endl; break;
case 7:
cout<<"Red"<<endl; break;
default:
  cout<<”Error”;
}
}


Iteration statements (Loops)
1. for loop
2. while loop
3. do while loop


The for loop
For loop allows a statement or group of statements to be performed repeatedly in a loop, a given number of times.  Syntax
  for (initializer; condition; expression)
  {
  Body of the loop;
}

The initializer is an assignment statement that is used to initialize the control variable which is used as counter.
The condition evaluates the condition that is it compares the value of control variable with some limit value.
The expression is an assignment statement that is used to alter the value (increment or decrement) of the control variable.
The while loop
The looping statement while is used to execute series of statements in a loop over and over as long as given condition is true.
Syntax

while(condition)
{ body of the loop;
}

The do-while loop
The do-while is a looping statement unlike the while and for loops, which are pre-tested loops the do-while is the post-tested loop i.e. the condition is tested after the execution of the body of the loop. In this loop the body of the loop executed at least once.


Syntax
do
{ body of the loop;
}
while(condition);


The break, continue and exit( ) statements
The break statement immediately ends the looping process. The continue statement performs the opposite function of break statement. It transfers the control at the top of the loop for next iteration. exit( ) statement is declared in the stdlib.h header file, enables you to exit the program.


Print natural numbers from 1 to 30 using for loop

#include <iostream.h> void main()
{
  int i;
  for (i=1;i<=30;i++)
  {
cout<<i<<endl;
  }  
}

Print natural numbers from 1 to 30 using while loop

#include<iostream.h> void main()
{
  int  a=1;   while(a<=30)        {         cout<<a<<endl;         a++;
        }
 
}




Print natural numbers from 1 to 30 using do while loop

#include<iostream.h> void main()
{
  int  a=1;
  do
    {
     cout<<a<<endl;      a++;      }   while(a<=30);
}

Display first 10 Odd numbers using for loop

#include <iostream.h> void main()
{
  int i;
  for (i=1;i<=20;i=i+2)
  cout<<"  i="<<i<<endl;
}  

Display first 10 even numbers using for loop

#include <iostream.h> void main()
{
  int i;
  for (i=2;i<=20;i=i+2)
  cout<<"  i="<<i<<endl;
}      Find the Factorial of Number using do while loop

#include<iostream.h> void main() {  int n, i=1,fact=1;  cout<<" enter the number ";
 cin>>n;  if(n>=0)
 {
  do
  {
  fact=fact*i;
  i++;
  }
  while(i<=n);   cout<<"fact="<<fact<<"\n";
 }
}

Check whether the given number is Armstrong or not

#include<iostream.h> #include<math.h> void main() {   int n, x, a=0,r;  cout<<" enter the number ";
 cin>>n;  x=n;  while(n>0)
  {
r=n%10; a=a+pow(r,3); n=n/10; }
if(x==a) cout<<”Armstrong Number”; else
cout<<”Not Armstrong”;
 }




\
Difference between While and Do_While loop:-


While Loop Do_While Loop
1) In while condition will checked at first .
2) In this loop if condition became false then it didn’t print any statement in loop and controll will come out of loop.
3) It didn’t needs semi column(;) at the end of loop body because after condition loop body start.
  1) InDo- while condition will checked at last.
2) In this loop if condition became false then at least it  print  statement one time  in loop and controll will come out of loop.
3) It  needs semi column(;) at the end of loop body because before condition loop body is finished


OOP CONCEPTS
Paradigm-: It means organizing principle of a program. It is an approach to programming.

Procedural Paradigm

In procedural programming paradigm, the emphasis is on doing things i.e., the procedure or the algorithm. The data takes the back seat in procedural programming paradigm. Also, this paradigm does not model real world well.

Object oriented programming
The object oriented programming paradigm models the real world well and overcomes the shortcomings of procedural paradigm. It views a problem in terms of objects and thus emphasizes on both procedures as well as data.

The following are the basic concepts used in object-oriented programming.

Object-: An object is an identifiable entity with some characteristics and behavior.
                                       OR
 Object: An object is run time entities.

Example: Pen, Pencil, Mango, A/c Number etc.

Class-: A class represents a group of objects that share common properties, behavior and relationships.
  OR
Class: A class is collection of similar type objects.

Example:  fruit, shape
 
Data Abstraction-: Abstraction refers to act of representing essential features without including the background details or explanations.

Encapsulation-: The wrapping up of data and associated functions into a single unit is known as Encapsulation. Encapsulation implements data abstraction.

Modularity-: Modularity is the property of a system that has been decomposed into a set of cohesive and loosely coupled modules.

Inheritance-: It is the capability of one class of things to inherit capabilities or properties from another class.

Base and sub classes-: The class whose properties are inherited is called base class (or superclass) and the class that inherits the properties is known as derived class(or subclass).

Derived Class :- The class, which inherits from other classes is called derived class or Subclass.
Polymorphism-: It is the ability for a message or data to be processed in more than one form. Polymorphism is a property by which the same message can be sent to objects of several different classes. Polymorphism is implemented in C++ through virtual functions and overloading- function overloading and operator overloading.

Advantages of Object oriented programming.
Software complexity can be easily managed
Object-oriented systems can be easily upgraded
It is quite easy to partition the work in a project based on object

class enforce data-hiding, abstraction & encapsulation
A class groups its members into three sections : private, protected, and public. The private and protected members remain hidden from outside world. Thus through private and protected members, a class enforces data-hiding.
The outside world is given only the essential and necessary information through public members, rest of the things remain hidden, which is nothing but abstraction. Abstraction means representation of essential features without including the background details and explanation.

CLASSES & OBJECTS
The mechanism that allows you to combine data and the function in a single unit is called a class. Once a class is defined, you can declare variables of that type. A class variable is called object or instance. In other words, a class would be the data type, and an object would be the variable. Classes are generally declared using the keyword class, with the following format: class class_name
{    private:
      members1;    protected:       members2;    public:
      members3; };
Where class_name is a valid identifier for the class. The body of the declaration can contain members, that can be either data or function declarations, The members of a class are classified into three categories: private, public, and protected. Private, protected, and public are reserved words and are called member access specifiers. These specifiers modify the access rights that the members following them acquire.

Private members of a class are accessible only from within other members of the same class. You cannot access it outside of the class.

Protected members are accessible from members of their same class and also from members of their derived classes.
Public members are accessible from anywhere where the object is visible.
By default, all members of a class declared with the class keyword have private access for all its members. Therefore, any member that is declared before one other class specifier automatically has private access.
Here is a complete example:
class student
{   private :     int rollno;     float marks;    public:     void getdata()
    {
       cout<<"Enter Roll Number : ";
       cin>>rollno;        cout<<"Enter Marks : ";        cin>>marks;
    }
    void displaydata()
    {
       cout<<"Roll number : "<<rollno<<"\nMarks : "<<marks;
    }
};

Object Declaration
Once a class is defined, you can declare objects of that type. The syntax for declaring a object is the same as that for declaring any other variable. The following statements declare two objects of type student: student st1, st2;

Accessing Class Members
Once an object of a class is declared, it can access the public members of the class.st1.getdata ();

Defining Member function of class
You can define Functions inside the class as shown in above example. Member functions defined inside a class this way are created as inline functions by default. It is also possible to declare a function within a class but define it elsewhere. Functions defined outside the class are not normallyinline.
When we define a function outside the class we cannot reference them (directly) outside of the class.
In order to reference these, we use the scope resolution operator, :: (double colon).

 In this example, we are defining function getdata outside the class:void student :: getdata()
{
     cout<<"Enter Roll Number : ";
     cin>>rollno;      cout<<"Enter Marks : ";      cin>>marks; }
The following program demostrates the general feature of classes. Member function initdata() is defined inside the class. Member funcitons getdata() and showdata() defined outside the class. class student //specify a class
{   private :
    int rollno; //class data members
    float marks;    public:     void initdata(int r, int m)
    {        rollno=r;
       marks=m;
    }
    void getdata(); //member function to get data from user     void showdata();// member function to show data
};

void student :: getdata()
{
    cout<<"Enter Roll Number : ";
    cin>>rollno;     cout<<"Enter Marks : ";     cin>>marks;
}

void student :: showdata()
{
    cout<<"Roll number : "<<rollno<<"\nMarks : "<<marks; }

int main() {     student st1, st2; //define two objects of class student     st1.initdata(5,78); //call member function to initialize     st1.showdata();
    st2.getdata(); //call member function to input data     st2.showdata(); //call member function to display data     return 0;
}





CONSTRUCTOR AND DESTRUCTOR
CONSTURCTOR
It is a member function having same name as it’s class and which is used to initialize the objects of that class type with a legel initial value. Constructor is automatically called when object is created.
Types of Constructor
Default Constructor-: A constructor that accepts no parameters is known as default constructor. If no constructor is defined then the compiler supplies a default constructor. student :: student()
{      rollno=0;       marks=0.0;  }
Parameterized Constructor -: A constructor that receives arguments/parameters, is called parameterized constructor.

student :: student(int r)
{
     rollno=r;  }
Copy Constructor-: A constructor that initializes an object using values of another object passed to it as parameter, is called copy constructor. It creates the copy of the passed object.

student :: student(student &t)
{
     rollno = t.rollno;  }
There can be multiple constructors of the same class, provided they have different signatures.
DESTRUCTOR
A destructor is a member function having sane name as that of its class preceded by ~(tilde) sign and which is used to destroy the objects that have been created by a constructor. It gets invoked when an object’s scope is over.

~student() { }
Example : In the following program constructors, destructor and other member functions are defined inside class definitions. Since we are using multiple constructor in class so this example also illustrates the concept of constructor overloading
#include<iostream.h>

class student //specify a class
{   private :
    int rollno; //class data members
    float marks;    public:     student() //default constructor     {        rollno=0;
       marks=0.0;
    }
    student(int r, int m) //parameterized constructor
    {        rollno=r;        marks=m;
    }
    student(student &t) //copy constructor
    {        rollno=t.rollno;
       marks=t.marks;
    }
    void getdata() //member function to get data from user
    {
       cout<<"Enter Roll Number : ";        cin>>rollno;        cout<<"Enter Marks : ";
       cin>>marks;
    }
    void showdata() // member function to show data
    {
       cout<<"\nRoll number: "<<rollno<<"\nMarks: "<<marks;
    }
    ~student() //destructor
    {}
};

int main() {
    student st1; //defalut constructor invoked     student st2(5,78); //parmeterized constructor invoked     student st3(st2); //copy constructor invoked     st1.showdata(); //display data members of object st1     st2.showdata(); //display data members of object st2     st3.showdata(); //display data members of object st3     return 0;
}






INHERITANCE
Inheritance:It is the capability of one class to inherit properties from another class.
Base Class: It is the class whose properties are inherited by another class. It is also called Super Class.
Derived Class:It is the class that inherit properties from base class(es).It is also called Sub Class.

FORMS OF INHERITANCE
(1) Single Inheritance: It is the inheritance hierarchy wherein one derived class inherits from one base class.
(2) Multiple Inheritance:It is the inheritance hierarchy wherein one derived class inherits from multiple base class(es)
(3) Hierarchical Inheritance: It is the inheritance hierarchy wherein multiple subclasses inherits from one base class.
(4) Multilevel Inheritance: It is the inheritance hierarchy wherein subclass acts as a base class for other classes.
(5) Hybrid Inheritance:The inheritance hierarchy that reflects any legal combination of other four types of inheritance.

Visibility Mode: It is the keyword that controls the visibility and availability of inherited base class members in the derived class.It can be either private or protected or public.

Private Inheritance: It is the inheritance facilitated by private visibility mode.In private inheritance ,the protected and public members of base class become private members of the derived class.
Public Inheritance: It is the inheritance facilitated by public visibility mode.In public inheritance ,the protected  members of base class become protected members of the derived class and public members of the base class become public members of derived class.;
Protected Inheritance: It is the inheritance facilitated by protected visibility mode.In protected inheritance ,the protected and public members of base class become protected members of the derived class.
Base Class Visibility Derived class visibility
Public derivation Private derivation Protected derivation
Private Not inherited Not inherited Not inherited
Protected
Protected Private Protected
Public
Public Private Protected
Containership:When a class contains objects of other class types as its members, it is called containership.It is also called containment,composition, aggregation.
Execution of base class constructor
Method of inheritace Order of execution
class B : public A { }; A(); base constructor  B(); derived constructor
class A : public B, public C
B();base (first)
C();base (second)
A();derived constructor
When both derived and base class contains constructors, the base constructor is executed first and then the constructor in the derived class is executed.  In case of multiple inheritances, the base classes are constructed in the order in which they appear in the declaration of the derived class.

Overriding of method(function) in inheritance
We may face a problem in multiple inheritance, when a function with the same name appears in more than one base class. Compiler shows ambiguous error when derived class inherited by these classes uses this function.    
We can solve this problem, by defining a named instance within the derived class, using the class resolution operator with the function as below : class P : public M, public N        //multiple inheritance
{  public :    void display()  //overrides display() of M and N
   {
      M::display()
   } }; we can now used the derived class as follows :
 void main()
{   P obj;   obj.display();
}
Virtual Base Class
Multipath inheritance may lead to duplication of inherited members from a grandparent base class. This may be avoided by making the common base class a virtual base class. When a class is made a virtual base class, C++ takes necessary care to see that only one copy of that class is inherited. class A
{
 ....
 ....
}; class B1 : virtual public A
{
 ....
 ....
}; class B2 : virtual public A {
 ....
 ....
}; class C : public B1, public B2 {
 ....   // only one copy of A
 ....   // will be inherited
};