0% found this document useful (0 votes)
11 views

C & C++ lecture by Earul sir

The document provides an overview of programming basics, including the definition of programming, basic operations a computer can perform, and the necessity of understanding computer languages. It categorizes programming languages into low-level, mid-level, and high-level languages, and discusses algorithms and flowcharts as tools for program design. Additionally, it covers the structure of C programming, the role of compilers and interpreters, C tokens, data types, and operators.

Uploaded by

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

C & C++ lecture by Earul sir

The document provides an overview of programming basics, including the definition of programming, basic operations a computer can perform, and the necessity of understanding computer languages. It categorizes programming languages into low-level, mid-level, and high-level languages, and discusses algorithms and flowcharts as tools for program design. Additionally, it covers the structure of C programming, the role of compilers and interpreters, C tokens, data types, and operators.

Uploaded by

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

Programming basics

Programming:
 Telling the computer what to do

Basic operation a computer can perform (instructed by program):

 Input: get data from keyboard, file or some other devices


 Output: write
 Math: perform some calculations like addition, multiplication
 Conditional execution: check some condition and execute on sequence of
instructions or other
 Repetition: repeat some sequence of operation if instructed by program.

=> Necessary to know computer language


1
Types of computer language(1)
Based on interpretation:
Computer languages

Low level language Mid level language High level language

Low level language:


• Either machine codes or are very close them
• Corresponds directly to a specific machine
• Direct memory management
• Register access
• Statements usually have an obvious correspondence with clock cycles
• Two types:
• Machine language
• Assembly language 2
Types of computer language (2)
Mid level language:
• Serves as the bridge between the raw hardware and programming layer of a
computer system.
• High level abstractions such as objects or functions
• Static typing
• Extremely commonplace (mid-level languages are by far the most widely used)
• Virtual machines
• Garbage collection
• Easy to understand the program flow
Example:
 C
 FORTH
 Macro-assembly language

3
Types of computer language(3)
High level language:
• Human understandable
• Interpreted
• Dynamic constructs (open classes, message-style methods, etc)
• Concise code
• Flexible syntax
Example:
 Ada
 Modula-2
 Pascal
 COBOL
 FORTRAN
 BASIC
 JAVA
 Python etc.

=> Necessary to develop program


4
Algorithm and flowchart
Algorithm and flowchart are tools to explain the process of a program
Algorithm:
• Writes a logical step-by-step method to solve the problem
• Includes calculations, reasoning and data processing
• Can be presented by natural languages, pseudo code and flowcharts
Flowchart:
• Graphical or pictorial representation of an algorithm
• Several standard graphics are applied in a flowchart
 Start or End
 Input/ Output
 Process
 Decision
 Connector

5
Use Flowcharts to Represent Algorithms
Start
An example to Print 0 to 20:
Algorithm:
• Step 1: Initialize X as 0, Set X=0

• Step 2: Increment X by 1,
• Step 3: Print X, Print X

• Step 4: If X is less than 20 then go back to step 2.


Increase X by 1

Yes
X<=20

No
End

=>Here, we will focus only on C language to write code


6
Overview of C programming language
Designed by Dennis Ritchie at Bell Laboratories in the early 1970s
Influenced by:
 ALGOL 60 (1960),
 CPL (Cambridge, 1963),
 BCPL (Martin Richard, 1967),
 B (Ken Thompson, 1970)
Traditionally used for systems programming
• Case sensitive
• C-development environment includes
 System libraries and headers
 Application Source
 Compiler
 Linker

7
Structure of C program

User program structure Example: Add two numbers:


 The program must have a “header file” #include<stdio.h>
 When the program runs the execution void main()
begins {
at the “main” function int i, j, k;
Header file: printf("Enter the numbers: ");
 Specified in include section scanf("%d %d",&i, &j);
 Precompiled files some functions defined k=i+j;
in them
printf("The sum is %d",k);
 An extension.h
getch();
main function: }
 The function where the program starts
execution
 Outlines what the program does => To run this program requires
compiling
8
Compiler and Interpreter
A compiler and interpreter both are computer translator software
 Compiler:
 Reads the entire program at a time and converts it into source code
