Learn c# Quickly and c++ Coding Practice Exercises_ Coding -- Tam, Jj -- 2021 -- A2760371e7f02ced6e6269d246f686e0 -- Anna’s Archive
Learn c# Quickly and c++ Coding Practice Exercises_ Coding -- Tam, Jj -- 2021 -- A2760371e7f02ced6e6269d246f686e0 -- Anna’s Archive
AND
C++
CODING PRACTICE
EXERCISES
C# Vs .net
C# is a programming language, and ‘.NET’ is a framework. ‘.NET’ has
various languages under it. C# is one of the language in ‘.NET’.
Press OK.
using System ;
namespace HelloWorld
{
class Program
{
static void Main ( string [] args)
{
Console.WriteLine("Hello World");
Console.WriteLine("Welcome To C# Programming.........");
}
}
}
Press ‘CTRL + F5’, it opens command prompt and show the strings that we
passed to 'Console.WriteLine' method.
‘using System’
Above statement loads a names space ‘System’. Name spaces are used to
organize the code. A name space is a collection of classes, interfaces,
enums, structs & delegates.
namespace HelloWorld
Above statement gives the name space ‘HelloWorld’ to this program. It is
optional. You can even run the program without this statement.
using System ;
class Program
{
static void Main ( string [] args)
{
Console.WriteLine("Hello World");
Console.WriteLine("Welcome To C# Programming.........");
}
}
class Program
Class is used to encapsulate methods and properties as single entity. Ignore
this for time being, I will explain about this in later posts.
Console.WriteLine("Hello World");
Above statement writes the message "Hello World" to console. Console is
the class resides in name space System. WriteLine is the method of class
Console.
C#: Read input from console
‘Console’ class provides ‘ReadLine’ method to read input from console.
ReadLine method reads the information from console and return the input
in string format.
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
Console.WriteLine("Welcome to C#, Please Enter Basic Informaiton");
Console.WriteLine("Hello " + name + " You are " + age + " years
old");
}
}
Output
Welcome to C#, Please Enter Basic Informaiton
Enter Your Name
JJ TAM
Enter Your Age
26
Hello JJ TAM You are 26 years old
While concatenating the strings, place holder syntax is very convenient than
using ‘+’ operator.
Console.WriteLine("Hello " + name + " You are " + age + " years old");
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
Console.WriteLine("Welcome to C#, Please Enter Basic Informaiton");
}
}
Output
Welcome to C#, Please Enter Basic Informaiton
Enter Your Name
JJ TAM
Enter Your Age
26
Hello JJ TAM
You are 26 years old
Hello 26. You are JJ TAM years old
Press any key to continue . . .
C#: Built in Types
C# support almost all kind of data types to work with. All data types are
represented as classes in System namespace. Data types can be categorized
into following types.
a. Boolean : bool
b. Integer: byte, sbyte, int, uint, short, ushort, long, ulong
c. Float: double, float, decimal
d. Character : char
e. String
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
byte byteVar = 10 ;
sbyte sbyteVar = 11 ;
int intVar = 12 ;
uint uintVar = 13 ;
short shortVar = 14 ;
ushort ushortVar = 15 ;
long longVar = 16 ;
ulong ulongVar = 17 ;
float floatVar = 18.18f ;
double doubleVar = 19.19 ;
decimal decimalVar = 20.20 m;
char charVar = 'S';
string stringVar = "Hello World";
Ex:
String firstName = "JJ TAM";
String lastName = "Delhi";
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
String firstName = "JJ TAM";
String lastName = "Delhi";
Output
using System ;
class Program
{
static void Main ( string [] args)
{
String quote = "Life is an \"Open Secret\". \nEverything is avialble,
you can't hidden";
Console.WriteLine(quote);
}
}
Output
Life is an "Open Secret".
Everything is avialble, you can't hidden
C#: Verbatim Literal
A verbatim string literal consists of an @ character followed by a string in
double quotes. The escape sequences in verbatim string literal are not
processed.
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
String withoutVerbatim = @"1\n2\n3\t4";
String withoutVerbatim = "1\n2\n3\t4";
Console.WriteLine(withVerbatim);
Console.WriteLine("******************");
Console.WriteLine(withoutVerbatim );
}
}
Output
1\n2\n3\t4
******************
1
2
3 4
As you see the ouput, @ symbol don’t interpret the escape sequences \n, \t.
Where as the string withOutVerbatim interpreted \n as new line and \t as
tab.
C#: Operators
An operator is a symbol which perform an operation
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
int operand1 = 30 ;
int operand2 = 10 ;
Output
operand1 = 30
operand2 = 10
Addition of operand1 and operand2 is 40
Subtraction of operand1 and operand2 is 20
Multiplication of operand1 and operand2 is 300
Division of operand1 and operand2 is 3
Remainder of operand1 and operand2 is 0
C#: Arithmetic Operators: ++, --
++ Increment operator; increments a value by 1
-- Decrement operator; decrements a value by 1
Pre increment
Syntax:
++variable
pre increment operator increments the variable value by 1 immediately.
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
int var = 10 ;
Output
var = 11
Post increment
Syntax:
variable++
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
int var = 10 ;
Output
var = 10
var = 11
Pre Decrement
Syntax:
--variable
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
int var = 10 ;
Output
var = 9
Post Decrement
Syntax:
variable--
Post decrement operator decrements the variable value by 1 after executing
the current statement.
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
int var = 10 ;
Output
var = 10
var = 9
C#: Conditional operators
Conditional operators determine whether one operand is greater than, less
than, equal to, or not equal to another operand.
Conditional operators take two operands and return true, if the condition
evaluates to true, otherwise return false.
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
int a = 10 , b = 11 ;
Output
is a equals to a True
is a equals to b False
is a not equals to a False
is a not equals to b True
is a less than a False
is a less than b True
is a less than or equal to a True
is a less than or equal b True
is a greater than a False
is a greater than b False
is a greater than or equal to a True
is a greater than or equal to b False
C#: Logical Operators
C# provides three logical operators, These are &&(AND), || (OR), and !
(NOT)
Logical AND, OR are called Short circuit operators, will see why these are
called short circuit soon.
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
bool operand1 = true ;
bool operand2 = true ;
operand1 = true ;
operand2 = false ;
Console.WriteLine("\noperand1 = {0}", operand1);
Console.WriteLine("operand2 = {0}", operand2);
Console.WriteLine("operand1 && operand2 = {0}",(operand1 &&
operand2));
operand1 = false ;
operand2 = true ;
Console.WriteLine("\noperand1 = {0}", operand1);
Console.WriteLine("operand2 = {0}", operand2);
Console.WriteLine("operand1 && operand2 = {0}", (operand1 &&
operand2));
operand1 = false ;
operand2 = false ;
Console.WriteLine("\noperand1 = {0}", operand1);
Console.WriteLine("operand2 = {0}", operand2);
Console.WriteLine("operand1 && operand2 = {0}", (operand1 &&
operand2));
}
}
Output
operand1 = True
operand2 = True
operand1 && operand2 = True
operand1 = True
operand2 = False
operand1 && operand2 = False
operand1 = False
operand2 = True
operand1 && operand2 = False
operand1 = False
operand2 = False
operand1 && operand2 = False
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
int a = 10 , b = 21 ;
Output
a is not incremented 10
This statement is evaluated
a is incremented 11
Observation
In the expression (a>b) && (a++ > b), a>b is false, so && operator won't
evaluate second statement in the expression, so a is not incremented.
Logical OR Operator
Operand1-Operand2-Evaluates To
TRUE-TRUE-TRUE
TRUE-FALSE-TRUE
FALSE-TRUE-TRUE
FALSE-FALSE-FALSE
As shown in the above table, || operator returns true if any of the operand
evaluates to true, otherwise returns false.
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
bool operand1 = true ;
bool operand2 = true ;
operand1 = true ;
operand2 = false ;
Console.WriteLine("\noperand1 = {0}", operand1);
Console.WriteLine("operand2 = {0}", operand2);
Console.WriteLine("operand1 || operand2 = {0}", (operand1 ||
operand2));
operand1 = false ;
operand2 = true ;
Console.WriteLine("\noperand1 = {0}", operand1);
Console.WriteLine("operand2 = {0}", operand2);
Console.WriteLine("operand1 || operand2 = {0}", (operand1 ||
operand2));
operand1 = false ;
operand2 = false ;
Console.WriteLine("\noperand1 = {0}", operand1);
Console.WriteLine("operand2 = {0}", operand2);
Console.WriteLine("operand1 || operand2 = {0}", (operand1 ||
operand2));
}
}
Output
operand1 = True
operand2 = True
operand1 || operand2 = True
operand1 = True
operand2 = False
operand1 || operand2 = True
operand1 = False
operand2 = True
operand1 || operand2 = True
operand1 = False
operand2 = False
operand1 || operand2 = False
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
int a = 10 , b = 21 ;
}
}
Output
This statement evaluated
a is not incremented 10
a is incremented 11
Operand -Evaluates To
FALSE-TRUE
TRUE-FALSE
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
bool a = true ;
Console.WriteLine("a = {0}, !a = {1}", a, !a);
a = false ;
Console.WriteLine("a = {0}, !a = {1}", a, !a);
}
}
Output
operand1 = True
operand2 = True
operand1 || operand2 = True
operand1 = True
operand2 = False
operand1 || operand2 = True
operand1 = False
operand2 = True
operand1 || operand2 = True
operand1 = False
operand2 = False
operand1 || operand2 = False
C#: Shift Operators
Bit Wise Left Shift(<<)
Left shift operator shifts all the bits to one bit left, i.e, it simply doubles the
value.
Syntax:
variable << n
int var = 2;
var << 1 = 2 * 2 power 1 = 4
var << 2 = 2 * 2 power 2 = 8
var << 9 = 2 * 2 power 9 = 1024
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
byte byteVar = 7 ;
Console.WriteLine("Value of Byte variable is " + byteVar);
Console.WriteLine("After shifting 1 bit left " + (byteVar << 1 ));
Console.WriteLine("After shifting 2 bits left " + (byteVar << 2 ));
Console.WriteLine("After shifting 3 bits left " + (byteVar << 3 ));
Console.WriteLine("After shifting 4 bits left " + (byteVar << 4 ));
Console.WriteLine("After shifting 5 bits left " + (byteVar << 5 ));
Console.WriteLine("After shifting 6 bits left " + (byteVar << 6 ));
Console.WriteLine("Value of Byte variable is " + byteVar);
}
}
Output
Right shift operator shifts all the bits to one bit right, i.e, it simply half
(divide by 2) the value
Syntax:
variable >> n
right shift the variable by 'n' number of times.
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
int intVar = 128 ;
Output
Value of int variable is 128
After shifting 1 bit Right 64
After shifting 2 bits Right 32
After shifting 3 bits Right 16
After shifting 4 bits Right 8
After shifting 5 bits Right 4
After shifting 6 bits Right 2
After shifting 6 bits Right 1
Value of int variable is 128
C#: Bitwise Operators
Bit Wise AND(&), OR(|), Exclusive OR(^)
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
byte a = 8 ;
byte b = 9 ;
Output
a & b is 8
a | b is 9
a ^ b is 1
Explanation
a = 0000 1000
b = 0000 1001
a&b = 0000 1000
a = 0000 1000
b = 0000 1001
a|b = 0000 10001
a = 0000 1000
b = 0000 1001
a^b = 0000 0001
C#: Compound Assignment
Operators
Compound Assignment
Syntax:
variable operator= value
Example:
int a = 10;
a+=10 evaluates to a=a+10
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
int var1 = 100 ;
int sum = 10 , sub = 10 , mul = 10 , div = 1000 ;
Output
sum+var1 is 110
sub-var1 is -90
mul*var1 is 1000
div/var1 is10
C#: Ternary operator( ?: )
Returns one of two expressions depending on a condition.
Syntax
test ? expression1 : expression2
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
int a = 100 ;
Output
flag = True
C#: Arrays
An array is a series of elements of the same type placed in contiguous
memory locations. Elements in the array are accessed using index positions.
Syntax
datatype[] arrayName = new datatype[sizeOfTheArray];
Ex:
int[] evenNumbers = new int[10];
int var1, var2, var3, var4, var5, var6, var7, var8, var9;
var1 = 5;
var2 = -10;
var3 = 7;
var4 = 8
var5 = 11;
var6 = 12;
var7 = 14;
var8 = 21;
var9 = 0;
var[0] = 5;
var[1] = -10;
var[2] = 7;
var[3] = 8
var[4] = 11;
var[5] = 12;
var[6] = 14;
var[7] = 21;
var[8] = 0;
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
int [] var = new int [ 9 ];
var [ 0 ] = 5 ;
var [ 1 ] = - 10 ;
var [ 2 ] = 7 ;
var [ 3 ] = 8 ;
var [ 4 ] = 11 ;
var [ 5 ] = 12 ;
var [ 6 ] = 14 ;
var [ 7 ] = 21 ;
var [ 8 ] = 0 ;
Output
var[0] = 5
var[1] = -10
var[2] = 7
var[3] = 8
var[4] = 11
var[5] = 12
var[6] = 14
var[7] = 21
var[8] = 0
C#: Comments
Comments make the program more readable. Comments are used to
document your code.
class Program
{
static void Main ( string [] args)
{
int marks; /* variable marks represents the marks
obtained by a student */
marks = 70 ;
Output
Marks : 70
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
IntresetCalculator calc;
}
}
/// <summary>
/// Class Calculates simple intrest
/// </summary>
class IntresetCalculator
{
When you hover the mouse on ‘IntresetCalculator’, you can able to see the
summary of ‘IntresetCalculator’ class.
C#: if, else : Conditional statements
C# provides control flow statements for decision making.
if statement
“if” statement execute the section of code when the condition evaluates to
true.
Syntax
if(condition){
// Executes if the condition true
}
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
Console.WriteLine("Please Enter Your Marks");
if (marks >= 35 )
{
Console.WriteLine("Congrats, you passed in the Exam");
}
}
}
Sample Output1
Please Enter Your Marks
85
Congrats, you passed in the Exam
Sample Output2
Please Enter Your Marks
20
You failed in the Exam. Better luck next time
if-else statement
Syntax:
if(condition){
}
else{
If the condition true, then if block code executed, otherwise else block code
executed.
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
Console.WriteLine("Please Enter Your Marks");
if (marks < 35 )
{
Console.WriteLine("You failed in the Exam. Better luck next time");
}
else
{
Console.WriteLine("Congrats, you passed in the Exam");
}
}
}
Sample Output1
Please Enter Your Marks
85
Congrats, you passed in the Exam
Sample Output2
Please Enter Your Marks
20
You failed in the Exam. Better luck next time
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
Console.WriteLine("Please Enter Your Marks");
if (marks < 35 )
{
Console.WriteLine("You are failed");
}
else if (marks < 50 )
{
Console.WriteLine("You are passed and got third class");
}
else if (marks < 60 )
{
Console.WriteLine("You are passed and got second class");
}
else if (marks < 70 )
{
Console.WriteLine("You are passed and got first class");
}
else
{
Console.WriteLine("You are passed and got distinction");
}
}
}
Sample Output1
Please Enter Your Marks
20
You are failed
Sample Output2
Please Enter Your Marks
40
You are passed and got third class
Sample Output3
Please Enter Your Marks
60
You are passed and got first class
Sample Output4
Please Enter Your Marks
80
You are passed and got distinction
C#: Switch statement
switch statement evaluates its expression, then executes all statements that
follow the matching case label. The body of a switch statement is known as
a switch block. A statement in the switch block can be labelled with one or
more case or default labels.
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
Console.WriteLine("Enter a Number");
switch (number)
{
case 1 :
Console.WriteLine("Sunday");
break ;
case 2 :
Console.WriteLine("Monday");
break ;
case 3 :
Console.WriteLine("Tueday");
break ;
case 4 :
Console.WriteLine("Wednesday");
break ;
case 5 :
Console.WriteLine("ThursDay");
break ;
case 6 :
Console.WriteLine("Friday");
break ;
case 7 :
Console.WriteLine("Saturday");
break ;
default :
Console.WriteLine("You entered wrong day number");
break ;
}
}
}
Sample Output
Enter a Number
5
ThursDay
Sample Output
Enter a Number
15
You entered wrong day number
C#: goto statement
By using goto statement, we can transfer the control to a label. Label is a
marker in the program, where your code can jump there directly.
Syntax
goto label;
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
Console.WriteLine("Enter a Number");
if (num == 5 )
{
goto error;
} else
{
Console.WriteLine("You Entered {0}", num);
goto exit;
}
error:
Console.WriteLine("Wrong Choice");
System.Environment.Exit( 1 );
exit:
Console.WriteLine("Exiting Successfully");
System.Environment.Exit( 0 );
}
}
Sample Output1
Enter a Number
5
Wrong Choice
Sample Output2
Enter a Number
10
You Entered 10
Exiting Successfully
C#: while loop
while statement executes a block of statements until a particular condition is
true
Syntax
while (expression) {
//statements
}
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
int var1 = 0 ;
while (var1 < 10 )
{
Console.WriteLine(var1);
var1++;
}
}
}
Output
0
1
2
3
4
5
6
7
8
9
C#: do-while loop
do-while is a loop construct like while loop, but evaluates its expression at
the end of the loop.
Syntax
do {
//statement(s)
} while (expression);
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
int var1 = 0 ;
do
{
Console.WriteLine(var1);
var1++;
} while (var1 < 10 );
}
}
Output
0
1
2
3
4
5
6
7
8
9
C#: for loop
‘for’ statement provides a compact way to iterate over a range of values.
Syntax
for(initialization; condition; update){
//statements to be executed
}
‘for’ loop execute the statements until the condition evaluates to false.
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
for ( int var1 = 0 ; var1 < 10 ; var1++)
{
Console.WriteLine(var1);
}
}
}
Output
0
1
2
3
4
5
6
7
8
9
C#: for-each loop
‘for-each’ loop is used to iterate over a collection of elements.
Syntax
foreach(datatype variable in collection){
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
int [] primeNumbers = new int [ 10 ];
primeNumbers[ 0 ] = 2 ;
primeNumbers[ 1 ] = 3 ;
primeNumbers[ 2 ] = 5 ;
primeNumbers[ 3 ] = 7 ;
primeNumbers[ 4 ] = 11 ;
primeNumbers[ 5 ] = 13 ;
foreach ( int num in primeNumbers)
{
Console.WriteLine(num);
}
}
}
Output
2
3
5
7
11
13
0
0
0
0
C#: break statement
‘break’ statement is used to come out of the loop.
Syntax
break;
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
for ( int i = 0 ; i < 10 ; i++)
{
if (i == 5 ) break ;
Console.WriteLine(i);
}
Console.WriteLine("I am out of the loop");
}
}
Output
0
1
2
3
4
I am out of the loop
C#: continue statement
‘continue’ statement skips the current iteration of for, while, do-while, for-
each loops.
Syntax
continue;
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
for ( int i = 0 ; i < 10 ; i++)
{
if (i % 2 == 0 ) continue ;
Console.WriteLine(i);
}
Console.WriteLine("I am out of the loop");
}
}
Output
1
3
5
7
9
I am out of the loop
C#: Methods
Method is a block of statements, you can define method once and execute it
any number of times.
Syntax
accessModifier returnType methodName(arguments){
//Body Of the method
}
Don’t worry about accessModifier now, I will explain about this, after
explaining about classes.
returnType is the value returned by the method, this can be any valid
predefined (or) custom data type. If you don’t want to return any value from
the method, make the return type as ‘void’.
Example
int sum(int a, int b)
{
return a + b;
}
int : Return type of the method sum
sum: Method name
int a, int b : Arguments to the method sum
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
Program obj = new Program();
obj.printEvenNumbers();
}
int sum ( int a, int b)
{
return a + b;
}
void printEvenNumbers ()
{
Console.WriteLine("Even Numbers from 0 to 10 are : ");
for ( int i= 0 ; i< 10 ; i += 2 )
{
Console.WriteLine(i);
}
}
Output
Sum of 10 and 5 is 15
Subtraction of 10 and 5 is 5
Multiplication of 10 and 5 is 50
Division of 10 and 5 is 2
Even Numbers from 0 to 10 are :
0
2
4
6
8
Notify above snippet, methods are called using the instance (object) of the
class Program.
Static Methods
Methods defined using static keyword are called static methods. These are
called class level methods. Static methods are called by class name.
Ex:
static int sum(int a, int b)
{
return a + b;
}
You can call above method by using ‘Program.sum(10, 5)’, where Program
is the class name.
Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
Program obj = new Program();
Program.printEvenNumbers();
}
}
Output
Sum of 10 and 5 is 15
Subtraction of 10 and 5 is 5
Multiplication of 10 and 5 is 50
Division of 10 and 5 is 2
Even Numbers from 0 to 10 are :
0
2
4
6
8
C++
CODING PRACTICE
EXERCISES
C++ CODE
#include <iostream>
using namespace std;
int main()
{
cout << "\n\n Find the perfect numbers between 1 and 500:\n";
cout << "------------------------------------------------\n";
int i = 1, u = 1, sum = 0;
cout << "\n The perfect numbers between 1 to 500 are: \n";
while (i <= 500)
{
while (u <= 500)
{
if (u < i)
{
if (i % u == 0)
sum = sum + u;
}
u++;
}
if (sum == i) {
cout << i << " " << "\n";
}
i++;
u = 1;
sum = 0;
}
}
OUTPUT
Check whether a number is prime
or not
C++ CODE
#include <iostream>
using namespace std;
int main()
{
int num1, ctr = 0;
cout << "\n\n Check whether a number is prime or not:\n";
cout << "--------------------------------------------\n";
cout << " Input a number to check prime or not: ";
cin>> num1;
for (int a = 1; a <= num1; a++)
{
if (num1 % a == 0)
{
ctr++;
}
}
if (ctr == 2)
{
cout << " The entered number is a prime number. \n";
}
else {
cout << " The number you entered is not a prime number. \n";
}
}
OUTPUT
Find prime number within a range
C++ CODE
#include <iostream>
#include<math.h>
using namespace std;
int main()
{
int num1,num2;
int fnd=0,ctr=0;
cout << "\n\n Find prime number within a range:\n";
cout << "--------------------------------------\n";
cout << " Input number for starting range: ";
cin>> num1;
cout << " Input number for ending range: ";
cin>> num2;
cout << "\n The prime numbers between "<<num1<<" and "<<num2<<"
are:"<<endl;
for(int i=num1;i<=num2;i++)
{
for(int j=2;j<=sqrt(i);j++)
{
if(i%j==0)
ctr++;
}
if(ctr==0&&i!=1)
{ fnd++;
cout<<i<<" ";
ctr=0;
}
ctr=0;
}
cout<<"\n\n The total number of prime numbers between "<<num1<<" to "
<<num2<<" is: "<<fnd<<endl;
return 1;
}
OUTPUT
Find the factorial of a number
C++ CODE
#include <iostream>
using namespace std;
int main()
{
int num1,factorial=1;
cout << "\n\n Find the factorial of a number:\n";
cout << "------------------------------------\n";
cout << " Input a number to find the factorial: ";
cin>> num1;
for(int a=1;a<=num1;a++)
{
factorial=factorial*a;
}
cout<<" The factorial of the given number is: "<<factorial<<endl;
return 0;
}
OUTPUT
Find the last prime number occur
before the entered number
C++ CODE
#include <iostream>
using namespace std;
int main()
{
int num1, ctr = 0;
cout << "\n\n Find the last prime number occurs before the entered
number:\n";
cout << "-----------------------------------------------------------------\n";
cout << " Input a number to find the last prime number occurs before the
number: ";
cin >> num1;
for (int n = num1 - 1; n >= 1; n--)
{
for (int m = 2; m < n; m++)
{
if (n % m == 0)
ctr++;
}
if (ctr == 0)
{
if (n == 1)
{
cout << "no prime number less than 2";
break;
}
cout << n << " is the last prime number before " << num1 << endl;
break;
}
ctr = 0;
}
return 0;
}
OUTPUT
Program in C++ to find factorial of
large numbers using array
Example of 5
For x=2
ar[]=1, ar_size=1
p=2*ar[]=2*1 ,c=0
ar[]=2 ,c=0
For x=3
ar[]=2,ar_size=1
p=3*ar[]=3*2 ,c=0
ar[]=6 ,c=0
For x=4
ar[]=6,ar_size=1
p=4*ar[]=4*6=24 ,c=2
ar[]=4, c=2 ar[]=42,c=0
For x=5
ar[]=42,c=0
p=5*4=20
ar[]=0 ,c=2
p=5*2+c=12
ar[]=021
PROGRAM
#include<iostream>
using namespace std;
void factorial(int n)
{
int ar[size];
ar[0] = 1;
int ar_size = 1;
for (int x=2; x<=n; x++)
ar_size = fact(x, ar, ar_size);
for (int i=ar_size-1; i>=0; i--)
cout << ar[i];
cout<<endl;
}
while (c)
{
ar[ar_size] = c%10;
c = c/10;
ar_size++;
}
return ar_size;
}
int main()
{
int n;
return 0;
}
OUTPUT
program in C++ Read and print
details of a student using class
PROGRAM
/*C++ program to create class for a student.*/
#include <iostream>
using namespace std;
class student
{
private:
char name[30];
int rollNo;
int total;
float perc;
public:
//member function to get student's details
void getDetails(void);
//member function to print student's details
void putDetails(void);
};
int main()
{
student std; //object creation
std.getDetails();
std.putDetails();
return 0;
}
OUTPUT
Program C++ to print all Even and
Odd numbers
PROGRAM
// C++ program to print all
// Even and Odd numbers from 1 to N
#include <iostream>
using namespace std;
// function : evenNumbers
// description: to print EVEN numbers only.
void evenNumbers(int n)
{
int i;
for (i = 1; i <= n; i++) {
//condition to check EVEN numbers
if (i % 2 == 0)
cout << i << " ";
}
cout << "\n";
}
// function : oddNumbers
// description: to print ODD numbers only.
void oddNumbers(int n)
{
int i;
for (i = 1; i <= n; i++) {
//condition to check ODD numbers
if (i % 2 != 0)
cout << i << " ";
}
cout << "\n";
}
// main code
int main()
{
int N;
// input the value of N
cout << "Enter the value of N (limit): ";
cin >> N;
return 0;
}
OUTPUT
Code in C++ to find power of a
number using loop
Example:
Input:
base: 5, power: 4
Output:
625
PROGRAM
#include <iostream>
using namespace std;
int main()
{
int num;
int a = 1;
int pw;
cout << a;
return 0;
}
OUTPUT
Enter a number: 5
Enter a power : 3
125
Program in C++ to Convert Roman
Number
Example:
Input: XIV
Output: 14
Input: XI
Output: 11
PROGRAM
#include <bits/stdc++.h>
map<char,int> rmap;
rmap['I'] = 1;
rmap['V'] = 5;
rmap['X'] = 10;
rmap['L'] = 50;
rmap['C'] = 100;
rmap['D'] = 500;
rmap['M'] =1000;
int number=0,i=0;
if(roman.length()<=1){
return rmap[roman.at(0)];
}
else{
while(i<roman.size()){
if(rmap[roman[i]]<rmap[roman[i+1]]){
number+=rmap[roman[i+1]]-rmap[roman[i]];
i+=2;
else{
number+=rmap[roman[i]];
i++;
return number;
}
int main(){
string roman;
getline(cin,roman);
int number;
number=roman_to_int(roman);
return 0;
OUTPUT
Check if a number is power of 2 or
not in C++
PROGRAM
#include <iostream>
if(n>0)
{
while(n%2 == 0)
{
n/=2;
}
if(n == 1)
{
cout<<"Number is power of 2"<<endl;
}
}
if(n == 0 || n != 1)
{
cout<<"Number is not power of 2"<<endl;
}
return 0;
}
OUTPUT
Program in C++ to find LCM of
two numbers
LCM (least common multiple)
PROGRAM
#include <iostream>
using namespace std;
int main()
{
int m,n,max;
m=12;
n=15;
if(m > n)
max= m;
else
max = n;
while(true)
{
if (max % m == 0 && max % n == 0)
{
cout << "LCM of "<<m<<" and "<<n<<" = "<< max;
break;
}
else
max++;
}
return 0;
}
OUTPUT
LCM of 12 and 15 = 60
Code in C++ to find power of a
number using loop
Example:
Input:
base: 5, power: 4
Output:
625
PROGRAM
#include <iostream>
using namespace std;
int main()
{
int num;
int a = 1;
int pw;
cout << a;
return 0;
}
OUTPUT
Enter a number: 5
Enter a power : 3
125
Reverse an integer number in C++
PROGRAM
#include <iostream>
using namespace std;
int main()
{
long int num,sum;
int digit;
//input integer number
cout<<"Enter an integer number: ";
cin>>num;
//check validation
if(num<0)
{
cout<<"Input positive number!!!"<<endl;
return -1;
}
//Reverse number
sum=0;
while(num>0)
{
digit=num%10; //get digit
sum = (sum*10) + digit;
num=num/10;
}
cout<<"Reverse number is: "<<sum<<endl;
return 0;
}
OUTPUT
C++ program to check EVEN or
ODD
using if else in C++
PROGRAM
#include <iostream>
using namespace std;
int main()
{
int num;
cout<<"Enter an integer number: ";
cin>>num;
if(num%2==0)
cout<<num<<" is an EVEN number."<<endl;
else
cout<<num<<" is an ODD number."<<endl;
return 0;
}
OUTPUT
Enter an integer number: 50
is an EVEN number.
Find the Greatest Common Divisor
(GCD) of two numbers
C++ CODE
#include <iostream>
using namespace std;
int main()
{
int num1, num2, gcd;
cout << "\n\n Find the Greatest Common Divisor of two numbers:\n";
cout << "-----------------------------------------------------\n";
cout << " Input the first number: ";
cin >> num1;
cout << " Input the second number: ";
cin >> num2;