0% found this document useful (0 votes)
21 views137 pages

Learn c# Quickly and c++ Coding Practice Exercises_ Coding -- Tam, Jj -- 2021 -- A2760371e7f02ced6e6269d246f686e0 -- Anna’s Archive

The document is a comprehensive guide for beginners to learn C# and C++ programming languages, covering fundamental concepts, syntax, and coding exercises. It includes sections on data types, operators, control statements, and practical coding examples in both languages. The guide aims to provide hands-on projects and exercises to enhance coding skills for new programmers.

Uploaded by

Sarthak Arghode
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views137 pages

Learn c# Quickly and c++ Coding Practice Exercises_ Coding -- Tam, Jj -- 2021 -- A2760371e7f02ced6e6269d246f686e0 -- Anna’s Archive

The document is a comprehensive guide for beginners to learn C# and C++ programming languages, covering fundamental concepts, syntax, and coding exercises. It includes sections on data types, operators, control statements, and practical coding examples in both languages. The guide aims to provide hands-on projects and exercises to enhance coding skills for new programmers.

Uploaded by

Sarthak Arghode
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 137

LEARN C# QUICKLY

AND
C++
CODING PRACTICE
EXERCISES

CODING FOR BEGINNERS


WITH HANDS ON PROJECTS
BY
J J TAM
INTRODUCTION TO C#
C#: HELLO WORLD PROGRAM
C#: READ INPUT FROM CONSOLE
C#: BUILT IN TYPES
C#: STRINGS AND ESCAPE SEQUENCES
C#: VERBATIM LITERAL
C#: OPERATORS
C#: ARITHMETIC OPERATORS
C#: ARITHMETIC OPERATORS: ++, --
C#: CONDITIONAL OPERATORS
C#: LOGICAL OPERATORS
C#: SHIFT OPERATORS
C#: BITWISE OPERATORS
C#: COMPOUND ASSIGNMENT OPERATORS
C#: TERNARY OPERATOR( ?: )
C#: ARRAYS
C#: COMMENTS
C#: IF, ELSE : CONDITIONAL STATEMENTS
C#: SWITCH STATEMENT
C#: GOTO STATEMENT
C#: WHILE LOOP
C#: DO-WHILE LOOP
C#: FOR LOOP
C#: FOR-EACH LOOP
C#: BREAK STATEMENT
C#: CONTINUE STATEMENT
C#: METHODS
C++ CODING EXERCISES
C++ EXERCISES: FIND THE FIRST 10 NATURAL NUMBERS
FIND THE SUM OF FIRST 10 NATURAL NUMBERS
DISPLAY N TERMS OF NATURAL NUMBER AND THEIR SUM
FIND THE PERFECT NUMBERS BETWEEN 1 AND 500
CHECK WHETHER A NUMBER IS PRIME OR NOT
FIND PRIME NUMBER WITHIN A RANGE
FIND THE FACTORIAL OF A NUMBER
FIND THE LAST PRIME NUMBER OCCUR BEFORE THE ENTERED NUMBER
PROGRAM IN C++ TO FIND FACTORIAL OF LARGE NUMBERS USING ARRAY
PROGRAM IN C++ READ AND PRINT DETAILS OF A STUDENT USING CLASS
PROGRAM C++ TO PRINT ALL EVEN AND ODD NUMBERS
CODE IN C++ TO FIND POWER OF A NUMBER USING LOOP
PROGRAM IN C++ TO CONVERT ROMAN NUMBER
CHECK IF A NUMBER IS POWER OF 2 OR NOT IN C++
PROGRAM IN C++ TO FIND LCM OF TWO NUMBERS
CODE IN C++ TO FIND POWER OF A NUMBER USING LOOP
REVERSE AN INTEGER NUMBER IN C++
C++ PROGRAM TO CHECK EVEN OR ODD
FIND THE GREATEST COMMON DIVISOR (GCD) OF TWO NUMBERS
OUR OTHER PUBLISHING
LEARN C# QUICKLY