=> After scanning entire program, it generates an error message (if any)
 Object code further requires linking, hence more memory is required
 Overall execution time is faster but takes much time to analyze the source code.
 Languages like C, C++ use it

 Interpreter:
 Translates one statement of the program at a time.
 No intermediate object code is generated, hence are memory efficient
 Each time it finds an error, it stops immediately giving an error message, hence
debugging is easy
=> Takes less time to analyze the source code but overall execution time is slower
 Languages like Python, Rubi use it
9
C token
C token is basic element of source-program text just like letters of a
language: The compiler does not break it down into component elements

Type of C Token (Six types):

1. Keyword

2. Identifier

3. Constant

4. String-literal

5. Operator

6. Punctuator

10
C Token(1)
1. Keyword: Words that have special meaning to C compiler

 Predefined and reserved words


 Always are of lowercase in C
 Can not be redefined and part of the syntax
 C has 32 keywords (ANSI standard)
 Turbo C has 11 extended keywords

Keywords name:
auto break case char const continue default do
double else enum extern float for goto if
int long register return short signed sizeof static
struct switch typedef union unsigned void volatile while

11
C Token(2)
2. Identifier
Names that are used to reference:
 Variables
 Functions
 Labels
 User-defined objects

Rules to be an identifier:

 Can be 1 to 32 characters long


 First character must be letter (A-Z or a-z) or underscore( _ )
 Subsequent characters can be either letter, number or underscore
 Case sensitive, i.e. “Earth” and “earth” are not same.
 Can not be any keyword
 Shouldn‟t have the same name as library or user defined functions
 Example: exam, _balance, room21 etc.
12
Variable
Local variables:
• Are declared inside a function
• Can be referenced only by statements that are inside the block in which the
variable is declared
• Are not known outside it‟s own block
• Two different blocks can have variable of same name and assigning one a
value will not alter the other.
• Is created upon entry into its block and destroy upon exit

Global variables are:


• Declared outside the main() function
• Available at all times from anywhere
• Created at the start of the program, and lasts until the end
• It takes up memory during the entire program
• Difficult to debug
• Use of less number of global variable is suggested unless unknown error
can occur

13
Local and global variable example
#include<stdio.h>
int a; //Global variable declaration
int main()
{
{
int b=10, sum;
a=20;
sum=a+b; b is unknown outside
printf("Sum = %d\n",sum); this block a is known to the
} entire program
{
int c=8, multpl;
a++;
c is unknown
multpl=a*c; outside this block
printf("Multiple = %d",multpl);
}
return 0 ;
} 14
Data types
Five basic data types:

Integer : int a = 2; int a = 2.5; count only 2


Float : float a = 0.5; float a = „C‟;
Double : double a = 5.5; double a = „A‟;
Character : char a = „Z‟; char a = 7;
Void : valueless

Type Format specifier Memory (bytes) Range


int %d 2 -32768 to 32767
float %f 4 3.4E-38 to 3.4E+38
double %lf 8 1.7E-308 to 1.7E+308
char %c 1 0 to 255
void %p 0 valueless

=> Important to decide coding


15
Test on data type

1. Which of the following statements will execute?


1. char a = 2; 6. int num = 327689;
2. int x = 2.5; 7. char stat = „1‟;
3. int raw = 64; 8. float numb = ‟46.046‟;
4. void new = 12;; 9. int n = 4/2;
5. char nam = „Joker‟;10. char d = „n‟;

2. Execution of which of the following code segments will loose no data?


1. int x = 10/3;
2. double d = 12;
• int x = d;
3. float n = 10/3;
4. int num = 10/2;

16
Test data Answer
Exceeds the
integer range
Which of the following statements will execute?
2 is an
1. char a = 2; 6. int num = 327689; „ ‟ should be
integer
2. int x = 2.5; ;7. char stat = „1‟; absent
Takes only 1 3. int raw = 64; 8. float numb = ‟46.046‟;
character void is
4. void new = 12; 9. int n = 4/2;
5. char nam = „Joker‟;10. char d = „n‟; valueless

