Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

Programming fundamentals

Programming fundamental importants topics

Uploaded by

asianspublic2006
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Programming fundamentals

Programming fundamental importants topics

Uploaded by

asianspublic2006
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Conditional structure in c++

Decision Making in C (if , if..else, Nested if, if-else-if )

• The conditional statements (also known as decision control structures) such as if, if else,
switch, etc. are used for decision-making purposes in C programs.

• They are also known as Decision-Making Statements and are used to evaluate one or more
conditions and make the decision whether to execute a set of statements or not

• These decision-making statements in programming languages decide the direction of the


flow of program execution

Need of Conditional Statement

• They're come situations in real life when we need to make some decisions and based on
these decisions, we decide what should we do next.

• Similar situations arise in programming also where we need to make some decisions and
based on these decisions we will execute the next block of code.

• For example

• In C if x occurs then execute y else execute z. There can also be multiple conditions like in C
if x occurs then execute p, else if condition y occurs execute q, else execute r. This condition
of C else-if is one of the many ways of importing multiple conditions.

Types of Conditional Statements in C++

if in C++
• The if statement is the simplest decision-making statement. It is used to decide whether a
certain statement or block of statements will be executed or not i.e if a certain condition is
true then a block of statements is executed otherwise not.
Syntax of if Statement

If (condition)

Statements to be executed if condition is true

Explanation

Here, the condition after evaluation will be either true or false. C if statement accepts boolean values
– if the value is true then it will execute the block of statements below it otherwise not. If we do not
provide the curly braces ‘{‘ and ‘}’ after if(condition) then by default if statement will consider the first
immediately below statement to be inside its block.

Example

// C program to illustrate If statement

#include <stdio.h>

int main()

int i = 10;