CODING FOR BEGINNERS


BY
J J TAM
Introduction to C#
C# is a programming language that supports more than one programming
paradigm. The basic syntax of C# is similar to that of C, C++ and Java. So
if you are familiar with any one of these languages, you can learn C# just
like that.

What is multi-paradigm programming language?


A Language that supports more than one programming paradigm is called
multi-paradigm programming language. C# is a multi-paradigm
programming language, it supports both imperative and object-oriented
paradigms. C# support some level of functional programming also.

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’.

What is the latest version of C#?


At the time of writing this article, the most recent version is C# 6.0 which
was released in 2015.

Prerequisites to work with C#


Install Visual studio. You can get the community edition from following
link.
https://www.visualstudio.com/vs/community/
C#: Hello World Program
I hope, you installed Visual studio. Following step-by-step procedure
explains simple ‘Hello World’ application.

Step 1: Open Visual studio

Step 2: Go to File -> New -> Project.


Select “Console Application”, give the project name as “HelloWorld”.

Press OK.

It creates a file ‘Program.cs’, with some default data.

Update the program like below.

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.

Let’s analyze the program

‘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.

static void Main(string[] args)


Main method is the entry point of your C# application. Application
executions starts from here.

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.

String name = Console.ReadLine();

Program.cs
using System ;

class Program
{
static void Main ( string [] args)
{
Console.WriteLine("Welcome to C#, Please Enter Basic Informaiton");

Console.WriteLine("Enter Your Name");


String name = Console.ReadLine();

Console.WriteLine("Enter Your Age");


String age = Console.ReadLine();

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

Place Holder Syntax

While concatenating the strings, place holder syntax is very convenient than
using ‘+’ operator.

Following is the example of place holder syntax.

Console.WriteLine("Hello {0}. You are {1} years old", name, age);

Above statement is equivalent of following statement.

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");

Console.WriteLine("Enter Your Name");


String name = Console.ReadLine();

Console.WriteLine("Enter Your Age");


String age = Console.ReadLine();

Console.WriteLine("Hello {0}", name);


Console.WriteLine("You are {0} years old", age);

Console.WriteLine("Hello {1}. You are {0} years old", name, age);

}
}

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

Following table summarizes all the data types


Short Class Min value Max value
Name
byte Byte 0 255
sbyte SByte -128 127
int Int32 -2,147,483,648 2,147,483,647
uint UInt32 0 4294967295
short Int16 -32,768 32767
ushort UInt16 0 65535
long Int64 - 9223372036854775808 9223372036854775807
ulong UInt64 0 18446744073709551615
float Single -3.402823e38 3.402823e38
double Double -1.79769313486232e308 1.79769313486232e308
decimal Decimal ±1.0 × 10e−28 ±7.9 × 10e28
char Char Represent Unicode
character. It take 16 bits.
string String Sequence of characters
Note
a. Suffix Float variables by f.
Ex: float floatVar = 18.18f;

b. Suffix Decimal variables by m.


Ex: decimal decimalVar = 20.20m;

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";

Console.WriteLine("byteVar = {0}", byteVar);


Console.WriteLine("sbyteVar = {0}", sbyteVar);
Console.WriteLine("intVar = {0}", intVar);
Console.WriteLine("uintVar = {0}", uintVar);
Console.WriteLine("shortVar = {0}", shortVar);
Console.WriteLine("ushortVar = {0}", ushortVar);
Console.WriteLine("longVar = {0}", longVar);
Console.WriteLine("ulongVar = {0}", ulongVar);
Console.WriteLine("floatVar = {0}", floatVar);
Console.WriteLine("doubleVar = {0}", doubleVar);
Console.WriteLine("decimalVar = {0}", decimalVar);
Console.WriteLine("charVar = {0}", charVar);
Console.WriteLine("stringVar = {0}", stringVar);
}
}
C#: Strings and Escape Sequences
String is a Collection of characters. Strings are enclosed in double quotes.

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";