Execution of which of the following code segments will loose no data?


1. int x = 10/3;
2. double d = 12; Double
int x = d; contains only
3. float n = 10/3; integer part
4. int num = 10/2;
Fraction part
loss
17
Backslash character constants
Backslash codes and their meaning:

Code Meaning Code Meaning

\b Backspace \’ Single quote

\f From feed \0 Null

\n New line \\ Backslash

\r Carriage return \v Vertical tab

\t Tab \o Audible alert

\” Double quote \x Hex constant

18
C token (3)

3. Constants Examples
Integer constant 1, 3, 038
Real constant -3.0, 0.67, -7.98
Character constant „A','B‟,'C','Z‟
Backslash character constant \n, \b, \\
String constant “ABCD”, “Hello Audience”

4. String-literal :
Sequence of characters enclosed in double quotation marks (“ ”).
• Forms a null-terminated string
• Can contain spaces between characters
• Example:
• char *msg = “I love C programming”;
• char inp[ ] = “Bangladesh”;
19
C Token (4)

5. Operators:
• Arithmetic operators (+, -, *, /, %)

• Increment and Decrement operator (++, --)

• Assignment operator (=, +=, -=, *=, /=, %=)


• Relational operator (==, !=, <, >, <=, >=)

• Logical operator (&&, | |, !)


• Conditional operator/Ternary operator (? :)

• Bitwise operator (&, |, <<, >>, ^, ~)

• Comma operator ( , )

• sizeof operator
20
5. Operators
Operator Meaning Operator Meaning Operator Meaning
+ Addition/ unary *= Multiplication || Logical Or
plus
- Subtraction/ /= Division ! Logical Not
unary minus
* Multiplication %= Modulo division ?: Condition
/ Division != Not equal ~ Bitwise
Complemen
t
% Modulo == Equal to ^ Bitwise Ex-
Division OR
++ Increment > Greater than & Bitwise And
-- Decrement < Less than | Bitwise Or
= Assignment >= Greater than / equal << Bitwise Left
Shift
+= Increment <= Less than / equal >> Bitwise
21
Operators with = (assignment sign)

taka = 4 taka == 4

Sets taka variable to the Tests if taka variable has


value of 4 the value 4

taka += 4 taka -= 4

Increases taka by 4 each decreases taka by 4 each


time the line is executed time the line is executed
22
Operator Precedence
Precedenc Operator Description Associativity
e
1 () [] Parentheses Left-to-right
-> . Member Selection (via pointer,
++ -- object)
Postfix increment and decrement
2 ++ -- Prefix increment and decrement Right-to-left
(type) Type cast
* & Pointer, Address of
sizeof
+ - ~ !
3 * / % Left-to-right
4 + - Left-to-right
5 << >> Left-to-right
6 < <= > >= Left-to-right

23
Operator Precedence

Precedence Operator Description Associativity


8 &
9 ^
Left to-right
10 |
11 && and
12 || or
13 ?: Right-to-left
14 = Simple Assignment Right to left
+= -= Assignment by sum and difference
*= /= %= Assignment by product, quotient,
reminder

15 , comma Left to-right

24
Operator Precedence test
Which function will be called first? f( ) or g( )?
 int i = (f( ) + g( )) || g( );
 int j = g( ) || (f( ) + g( ));

What value will be stored in a? 1, 2, -2, 10?

 int a = 5 * 3 % 6 - 8 + 3;

What will be the value of a? 1 or 0?

 int a = (1 > 2 + 3 && 4);

25
C Token (5)
Punctuators Use Example
<> Header file #include<stdio.h>
[] Array delimiter int a[10];
{} Initializes list, function body or
char a[2] = {„H‟, ‟i‟ } ;
compound statement
() Function parameter list delimiter; int fun(x, y)
used in expression grouping
* Pointer declaration char *p;
, Argument list separator char x(a, b)
: Statement label labela: if (x==9) x+=1;
= Declaration initializer float f=3.654;
; Statement end int a;
… Variable- length argument list int f ( int y, ...)
# Preprocessor directive #include<stdlib.h>
„„ Character constant char a= „h‟;
“” String literal char a[ ]= “hello”;
26
Components of a C program

