10 Simple C++ Programs
10 Simple C++ Programs
2. #include <iostream>
4. int main() {
5. int a ;
6. int b ;
7. cin>>a>>b;
8. cout<<a+b;
9. return 0;
10. }
11. Input: 2 5
Output: 7
16. int a ;
17. cin>>a;
20. else
21. cout<<”odd”;
22. return 0;
23. }
24. Input: 8
Output: even
33. a = b;
34. b = temp;
36. return 0;
37. }
38. Output: 10 20
20 10
39. Write a C++ program to find the largest number among three numbers.
A number will be largest if number is greater than both the other numbers.
43. float a, b, c;
51. return 0;
52. }
53. Input: 1 2 3
Largest number: 3
54. Write a C++ Program to Find the sum of all the natural numbers from 1 to n.
To find the sum of all the natural number from 1 to n in C++, We have two methods, one is by iterating from 1 to n and adding them up while the other
way is using the summation formula –
59. {
63. sum += i;
64. }
67. return 0;
68. }
69. Input: 5
Output: 15
74. int a ;
75. cin>>a;
76. int b = 2;
79. while(b!=a){
80. if(a%b == 0)
81. {
83. break;
84. }
85. b++;
86. }
87. if(prime)
88. cout<<"prime";
89. else
91. return 0;
92. }
Output: prime
93. Write a C++ program to Compute the power a given number to a given power.
To compute the power of a given number in C++, We initialize a variable result to 1. Then, we’ll use a while loop to multiply the result by base for power
number of times.
94. 3^3=3*3*3=27
104. power--;
105. }
107. return 0;
108. }
109. Input: 3 3
Output: 27
110. Write a C++ program to Calculate the average of all the elements present in an array.
We iterate over each element of the array and calculate the sum of all the elements. Then, we divide the sum by the size of the array to get the
average. The average is stored in a variable of type float and returned.
115. {
116. int n;
117. cin>>n;
118. int arr[n];
121. cin>>arr[i];
124. cout<<(float)(sum/(float)n);
125. return 0;
126. }
127. Input: 3
128. 1 4 5
Output: 3.33333
133. if(b == 0)
134. return a;
136. }
139. cin>>a>>b;
140. cout<<gcd(a,b);
141. return 0;
142. }
143. Input: 35 25
Output: 5
148. {
150. cin>>str;
153. count++;
154. cout<<count;
155. }
Output: 5