Console.WriteLine("Hello Mr {0} {1}", firstName, lastName);


}
}

Output

Hello Mr JJ TAM Delhi


Escape Sequences

Escape sequences in programing languages has special meaning, For


example, \n prints string in new line, \t is a tab character etc., Following
tables summarizes some of the escape characters in C#.

Escape Sequence Description


\a Bell alert
\b Backspace
\f Form feed
\n New Line
\r Carriage Return
\t Horizontal tab
\v Vertical tab
\’ Single Quote
\" Double Quote
\\ Backslash
\? Question Mark
\ooo ASCII Character in Octal Notation
\xhh ASCII Character in hexadecimal notation
\xhhhh Unicode character in hexadecimal notation
Program.cs

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

An operator is said to be unary, if it performs operation on single operand.


Ex:
int a = 10;
a++;

An operator is said to be binary, if it performs operation on two operands


Ex:
int a=10, b=20;
int c = a-b;

An Operator is said to be ternary if it perform operation on three operands


Ex:
int a = 10, b=20, c;
c= (a>b) ? a : b;

Operators in C# are divided into 4 major categories


Arithmetic
Conditional
Logical
Bitwise
C#: Arithmetic Operators
Arithmetic operators are used to perform arithmetic operation on operands.

Program.cs
using System ;

class Program
{
static void Main ( string [] args)
{
int operand1 = 30 ;
int operand2 = 10 ;

Console.WriteLine("operand1 = {0}", operand1);


Console.WriteLine("operand2 = {0}", operand2);
Console.WriteLine("Addition of operand1 and operand2 is {0}",
(operand1 + operand2));
Console.WriteLine("Subtraction of operand1 and operand2 is {0}",
(operand1 - operand2));
Console.WriteLine("Multiplication of operand1 and operand2 is {0}",
(operand1 * operand2));
Console.WriteLine("Division of operand1 and operand2 is {0}",
(operand1 / operand2));
Console.WriteLine("Remainder of operand1 and operand2 is {0}",
(operand1 % operand2));
}
}

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 ;

Console.WriteLine("var = {0}", ++ var );


}
}

Output
var = 11
Post increment
Syntax:
variable++

Post increment operator increments the variable value by 1 after


executing the current statement.

Program.cs
using System ;

class Program
{
static void Main ( string [] args)
{
int var = 10 ;

Console.WriteLine("var = {0}", var ++);


Console.WriteLine("var = {0}", var );
}
}

Output
var = 10
var = 11

Pre Decrement
Syntax:
--variable

Pre decrement operator decrements the variable value by 1 immediately.

Program.cs
using System ;

class Program
{
static void Main ( string [] args)
{
int var = 10 ;

Console.WriteLine("var = {0}", -- var );


}
}

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 ;

Console.WriteLine("var = {0}", var --);


Console.WriteLine("var = {0}", var );
}
}

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 ;

Console.WriteLine("is a equals to a {0}", (a == a));


Console.WriteLine("is a equals to b {0}", (a == b));
Console.WriteLine("is a not equals to a {0}", (a != a));
Console.WriteLine("is a not equals to b {0}", (a != b));
Console.WriteLine("is a less than a {0}", (a < a));
Console.WriteLine("is a less than b {0}", (a < b));
Console.WriteLine("is a less than or equal to a {0}", (a <= a));
Console.WriteLine("is a less than or equal b {0}", (a <= b));
Console.WriteLine("is a greater than a {0}", (a > a));
Console.WriteLine("is a greater than b {0}", (a > b));
Console.WriteLine("is a greater than or equal to a {0}", (a >= a));
Console.WriteLine("is a greater than or equal to b {0}", (a >= b));
}
}

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 is also called Conditional AND

Logical OR is also called Conditional OR

Logical AND, OR are called Short circuit operators, will see why these are
called short circuit soon.

Logical AND Operator

Operand1 - Operand2 - Evaluates To


TRUE-TRUE-TRUE
TRUE-FALSE-FALSE
FALSE-TRUE-FALSE
FALSE-FALSE-FALSE