Functions:
 These are building blocks of C. All C program must contain one or more functions
(at least the main() function)
 C has a set of library functions which can be called directly by including its header
file to the program
Statements:
 A function contains statements. A statement specifies an action to be performed by
the program
 All C statements end with a semicolon
Example of a short C program:
#include<stdio.h>
void main()
main() function
{ Header file
Library function printf(“I love C programming”); Statements
} 27
Create first program
Problem: Write a program to assign a value to a variable and then print
the value.
#include<stdio.h>
void main() Format specifier for
{ integer
int a;
a=10;
printf(“The value of the variable is %d”, a); Format specifiers:
%c for character type
}
%f for float type
%lf for double type
%s for string type

Output: The value of the variable is 10

http://www.codeblocks.org/home
28
Taking data from keyboard
Problem: Write a program that takes a value from keyboard and then
print the value.
#include<stdio.h>

void main()
{ address at operator
scanf() function allows
int a;
data from keyboard
scanf(“%d”, &a);
printf(“The value of the variable is %d”, a);
}

=> The input given by keyboard is the output

29
Home task

1. Write a program to assign a value to a character type variable and


then print the value.
2. Write a program that takes a float type value from keyboard and then
print the value.
3. Write a program to assign a value to a double type variable and then
print the value.
4. Write a program that takes a string type value from keyboard and
then print the value.

30
Performing Calculation
Write a program to make a simple calculator that can perform addition, subtraction,
multiplication and division of two number.
#include<stdio.h>
#include<conio.h> // holds clrscr() and getch()//
void main()
{
clrscr(); //clean entire previous screen//
int a, b, sum, subtr, mult;
float div;
printf(“Enter the value of a and b: \n”);
scanf(“%d %d”, &a, &b);
sum = a+b;
subtr = a-b;
mult = a*b;
div = a/b;
printf(“The value of sum is %d\n”, sum);
printf(“The value of subtraction is %d\n”, subtr);
printf(“The value of multiplication is %d\n”, mult);
printf(“The value of division is %d\n”, div);
getch(); // holds screen until pressing any key//
}

31
Task

1. Write a program to calculate the area of a rectangle.


2. Write a program to calculate the volume of a cube.

32
Become familiar with if
if statement:
this is C‟s selection or conditional statement
It allows a program to conditionally execute a statement
General form:
if(expression)
statement;
if the expression evaluates as true the statement will be executed, bypassed otherwise.

Example :
int a=23, b=27, c=56;
if(a<b && a<c)
printf(“%d is the lowest number”, a);

33
Program using if else statement

Write a program that read an integer from the keyboard and tells whether
it is even or odd.

#include<stdio.h>
void main()
{
int a;
printf("Enter an integer:\n");
scanf("%d", &a);
if(a%2==0)
printf("%d is even number",a);
else
printf("%d is odd number",a);
}
34
If else if ladder

Sometimes there can be more than 2 conditions. In those cases if-else-if


ladder is used.

Structure:
If(condition)
statement;
else if (condition)
statement;
……….
else
statement;

35
Loops

Loops

Entry controlled Exit controlled

1. for loop 1. do-while loop


2. while loop

36
for loop
Repeats statement or block of statement for a specific number of times
General form:
for(initialization; condition-test; increment)
statement;
• initialization section gives an initial value to the variable that controls
the loop
• initialization section is executed only once before the loop begins
• condition-test portion of the loop tests the loop-control variable value
against the target value.
• If the condition-test evaluates true the loop repeats. If false the loop
stops.
• increment portion increases the value of loop control variable to a
certain amount.
37
Program using for loop
Write a program that prints the even numbers up to 100.

#include<stdio.h>
#include<conio.h>
void main()
{
int i;
printf("List of even numbers up to hundred:\n");
for(i=2;i<=100;i+=2)
printf("%d ",i);
}

38
Tasks

1. Write a program that read a positive integer and display its factorial

