To find the sum of two numbers using C, C++ & Java we have two ways :-
1. Hardcode values in the code.
2. Take input from user.
1. Hardcode values in the code using C.
#include<stdio.h>
int main()
{
int n1=2,n2=3,sum=0;
sum=n1+n2;
printf("The sum of 2 number is : %d ",s);
return 0;
}
1. Hardcode values in the code using C++.
#include <iostream>
using namespace std;
int main()
{
int n1=2,n2=3,sum=0;
sum = a+b;
cout<<"\nThe sum of two numbers : "<<sum;
return 0;
}
1. Hardcode values in the code using Java.
public class SumOfNumbers1
{
public static void main(String args[])
{
int n1 = 2, n2 = 3, sum;
sum = n1 + n2;
System.out.println("The sum of two numbers is: "+sum);
}
}
2. Take input from user using C
#include<stdio.h>
int main()
{
int n1,n2,sum=0;
printf("Enter 2 Number : ");
scanf("%d%d",&n1,&n2);
sum=n1+n2;
printf("The Sum of two number : %d ",sum);
return 0;
}
2. Take input from user using C++
#include <iostream>
using namespace std;
int main()
{
int n1, n2, sum=0;
cout<<"Enter any two numbers : ";
cin>>n1>>n2;
sum = n1+ n2;
cout<<"\nSum of 1st three numbers : "<<sum;
return 0;
}
2. Take input from user using Java
import java.util.Scanner;
public class SumOfNumbers2
{
public static void main(String args[])
{
int n1, n2, sum=0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the first number: ");
n1 = sc.nextInt();
System.out.print("Enter the second number: ");
n2 = sc.nextInt();
sum = n1+n2;
System.out.println("The sum of two numbers n1 and n2 is: " + sum);
}
}
Comments
Post a Comment