Program.cs
using System ;

class Program
{
static void Main ( string [] args)
{
bool operand1 = true ;
bool operand2 = true ;

Console.WriteLine("operand1 = {0}", operand1);


Console.WriteLine("operand2 = {0}", operand2);
Console.WriteLine("operand1 && operand2 = {0}", (operand1 &&
operand2));

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

Why Logical AND is called short circuit operator?


Since if the first statement in the expression evaluates to false, then java
won't evaluate the entire expression. So Logical AND is called short circuit
AND.

Program.cs
using System ;

class Program
{
static void Main ( string [] args)
{
int a = 10 , b = 21 ;

if ((a > b) && (a++ > b))


{
Console.WriteLine("This statement not evaluated");
}
Console.WriteLine("a is not incremented " + a);

if ((a < b) && (a++ < b))


{
Console.WriteLine("This statement is evaluated");
}
Console.WriteLine("a is incremented " + a);
}
}

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 ;

Console.WriteLine("operand1 = {0}", operand1);


Console.WriteLine("operand2 = {0}", operand2);
Console.WriteLine("operand1 || operand2 = {0}", (operand1 ||
operand2));

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

Why Logical OR is called short circuit operator?


Since if the first statement evaluates to true, then java won't evaluates the
entire expression. So Logial OR is called short circuit OR.

Program.cs
using System ;

class Program
{
static void Main ( string [] args)
{
int a = 10 , b = 21 ;

if ((a < b) || (a++ < b))


{
Console.WriteLine("This statement evaluated");
}
Console.WriteLine("a is not incremented " + a);

if ((a > b) || (a++ > b))


{
Console.WriteLine("This statement is evaluated");
}
Console.WriteLine("a is incremented " + a);

}
}
Output
This statement evaluated
a is not incremented 10
a is incremented 11

Logical (!)NOT operator

Operand -Evaluates To
FALSE-TRUE
TRUE-FALSE

If the operand is FALSE, ! Operator evaluates it to TRUE


If the operand is TRUE, ! Operator evaluates it to 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

left shift the variable by 'n' number of times.

Variable << n is equals to variable = variable * 2 power 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

Value of Byte variable is 7


After shifting 1 bit left 14
After shifting 2 bits left 28
After shifting 3 bits left 56
After shifting 4 bits left 112
After shifting 5 bits left 224
After shifting 6 bits left 448
Value of Byte variable is 7
Bit Wise Right Shift(>>)

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.

Variable >> n is equals to variable = variable / 2 power n

int var = 128;


var >> 1 = 128 / (2 power 1) = 64
var >> 2 = 128 / (2 power 2) = 32

Program.cs

using System ;

class Program
{
static void Main ( string [] args)
{
int intVar = 128 ;

Console.WriteLine("Value of int variable is " + intVar);


Console.WriteLine("After shifting 1 bit Right " + (intVar >> 1 ));
Console.WriteLine("After shifting 2 bits Right " + (intVar >> 2 ));
Console.WriteLine("After shifting 3 bits Right " + (intVar >> 3 ));
Console.WriteLine("After shifting 4 bits Right " + (intVar >> 4 ));
Console.WriteLine("After shifting 5 bits Right " + (intVar >> 5 ));
Console.WriteLine("After shifting 6 bits Right " + (intVar >> 6 ));
Console.WriteLine("After shifting 6 bits Right " + (intVar >> 7 ));
Console.WriteLine("Value of int variable is " + intVar);
}
}

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 ;

Console.WriteLine("a & b is " + (a & b));


Console.WriteLine("a | b is " + (a | b));
Console.WriteLine("a ^ b is " + (a ^ b));
}
}

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

Compound Example Description


Operator
+= a+=10 a=a+10
-= a-=10 a=a-10
*= a*=10 a=a*10
/= a/=10 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 ;

Console.WriteLine("sum+var1 is " + (sum += var1));


Console.WriteLine("sub-var1 is " + (sub -= var1));
Console.WriteLine("mul*var1 is " + (mul *= var1));
Console.WriteLine("div/var1 is " + (div /= var1));
}
}

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

Returns expression1 if the “test” condition evaluates to true other wise


returns expression2.

Program.cs
using System ;

class Program
{
static void Main ( string [] args)
{
int a = 100 ;

bool flag = a > 10 ? true : false ;


Console.WriteLine("flag = {0}", flag);
}
}

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];

Suppose if you want to calculate sum of 9 integers, you have to define 9


variables like below

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;

By using arrays we can declare like below


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;

As you see, Array indexes starts from 0. var[0] represents 5, var[2]


represents 7 and so on.

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 ;

Console.WriteLine("var[0] = {0}", var [ 0 ]);


Console.WriteLine("var[1] = {0}", var [ 1 ]);
Console.WriteLine("var[2] = {0}", var [ 2 ]);
Console.WriteLine("var[3] = {0}", var [ 3 ]);
Console.WriteLine("var[4] = {0}", var [ 4 ]);
Console.WriteLine("var[5] = {0}", var [ 5 ]);
Console.WriteLine("var[6] = {0}", var [ 6 ]);
Console.WriteLine("var[7] = {0}", var [ 7 ]);
Console.WriteLine("var[8] = {0}", var [ 8 ]);
}
}

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.

Suppose you written thousand lines of program, without proper


documentation, after some time, for the owner of the application also, it is
very difficult to figure out what was written.

Comments solve this problem:


By using comments, you can document your code at the time of writing
program. Comments don't affect your program execution. Comments
simply document your code.

C# supports 3 types of comments

Single line comment :


Single line comments starts with //
// It is a single line comment

Multi Line comment


Multi line comments are place in between /* */
/* I am a mulltiline comment */

XML Documentation Comments


XML Documentation comments are used to provide help to given class,
function, namespace etc.,
Program.cs
using System ;

class Program
{
static void Main ( string [] args)
{
int marks; /* variable marks represents the marks
obtained by a student */
marks = 70 ;

Console.WriteLine("Marks : {0}", marks); //printing to console


}
}

Output
Marks : 70

XML Documentation Comments Example


Update Program.cs like below.

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.

Decision making statements

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");

int marks = int .Parse(Console.ReadLine());


if (marks < 35 )
{
Console.WriteLine("You failed in the Exam. Better luck next time");
}

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");

int marks = int .Parse(Console.ReadLine());

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

if-else if-else ladder

By using if-else if-else construct, you can choose number of alternatives.

An if statement can be followed by an optional else if...else statement,


which is very useful to test various conditions.

Program.cs
using System ;
class Program
{
static void Main ( string [] args)
{
Console.WriteLine("Please Enter Your Marks");

int marks = int .Parse(Console.ReadLine());

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");

int number = int .Parse(Console.ReadLine());

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");

int num = int .Parse(Console.ReadLine());

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
}

The expression in the while statement must evaluates to a Boolean value,


otherwise compiler throws an error. While statement first evaluates the
expression, until the expression evaluates to true, it executes the code inside
the while block, otherwise it comes out of the while loop.

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.

Initialization section executed only once, at the starting of loop.


Condition section evaluated every time, before executing the loop
statements
Update section executes immediately after every execution of loop
finishes.

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’.

methodName is any valid name which is not a C# keyword.

You can pass zero (or) more arguments to the method.

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();

int result1 = obj.sum( 10 , 5 );


int result2 = obj.sub( 10 , 5 );
int result3 = obj.mul( 10 , 5 );
int result4 = obj.div( 10 , 5 );

Console.WriteLine("Sum of 10 and 5 is {0}", result1);


Console.WriteLine("Subtraction of 10 and 5 is {0}", result2);
Console.WriteLine("Multiplication of 10 and 5 is {0}", result3);
Console.WriteLine("Division of 10 and 5 is {0}", result4);

obj.printEvenNumbers();
}
int sum ( int a, int b)
{
return a + b;
}

