C++ Input Output Statements (cout/cin) Practice 5

Let’s Do Some More Tasks in C++ To Practice input output statements (cin/cout) in C++.

You May also want to Check Part 1 , Part 2 , Part 3 and Part 4 of Input Output Statment Series Practice

Task 9:

Write a Program that takes a 4 digit number as input from the user.. And displays the digits separated.. E.g. if user enter 2341
Output should be
2,3,4,1
Also Find Sum of Digits
E.g sum=2+3+4+1=10

Code:

#include<iostream>
using namespace std;
int main()
{
	int num;
	cout<<"Enter 4 Digit Number : ";
	cin>>num;
	int d1,d2,d3,d4;
	d1=num/1000;
	num=num%1000;
	d2=num/100;
	num=num%100;
	d3=num/10;
	num=num%10;
	d4=num;
	cout<<"\n\n"<<d1<<" , "<<d2<<" , "<<d3<<" , "<<d4<<"\n\n";
	return 0;
}

Output:

Enter 4 Digit Number : 1346


1 , 3 , 4 , 6

Task 10:

Write a Program that takes two numbers as input from user and Swap their values using the third variable as well as without using the third variable
E.g. a=5 , b=10
After swapping a=10, b=5;

Code:

#include<iostream>
using namespace std;
int main()
{
	int a,b;
	cout<<"Enter Two Numbers : \n";
	cin>>a>>b;
	//swapping them using third variable temp;
//	int temp=a;
//	a=b;
//	b=temp;
//	cout<<"a = "<<a<<endl;
//	cout<<"b = "<<b<<endl;
	//without using third variable
	a=a+b;
	b=a-b;
	a=a-b;
	cout<<"a = "<<a<<endl;
	cout<<"b = "<<b<<endl;
	return 0;
}

Output:

Enter Two Numbers :
5
7
a = 7
b = 5

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *