Friday, 20 February 2015

Sample C++ program to illustrate - 1) Declaring variables 2) Writing to STDOUT, 3) reading user input from STDIN, 4) Using IF statement 5) Using FOR and WHILE loops

#include <iostream>
#include <string>
using namespace std;

int main()
{
  string name;
  cout << "What is your name ?";
  cin >> name;
  cout << "Hi " << name << "\n";

  int num;
  cout << "Enter a number: ";
  cin >> num;

  cout << "Even numbers below" << num << ": ";
  for(int i = 1; i < num; i++)
  {
    if(i%2 == 0)
    {
      cout << i << " ";
    }
  }
  cout << "\n";

  cout << "Odd numbers below" << num << ": ";
  int j = 1;
  while(j < num)
  {
    if(j%2 != 0)
    {
      cout << j << " ";
    }
    j++;
  }
  cout << "\n";

  return 1;
}

No comments:

Post a Comment