2. Write a program that print all Fibonacci numbers from 1 to n. n must

be chosen by the user. (Fibonacci series: 1, 1, 2, 3, 5, 8, 13, 21… …)

3. 1+2+3+4+…………………….upto nth term.

4. 2+4+6+8+…………………………upto nth term

5. 1.2+2.3+3.4+………………………upto nth term.

39
Nested for loop
Nested for loops are generally used to create various types of pyramids
Program using nested for loop.
Write a C program that output the pyramid

#include<stdio.h>
void main()

{
int i,j;
for ( i=1;i<=4; i++)
{
for ( j=1;j<=i; j++)
printf("%d ",(i+j-1)%2);
printf("\n"); OUTPUT
}
1
0 1
}
1 0 1
0 1 0 1
40
Task
Write C programs to create the following pyramid:

c. 1
a. 1 b. 1 2 2
2 2 2 2 3 3 3
3 3 3 3 3 3 4 4 4 4
2 2
3 3 3
3
2 2
1
a. 1
2 2
3 3 3

41
Take 10 numbers and calculate sum and average

#include <stdio.h>

void main()
{
float num, sum = 0.0, average;

printf("Please Enter the 10 Numbers\n");


for(int i = 1; i <= 10; i++)
{
printf("Number %d = ", i); Do for n numbers input?
scanf("%d", &num);
sum = sum + num;
}

avg = sum / 10;

printf("\nThe Sum of 10 Numbers = %f", sum);


printf("\nThe Average of 10 Numbers = %.2f\n", avg);
}

42
Array
An array is a collection of variables of same data type that are
referenced by a common name.
• Consists of contiguous memory location
• The lowest address corresponds to first element
• The highest address corresponds to last element
• May have one or several dimension

One dimensional array declaration:


type var_name[size]; size defines number of elements
To assign something to the first element of an array the index must be 0.
For example:
int myArray[20];
myArray[0]=100; 43
Take n numbers from keyboard
void main()
{
int i, size;
printf("Enter the value of arr size ");
scanf("%d",&size);
int array [size];
for(i=0;i<size; i++)
{
printf("Enter array value\t");
scanf("%d",&arr[i]);
}
for(i=0;i<size; i++)
{
printf("Value of array is %d \n",arr[i]);
}
}
44
Sorting an array of data descending order
#include<stdio.h>
void main ()