if (i > 15) {

printf("10 is greater than 15");

printf("I am Not in if");

if-else in C
• The if statement alone tells us that if a condition is true it will execute a block of statements
and if the condition is false it won’t. But what if we want to do something else when the
condition is false

• Here comes the C else statement. We can use the else statement with the if statement to
execute a block of code when the condition is false. The if-else statement consists of two
blocks, one for false expression and one for true expression.

Syntax of if else in C

If (condition)

{
Statements to be executed if condition is true

Else

Block to be executed if condition is false

Examples

Implement a program to determine whether a number is positive, negative, or zero using


an if-else statement.

#include <iostream>

using namespace std;

int main()

int num = 96;

//Conditions to check if the number is negative or positive

if (num > 0)

cout << "The number is positive";

else if (num < 0)

cout << "The number is negative";

else

cout << "Zero";

return 0;

Nested if-else in C
• A nested if in C is an if statement that is the target of another if statement. Nested if
statements mean an if statement inside another if statement. Yes, C allow us to nested if
statements within if statements, i.e, we can place an if statement inside another if
statement

Syntax of Nested if else


if (condition1)
{
// Executes when condition1 is true
if (condition_2)
{
// statement 1
}
else
{
// Statement 2
}
}
else {
if (condition_3)
{
// statement 3
}
else
{
// Statement 4
}
}

switch Statement in C
• The switch case statement is an alternative to the if else if ladder that can be used to
execute the conditional code based on the value of the variable specified in the switch
statement. The switch block consists of cases to be executed based on the value of the
switch variable

Syntax of switch

switch (expression) {
case value1:
statements;
case value2:
statements;
....
....
....
default:
statements;
}
Implement a program to determine whether a number is positive, negative, or zero using
an if-else statement.

#include <iostream>

using namespace std;

int main()

int num = 96;

//Conditions to check if the number is negative or positive

if (num > 0)

cout << "The number is positive";

else if (num < 0)

cout << "The number is negative";

else

cout << "Zero";

return 0;

Loops in programming
C++ Loops

• In Programming, sometimes there is a need to perform some operation more than once or
(say) n number of times.

• Loops come into use when we need to repeatedly execute a block of statements.

• For example: Suppose we want to print “Hello World” 10 times. This can be done in two
ways as shown below:

1. Manual Method (Iterative Method)

Manually we have to write cout for the C++ statement 10 times. Let’s say you have to write it 20
times (it would surely take more time to write 20 statements) now imagine you have to write it 100
times, it would be really hectic to re-write the same statement again and again. So, here loops have
their role.

2. // C++ program to Demonstrate the need of loops


#include <iostream>

using namespace std;

int main()

cout << "Hello World\n";

cout << "Hello World\n";

cout << "Hello World\n";

cout << "Hello World\n";

cout << "Hello World\n";

return 0;

Solution Using Loops

• In Loop, the statement needs to be written only once and the loop will be executed 10 times
as shown below.

• In computer programming, a loop is a sequence of instructions that is repeated until a


certain condition is reached.

• The C++ Course includes comprehensive lessons on the different types of loops available
in C++, ensuring you can implement them effectively in your programs

There are mainly two types of loops:

1. Entry Controlled loops: In this type of loop, the test condition is tested before entering the
loop body. For Loop and While Loop is entry-controlled loops.

2. Exit Controlled Loops: In this type of loop the test condition is tested or evaluated at the
end of the loop body. Therefore, the loop body will execute at least once, irrespective of
whether the test condition is true or false. the do-while loop is exit controlled loop.

Loop Type and Description

• while loop– First checks the condition, then executes the body.

• for loop– firstly initializes, then, condition check, execute body, update.

• do-while loop– firstly, execute the body then condition check


For Loop
• A For loop is a repetition control structure that allows us to write a loop that is executed a
specific number of times. The loop enables us to perform n number of steps together in one
line.

Syntax of for loop

for(initialization; condition; incr/decr)

//code to be executed

C++ for loop is same as C/C#. We can initialize variable, check condition and
increment/decrement value

Develop a program to display the first 10 multiples of any user-provided number using a for
loop

#include <iostream>

using namespace std;

int main() {

int num;

// Ask the user for a number

cout << "Enter a number: ";

cin >> num;

// Loop to display the first 10 multiples

cout << "The first 10 multiples of " << num << " are:" << endl;

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

cout << num * i << " ";

cout << endl;

return 0;

C++ While loop


• The while loop loops through a block of code as long as a specified condition is true
syntax

while (condition)

{
// code block to be executed
}

Example

In the example below the code in the loop will run , over and over again, as long as a variable (i)
is lexx thsan 5

int i = 0;
while (i < 5) {
cout << i << "\n";
i++;
}

C++ Do-While Loop


• The do /while loop is a variant of the while loop. This loop will execute the code block once,
before checking if the condition is true, then it will repeat the loop as long as the condition is
true

syntax

• do {
// code block to be executed
}
while (condition)

Const member functions in C++


Constant member functions are those functions that are denied permission to change the values of
the data members of their class. To make a member function constant, the keyword const is
appended to the function prototype and also to the function definition header.Like member functions
and member function arguments, the objects of a class can also be declared as const. An object
declared as const cannot be modified and hence, can invoke only const member functions as these
functions ensure not to modify the object. A const object can be created by prefixing the const
keyword to the object declaration. Any attempt to change the data member of const objects results
in a compile-time error.

Syntax

The const member function can be defined in three ways:

1. For function declaration within a class.

return_type function_name() const;


2. For function definition within the class declaration.

return_type function_name () const


{
//function body
}

3. For function definition outside the class.

return_type class_name::function_name() const


{
//function body
}

Example

Create a program where a const function protects class members from unintended changes

#include <iostream>

class Rectangle {

private:

int length;

int width;

public:

// Constructor to initialize length and width

Rectangle(int l, int w) : length(l), width(w) {}

// Const function to get the length

int getLength() const

return length;

// Const function to get the width

int getWidth() const

return width;

// Non-const function to set new dimensions


void setDimensions(int l, int w) {

length = l;

width = w;

// Const function to calculate and return the area

int getArea() const {

return length * width;

};

int main() {

Rectangle rect(4, 5); // Create a rectangle with length 4 and width 5

// Access dimensions and area using const functions

std::cout << "Length: " << rect.getLength() << ", Width: " << rect.getWidth() << std::endl;

std::cout << "Area: " << rect.getArea() << std::endl;

// Modify dimensions using a non-const function

rect.setDimensions(6, 8);

// Display updated dimensions and area

std::cout << "Updated Length: " << rect.getLength() << ", Updated Width: " << rect.getWidth() <<
std::endl;

std::cout << "Updated Area: " << rect.getArea() << std::endl;

return 0;

Explanation
1. Private Members:

• length and width store the rectangle's dimensions and are not accessible directly from
outside the class.

2. Const Functions:

• getLength(), getWidth(), and getArea() are const functions. They provide read-only access to
the class members without modifying them.

3. Non-Const Function:
• setDimensions(int l, int w) allows controlled updates to the rectangle's dimensions.

4. Main Function:

• A Rectangle object is created with an initial length and width.


• The dimensions and area are displayed using the const functions.
• The dimensions are updated using setDimensions(), and the new values are verified.

C++ Static Data Members


Static data members are class members that are declared using static keywords. A static member
has certain special characteristics which are as follows:

• Only one copy of that member is created for the entire class and is shared by all the objects
of that class, no matter how many objects are created.

• It is initialized before any object of this class is created, even before the main starts outside
the class itself.

• It is visible and can be controlled with the class access specifiers.

• Its lifetime is the entire program.

Syntax

className {
static data_type data_member_name;
....
}

Show function overloading by writing a program to add two integers and two floats.

#include <iostream>

// Function to add two integers

int add(int a, int b)

return a + b;

// Function to add two floats

float add(float a, float b) {

return a + b;

int main() {
// Add two integers

int intResult = add(5, 10);

std::cout << "Sum of integers: " << intResult << std::endl;

// Add two floats

float floatResult = add(2.5f, 3.7f);

std::cout << "Sum of floats: " << floatResult << std::endl;

return 0;

Write a program using templates to calculate the average of two numbers

#include <iostream>

using namespace std;

template <class T, class U>

T sum(T a, U b) {

return (a+b);

int main() {

cout<<"sum :-"<<sum(5,3)<<endl;

cout<<"ave :-"<<sum(5,3)/2<<endl;

Inheritance in C++
Inheritance is a fundamental concept in Object-Oriented Programming (OOP) that allows a class
(called the derived class) to acquire properties and methods from another class (called the base
class). It promotes code reuse and hierarchical classification.

Types of Inheritance in C++

1. Single Inheritance:

A derived class inherits from only one base class.

class Base {

public:

void display() {
cout << "Base class display method" << endl;

};

class Derived : public Base {

};

Multiple Inheritance:

A derived class inherits from more than one base class.

class Base1 {

public:

void display1() {

cout << "Base1 class method" << endl;

};

class Base2 {

public:

void display2() {

cout << "Base2 class method" << endl;

};

class Derived : public Base1, public Base2 {

};

Multilevel Inheritance:

A derived class inherits from another derived class.

class Base {

public:

void display() {
cout << "Base class method" << endl;

};

class Derived1 : public Base {

};

class Derived2 : public Derived1 {

};

Hierarchical Inheritance:

Multiple classes inherit from the same base class.

class Base {

public:

void display() {

cout << "Base class method" << endl;

};

class Derived1 : public Base {

};

class Derived2 : public Base {

};

Hybrid Inheritance:

Combines two or more types of inheritance, often leading to a diamond problem (resolved using
virtual inheritance).

class Base {

public:

void display() {
cout << "Base class method" << endl;

};

class Derived1 : public virtual Base {

};

class Derived2 : public virtual Base {

};

class FinalDerived : public Derived1, public Derived2 {

};

Syntax of Inheritance

class Base {

// Base class members

};

class Derived : access_specifier Base {

// Derived class members

};

Access Specifiers in Inheritance

Public Inheritance:

Public members of the base class become public in the derived class.

Protected members of the base class remain protected.

class Derived : public Base {};

Protected Inheritance:

Public and protected members of the base class become protected in the derived class.

Private Inheritance:

Public and protected members of the base class become private in the derived class.
class Derived : private Base {};

You might also like