Friday, November 28, 2014

Simple pro in c++



Do While Loop Program in C++

#include
#include
using namespace std;
int main()
{
       int a;
     cout<<"Enter the Number :";
     cin>>a;
     int counter = 1;
     do
     {
         cout<<"Execute Do While "<
         counter++;
     }
     while (counter <= a);
     getch();
     return 0;
 }

Output


Enter the Number :6
Execute Do While 1 time
Execute Do While 2 time
Execute Do While 3 time
Execute Do While 4 time
Execute Do While 5 time
Execute Do While 6 time

A Simple program without using functions


#include
#include
using namespace std;
int main()
{
   int number;
   int abs_number;

   cout << "This program finds the absolute value of an integer." << endl;
   cout << "Enter an integer (positive or negative): ";
   cin >> number;
    if(number >= 0)
   {
               abs_number = number;
   }
   else
               abs_number = -number;
   cout << "The absolute value of " << number << " is " << abs_number;
   cout << endl;
   return 0;
}

The same program using function

 
#include
#include
int abs(int i); 
int main()
{
   int number;
   int abs_number;
   cout << "This program finds the absolute value of an integer." << endl;
   cout << "Enter an integer (positive or negative): ";
   cin >> number;
   abs_number = abs(number);
   cout << "The absolute value of " << number << " is " << abs_number;
   cout << endl;
   return 0;
}
int abs(int i)
{
   if( i >= 0)
               return i;
   else
               return -i;
}

Formatted I/O using ios member functions

 
#include 
#include
using namespace std;
int main()
{
   float num[5] = {1.0, -1.2345, 2350.1, 23.4, 45.34};
   int i;
   cout.setf(ios::showpos); 
   cout.setf(ios::scientific); 
   cout.precision(2); 
   for(i = 0; i < 5; i++)
   {
               cout.width(20);    
               cout.fill('$');    
               cout << num[i] << endl;
   }
  return 0;
}

Formatted I/O using I/O manipulators

 
#include 
#include
#include 
using namespace std;
int main()
{
   float num[5] = {1.0, -1.2345, 2350.1, 23.4, 45.34};
   int i;
   cout << setiosflags(ios::showpos);
   cout << setiosflags(ios::scientific); 
   cout << setprecision(2); 
   for(i = 0; i < 5; i++)
   {
               cout << setw(20);    
               cout << setfill('$');    
               cout << num[i] << endl;
   }
 
  return 0;
}

Define your own I/O manipulators

 
#include 
#include
#include 
using namespace std;
ostream &sethex(ostream &stream);
int main()
{
   int input;
   cout << "Enter an integer: " ;
   cin  >> input;
   cout << "Hexdecimal is: ";
   cout << sethex << input << endl;
   return 0;
}
ostream &sethex(ostream &stream)
{
   stream.setf(ios::hex,ios::basefield); 
   return stream;
}

No comments:

Post a Comment