Wednesday, June 11, 2014

Declare Constant and Use Constant in C++

Syntax:
#define <constant_name> <value> 

or 
const <data_type> <constant_name> = <value>

Declare:
#define MAX 100 
#define PI 3.14 
#define Newline '\n'

const int MAX = 100;
const float PI = 3.14;
const char answer = ‘Y’;

Escape Sequences
Escape Sequences      Represents
\a                                     Bell (alert)
\b                                     Backspace
\f                                      Formfeed
\n                                     New line
\r                                      Carriage return
\t                                      Horizontal tab
\v                                     Vertical tab
\'                                      Single quotation mark
\"                                     Double quotation mark
\\                                      Backslash
\?                                     Literal question mark

Example 1: Calculate Area, Circumference of Circle using const keyword 

#include <iostream>
#include <conio.h>
using namespace std;
const double Pi=3.14;
double Radius, Area, Circumference;
int main(){
cout<<"Input Radius of Circle: "; cin>>Radius;
Area = Pi * Radius * Radius;
Circumference = 2 * Pi * Radius;
cout<<"Area of Circle = "<<Area<<endl;
cout<<"Circumference of Circle = "<<Circumference;
getch();
return 0;
}

Example 2: Calculate Circle using #define keyword 
#include <iostream>
#include <conio.h>
using namespace std;
#define PI 3.14159
#define NEWLINE '\n'
int main(){
double radius=7.0;       
  double circle;   
  circle = 2 * PI * radius;
  cout <<"CIRCLE: " <<circle;
  cout << NEWLINE;
getch();
return 0;
}

No comments:

Post a Comment