Printing addition using String in C++


This is a simple C++ program that demonstrates the difference between adding two integers and concatenating two strings.

  • The program starts by declaring three integer variables: x, y, and z. The values of x and y are initialized to 10 and 20, respectively. The value of z is then calculated by adding x and y.
  • Next, three string variables are declared: a, b, and c. The values of a and b are initialized to the strings "10" and "20", respectively. The value of c is then calculated by concatenating a and b.
  • Finally, the values of z and c are printed to the console using the cout statement.

One thing to note is that the + operator behaves differently depending on the types of the variables being added. When used with integers, it performs addition. When used with strings, it performs concatenation.

Source Code

#include<iostream>
#include<string.h>
using namespace std;
int main()
{
    int x = 10;
    int y = 20;
    int z = x+y;
    string a = "10";
    string b = "20";
    string c = a+b;
    cout<<"\nAddition of numbers :"<<z;
    cout<<"\nAddition of Strings :"<<c;
    return 0;
}
To download raw file Click Here

Output

Addition of numbers :30
Addition of Strings :1020

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples