CodezClub

By | 28.12.2016

Write a C++ program to Swap two numbers using class

#include<iostream>

using namespace std;

class swap
{
int a,b;
public:
void getdata();
void swapv();
void display();
};

void swap::getdata()
{
cout<<“Enter two numbers:”;
cin>>a>>b;
}

void swap::swapv()
{
a=a+b;
b=a-b;
a=a-b;
}

void swap::display()
{
cout<<“a=”<<a<<“tb=”<<b;
}

int main()
{

swap s;

s.getdata();
cout<<“\nBefore swap: \n”;
s.display();

s.swapv();
cout<<“nnAfter swap:n”;
s.display();

return 0;
}

 

OUTPUT ::

 

swap two numbers using class

swap two numbers using class

4.8 9 votes
Article Rating
Category: Uncategorized

About Tunde A

My name is Tunde Ajetomobi, a Tech Enthusiast and Growth Hacker. I enjoy creating helpful content that solves problem across different topics. Codezclub is my way of helping young aspiring programmers and students to hone their skills and find solutions on fundamental programming languages.

Subscribe
Notify of
guest

4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Kanu

Thank you it’s very much helpful

pranav

change the name of a class to run the program.
other wise error is coming

M Arslan Munir

#include<iostream>
using namespace std;

class MySwap
{
  int a, b;
public:
  void getdata();
  void swapv();
  void display();
};

void MySwap::getdata()
{
  cout<<“Enter two numbers: “;
  cin>>a>>b;
}

void MySwap::swapv()
{
  a = a + b;
  b = a – b;
  a = a – b;
}

void MySwap::display()
{
  cout<<“a = “<<a<<“\tb = “<<b<<endl;
}

int main()
{
  MySwap s;
  s.getdata();
   
  cout<<“Before swap:\n”;
  s.display();
   
  s.swapv();
  cout<<“\nAfter swap:\n”;
  s.display();
   
  return 0;
}

Shamini

I am also getting error.so I changed the class name.Then i got output.But why we have to change the class name.if i use same classname and avoiding “using namespace std” i am getting output.but i have to use std infront of cin and cout.

Last edited 9 months ago by Shamini