{
int i, j,temp;
int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
for(i = 0; i<10; i++)
{
for(j = i+1; j<10; j++)
{
if(a[j] > a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("Printing Sorted Element List ...\n");
for(i = 0; i<10; i++)
{
printf("%d\n",a[i]);
}
} 45
Program using array

• Write a C program that prints the squares from 1 to 10.


#include<stdio.h>
void main()
{
int i, sqrs[10];
for(i=0;i<10;i++)
sqrs[i]=(i+1)*(i+1);
for(i=0;i<10;i++)
printf("%d^2 = %d\n",i+1,sqrs[i]);
}

46
Q2

What will be the output of the following program? Explain the reason clearly.

#include<stdio.h>
void main()
{
int i = 5;
int a = ++i + i++;
printf("%d",a);
}

47
User define function
A user-defined function in C is any function that you (the programmer) create yourself,
rather than those provided by the language or standard libraries (like printf, scanf, etc.).

It generally has the following characteristics:


1.Name – Choose a meaningful function name (for example, add).
2.Return Type – (e.g., int, float, void, etc.).
3. Function Body – Contains the actual implementation

#include<stdio.h>
int add(int a, int b) //>> Function prototype
{
return a + b;
}
int main()
{
int result = add(3, 4); // >>Function call
printf("Result = %d\n", result);
return 0;
}

48
Advantages of user-defined function inside main()

Organization:
>>Breaking the program into multiple functions allows you to separate logic
into distinct blocks.
>>Each function handles a specific task, making your code more organized.

Reusability:
>> If you have a piece of logic you need to run multiple times, you can write
it once as a function and call it as many times as you want from main() or
elsewhere

Testability:
>>Each function can be tested independently. >>If there is a bug, it is
usually isolated within a single function.

Scalability:
>>It is easier to add new features or modify existing ones.

49
Pointer
Pointer is a variable that holds the memory address of another variable
C contains 2 special pointer operator, & and *.
• & - (ampersand) operator is used to obtain the address of a variable
• * - returns the value stored at the address that it precedes.

Declaration: int *p;

int x = 10;
int *p = &x; >>p now holds the address of x

printf("%d\n", *p);
Pointer gives access to the value at the
address stored in the pointer.
>> Prints the value of x, i.e., 10

50
How is pointer used in C?
Passing Arguments by Reference to Functions:

>>You can pass pointers to functions to allow the function to modify


the original variable, rather than working on a copy of the value.

void increment(int *value)


{
(*value)++;
}
int main() • When you call increment(&num), you
are passing the address of num to the
{ function.
int num = 5; • Inside the increment function, the
increment(&num); // num is now 6 parameter value is a pointer that points
to num‟s memory location.
return 0;
} >>Therefore, (*value)++ increments the
actual value stored at that address by 1.
Since num was 5, it becomes 6 in main
after the function returns.

51
File I/O (Input/Output) in C
Reading from and writing to files on your computer’s disk
In C, FILE is a structure data type (structure variable in the standard library)
>>represents an open file >> holds any information

When you see FILE *fp, it means you have a pointer (fp) to that FILE structure.

• fp points to a FILE structure created by fopen()

fopen() function to open a file.


• It takes two main arguments: name file (as a string)
• The mode (how you want to open the file: read, write, or append).

52
Open a File

#include <stdio.h>

int main()
{
FILE *fp; // 'fp' is a file pointer
fp = fopen("myfile.txt", "r"); // Open for reading ("r")

if (fp == NULL)
{
printf("Error opening file.\n");
return 0; // Exit if the file couldn't be opened
}
// use the file ...
fclose(fp); // Always close the file when you're done
return 0;
}

53
Mode of file

 "r": Read

 "w": Write (overwrites if file exists, or creates a new file)

 "a": Append (adds to the end if file exists, or creates a new file)

 "r+": Read and write

 "w+": Write and read

 "a+": Append and read

54
Write file
#include <stdio.h>
int main()
{
FILE *fp = fopen("output.txt", "w"); // "w" = write mode
if (fp == NULL)
{
printf("Error opening file.\n");
return 0;
}
fprintf(fp, "Hello File!\n"); // Write some text to the file go new line
fprintf(fp, “How is life! \n"); // Both line will save in out.text file
fclose(fp);
return 0;
}
55
File reading
#include <stdio.h>

int main()
{
FILE *fp = fopen("data.txt", "r"); // "r" = read mode

if (fp == NULL)
{
printf("Error opening file.\n");
return 0;
}

int num;
fscanf(fp, "%d", &num); // Assuming data.txt has an integer
printf("Number: %d\n", num);

fclose(fp);
return 0;
}

56
File open write and read
//File open and writing
// Reading
#include <stdio.h> fp = fopen("sample.txt", "r");
if
int main() (fp == NULL)
{ {
FILE *fp; printf("Error: not open file for reading.\n");
char buffer[100]; return 0;
}
fp = fopen("sample.txt", "w"); while (fgets(buffer, sizeof(buffer), fp) != NULL)
if (fp == NULL)
{ {
printf("Error: not open file for writing.\n"); printf("%s", buffer);
return 0; }
}
fprintf(fp, “Hi there!\n"); fclose(fp);
fclose(fp);
return 0;
Buffer: Temporary memory “box” stores data.
sizeof: operator > gives the size in bytes of a
}
type or a variable
57
58
C and C++

 C follows the structured programming model, where programs


are split into functions, while C++ extends C by introducing
classes (bundling data and methods together), enabling object-
oriented design patterns.
 C++ source organization builds upon C‟s approach but
introduces additional constructs (namespaces, inline functions in
classes, templates) that can affect how code is structured and
compiled.
 C++ has a richer standard library out-of-the-box. It significantly
speed up development of common data structures and
algorithms compared to C‟s standard library.

59
Identifier in C++
Stream represent flow
Identifiers in C++ of data from source to destination
An identifier is a name used to identify variables,
#include <iostream>
functions, classes, namespaces, and other user-
defined int main()

Rules to be an identifier: {

1. Uses letters (a–z, A–Z), digits (0–9), and int age = 25; // 'age' is an identifier
underscore (_). std::cout << "Age: " << age << "\n";
2. Begin with a digit (e.g., 2value is invalid). //standard output stream
3. No special characters like @, #, $, %, etc. return 0;
4. No whitespace is allowed in an identifier.
}
5. Must not be a C++ keyword (like int, class, for,
etc.).
6. Case-sensitive (e.g., MyVar and myVar are
different).

60
Class and Object
#include <iostream>
Class: class Adder
{
 A class is a user-defined data type that public: // Data members to store the two numbers

encapsulates data members (variables) and int a, b; // Member function to read input from the user
void getData()
member functions into a single unit. {
std::cout << "Enter the first number: ";
 Class members are private, meaning they std::cin >> a;
std::cout << "Enter the second number: ";
are accessible only inside the class (if no std::cin >> b;
}
access by public keyword).
void showSum() // Member function operation
Object: {
int sum = a + b;
 An object is an implementation of a class std::cout << "The sum is: " << sum << std::endl;
}
 When you create an object, memory is };
int main()
allocated for the class‟s data members and , {
Adder obj; // Create an object of the Adder class
multiple objects can be created from the obj.getData(); // Call member functions on the object
obj.showSum();
same class return 0;
}

>> Class describes what can hold and


perform and object implements the class
61
Encapsulation
#include<iostream>
• Encapsulation is a process of combining data class Encapsulation
members and functions in a single unit called {
private:
class.
int x;
• Only access to them is provided through the public:
void set(int a)
functions of the class.
{
• It is one of the popular feature of Object Oriented x =a;
}
Programming (OOPs) that helps in data hiding.
int get()
 Variable x is made private. This variable can be {
return x;
accessed and manipulated only using the }
};
functions get() and set() which are present inside
void main()
the class.
{
=> The variable x and the functions get() and set() are
Encapsulation obj;
binded together which is encapsulated.
obj.set(5);
cout<<obj.get();
}
62
Hierarchy or inheritance
• This is a process of creating new classes
from existing classes. #include <iostream>
• An existing class that is "parent" of a new class Parent
{
class is called a base class. New class that public:
int id_p;
inherits properties of the base class is };
called a derived class. class Child : public Parent
{
public:
int id_c;

Inheritance types:
};

•Single void main()


{
•Multilevel child obj1;
obj1.id_c = 7;
•Multiple obj1.id_p = 91;
•Heirarchical cout << "Child id is " << obj1.id_c << endl;
cout << "Parent id is " << obj1.id_p << endl;
•Hybrid }
•Multipath Inheritance

63
Polymorphism
• It allows one name to be used for several #include <iostream>
class Geeks
related but slightly different purposes. The {
purpose of polymorphism is to let one name public:
void func(int x)
be used to specify a general class of action. {
cout << "value of x is " << x << endl;
C++ supports two ways to achieve
}
polymorphism. void func(int x, int y)
{
• Function overloading cout << "value of x and y is " << x << ", " << y << endl;
}
• Operator overloading };
void main()
{
Function overloading: Geeks obj1;
obj1.func(7);
When there are multiple functions with same name obj1.func(85,64);
but different parameters then these functions are }
said to be overloaded.

64
Operator overloading:

C++ also provide option to overload #include <iostream>


#include <string>
operators. For example, we can make the
operator („+‟) for string class to void main()
{
concatenate two strings. We know that int a = 9;
this is the addition operator whose task is int b = 10;
int c = a + b;
to add to operands. So a single operator cout<<"c = "<<c<<endl;
„+‟ when placed between integer operands
std::string str1 = "hello";
, adds them and when placed between std::string str2 = "world”;
string operands, concatenates them. std::string str3 = str1 + str2;

cout<<"str3 = "<<str3<<endl;
}

65

You might also like