int sub ( int a, int b)


{
return a - b;
}

int mul ( int a, int b)


{
return a * b;
}

int div ( 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.

Program obj = new Program();

int result1 = obj.sum(10, 5);


int result2 = obj.sub(10, 5);
int result3 = obj.mul(10, 5);
int result4 = obj.div(10, 5);

Methods defined without ‘static’ keyword are called instance methods.


Instance methods must be called by defining the object to a class. In the
above example, sum, sub, mul, div, printEvenNumbers are the instance
methods.

Following statement defines the objects to the class Program.


Program obj = new 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();

int result1 = Program.sum( 10 , 5 );


int result2 = Program.sub( 10 , 5 );
int result3 = Program.mul( 10 , 5 );
int result4 = Program.div( 10 , 5 );

Console.WriteLine("Sum of 10 and 5 is {0}", result1);


Console.WriteLine("Subtraction of 10 and 5 is {0}", result2);
Console.WriteLine("Multiplication of 10 and 5 is {0}", result3);
Console.WriteLine("Division of 10 and 5 is {0}", result4);

Program.printEvenNumbers();
}

static int sum ( int a, int b)


{
return a + b;
}
static int sub ( int a, int b)
{
return a - b;
}

static int mul ( int a, int b)


{
return a * b;
}

static int div ( int a, int b)


{
return a/ b;
}

static 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
C++
CODING PRACTICE
EXERCISES

CODING FOR BEGINNERS


JJ TAM
C++ CODING EXERCISES
C++ Exercises: Find the first 10
natural numbers
C++ CODE
#include <iostream>
using namespace std;
int main()
{
int i;
cout << "\n\n Find the first 10 natural numbers:\n";
cout << "---------------------------------------\n";
cout << " The natural numbers are: \n";
for (i = 1; i <= 10; i++)
{
cout << i << " ";
}
cout << endl;
}
OUTPUT
Find the sum of first 10 natural
numbers
C++ CODE
#include <iostream>
using namespace std;
int main()
{
int i,sum=0;
cout << "\n\n Find the first 10 natural numbers:\n";
cout << "---------------------------------------\n";
cout << " The natural numbers are: \n";
for (i = 1; i <= 10; i++)
{
cout << i << " ";
sum=sum+i;
}
cout << "\n The sum of first 10 natural numbers: "<<sum << endl;
}
OUTPUT
Display n terms of natural number
and their sum
C++ CODE
#include <iostream>
using namespace std;
int main()
{
int n,i,sum=0;
cout << "\n\n Display n terms of natural number and their sum:\n";
cout << "---------------------------------------\n";
cout << " Input a number of terms: ";
cin>> n;
cout << " The natural numbers upto "<<n<<"th terms are: \n";
for (i = 1; i <= n; i++)
{
cout << i << " ";
sum=sum+i;
}
cout << "\n The sum of the natural numbers is: "<<sum << endl;
}
OUTPUT
Find the perfect numbers between
1 and 500

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;

#define size 10000

int fact(int x, int ar[], int ar_size);

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;
}

int fact(int x, int ar[], int ar_size)


{
int c = 0;
for (int i=0; i< ar_size; i++)
{ int p = ar[i] * x + c;
ar[i] = p % 10;
c = p/10;
}

while (c)
{
ar[ar_size] = c%10;
c = c/10;
ar_size++;
}
return ar_size;
}
int main()
{

int n;

cout<<"Enter an integer number: ";


cin>>n;

cout<<"Factorial of "<<n<<" is:"<<endl;


factorial(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);
};

//member function definition, outside of the class


void student::getDetails(void){
cout << "Enter name: " ;
cin >> name;
cout << "Enter roll number: ";
cin >> rollNo;
cout << "Enter total marks outof 500: ";
cin >> total;
perc=(float)total/500*100;
}

//member function definition, outside of the class


void student::putDetails(void){
cout << "Student details:\n";
cout << "Name:"<< name << ",Roll Number:" << rollNo << ",Total:" <<
total << ",Percentage:" << perc;
}

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;

