C & C++ lecture by Earul sir
C & C++ lecture by Earul sir
Programming:
Telling the computer what to do
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.
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
Yes
X<=20
No
End
7
Structure of C program
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
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
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:
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:
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
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 (+, -, *, /, %)
• 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
taka += 4 taka -= 4
23
Operator Precedence
24
Operator Precedence test
Which function will be called first? f( ) or g( )?
int i = (f( ) + g( )) || g( );
int j = g( ) || (f( ) + g( ));
int a = 5 * 3 % 6 - 8 + 3;
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
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);
}
29
Home task
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
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
Structure:
If(condition)
statement;
else if (condition)
statement;
……….
else
statement;
35
Loops
Loops
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
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;
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
{
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
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.).
#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.
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:
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.
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
"a": Append (adds to the end if file exists, or creates a new file)
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++
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;
}
Inheritance types:
};
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:
cout<<"str3 = "<<str3<<endl;
}
65