cout << "EVEN numbers are...\n";


evenNumbers(N);

cout << "ODD numbers are...\n";


oddNumbers(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 << "Enter a number: ";


cin >> num;
cout << "\n";

cout << "Enter a power : ";


cin >> pw;
cout << "\n";

for (int i = 1; i <= pw; i++) {


a = a * num;
}

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>

using namespace std;

int roman_to_int(string roman){

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 input is only one character

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;

cout<<"Enter the roman number (in capital only): ";

getline(cin,roman);

int number;

number=roman_to_int(roman);

cout<<"The interger form is: "<<number;

return 0;

OUTPUT
Check if a number is power of 2 or
not in C++
PROGRAM
#include <iostream>

using namespace std;


int main()
{
int n;
cout<<"Enter the number :";
cin>>n;

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 << "Enter a number: ";


cin >> num;
cout << "\n";

cout << "Enter a power : ";


cin >> pw;
cout << "\n";

for (int i = 1; i <= pw; i++) {


a = a * num;
}

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;

for (int i = 1; i <= num1 && i <= num2; i++)


{
if (num1 % i == 0 && num2 % i == 0)
{
gcd = i;
}
}
cout << " The Greatest Common Divisor is: " << gcd << endl;
return 0;
}
OUTPUT
OUR OTHER PUBLISHING
TAM SEL
APACHE SPARK AND SCALA FOR BEGINNERS: 2 BOOKS
IN 1 - Learn Coding Fast!

PYTHON AND JAVASCRIPT CODING BASICS: FOR


ABSOLUTE BEGINNERS

LARAVEL FOR BEGINNERS: Learn Coding Fast

HTML FOR BEGINNERS: Html CSS Programming Language


Crash Course, Web Design Quick Start Script Tutorial Book in
Easy Steps

DART PROGRAMMING BASICS: FOR ABSOLUTE


BEGINNERS

RUST AND GOLANG FOR BEGINNERS: 2 BOOKS IN 1 -


Learn Coding Fast! RUST AND GOLANG

APACHE SPARK AND HADOOP FOR BEGINNERS: 2


BOOKS IN 1 - Learn Coding Fast!

TENSORFLOW FOR BEGINNERS: LEARN CODING FAST


DJANGO AND PYTHON FOR BEGINNERS: 2 BOOKS IN 1
- Learn Coding Fast!

JAVASCRIPT AND DART CODING BASICS: FOR


ABSOLUTE BEGINNER

TENSORFLOW FOR BEGINNERS AND PYTHON CODING


BASICS: FOR ABSOLUTE BEGINNERS

RUST Programming Language: For Beginners, Learn Coding


Fast!

HADOOP AND PYTHON FOR BEGINNERS: 2 BOOKS IN 1


- Learn Coding Fast!

SELENIUM AND JAVA FOR BEGINNERS: 2 BOOKS IN 1 -


Learn Coding Fast!

ANDROID AND JAVA FOR BEGINNERS: 2 BOOKS IN 1 -


Learn Coding Fast!
J KING
PYTHON AND HADOOP BASICS

PYTHON BASICS AND PYTHON CODING EXAMPLES

C# AND C++ CODING EXAMPLES

PYTHON CODING AND C PROGRAMMING EXAMPLES

C++ AND JAVA CODING EXAMPLES

ANDROID BASICS AND PYTHON CODING EXAMPLES

C# BASICS AND PYTHON CODING EXAMPLES

ANGULAR AND PYTHON BASICS

PYTHON BASICS AND SCALA CODING EXAMPLES

JAVA BASICS AND PYTHON CODING EXAMPLES

PYTHON BASICS AND C# CODING EXAMPLES


ANDROID BASICS AND JAVA CODING EXAMPLES

C# BASICS AND C# CODING EXAMPLES

JAVASCRIPT AND HTML BASICS

HTML AND JAVASCRIPT CODING EXAMPLES

You might also like