Week 1
Week 1
Partha Pratim
Das Module 01: Programming in C++
Objectives & Recap of C
Outline
Recap of C
Data Types
Variables
Literals Partha Pratim Das
Operators
Expressions
Statements Department of Computer Science and Engineering
Control Flow
Arrays Indian Institute of Technology, Kharagpur
Structures
Unions [email protected]
Pointers
Functions
Input / Output
Std Library
Tanwi Mallick
Srijoni Majumdar
Organization
Himadri B G S Bhuyan
Build Process
References
Module 01
Std Library
Organization
Build Process
References
Std Library
Organization
Build Process
References
Module 01
Std Library
Organization
Build Process
References
Module 01
Data types in C are used for declaring variables and deciding on
Partha Pratim
Das
storage and computations:
Objectives & Built-in / Basic data types are used to define raw data
Outline
char
Recap of C
Data Types int
Variables
Literals
float
Operators
Expressions
double
Statements
Control Flow Additionally, C99 defines:
Arrays
Structures
Unions
bool
Pointers
Functions All data items of a given type has the same size (in bytes). The
Input / Output
size is implementation-defined.
Std Library
Organization Enumerated Type data are internally of int type and operates
Build Process on a select subset.
References
Objectives &
Each variable in C has a specific type, which determines
Outline the size and layout of the storage (memory) for the variable
Recap of C The name of a variable can be composed of letters, digits,
Data Types
Variables and the underscore character. It must begin with either a
Literals
Operators
letter or an underscore
Expressions
Statements
Control Flow int i, j, noOfData;
Arrays
Structures char c, endOfSession;
Unions
Pointers float f, velocity;
Functions
Input / Output
double d, dist_in_light_years;
Std Library
Organization
Build Process
References
Recap of C
int i = 10, j = 20, numberOfWorkDays = 22;
Data Types char c = ’x’;
Variables
Literals float weight = 4.5;
Operators
Expressions
double density = 0.0;
Statements
Control Flow
Arrays
Structures
Unions
Pointers
Functions
Input / Output
Std Library
Organization
Build Process
References
Module 01
Build Process
References
References
Recap of C
(of appropriate arity) is an expression
Data Types A function call is an expression
Variables
Literals
Operators
Examples:
Expressions
Statements For
Control Flow int i = 10, j = 20, k;
Arrays int f(int x, int y) { return x + y; }
Structures
Unions Expression are:
Pointers 2.5 // Value = 2.5
Functions i // Value 10
Input / Output -i // Value -10
Std Library i - j // Value -10
k = 5 // Value 5
Organization f(i, j) // Value 30
i + j == i * 3 // Value true
Build Process (i == j)? 1: 2 // Value 2
References
Build Process t = i;
i = j;
References j = t;
}
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 14
Control Constructs
Recap of C
Iteration-statement: for, while, do-while
Data Types Jump-statement: goto, continue, break, return
Variables
Literals
Operators
Examples:
Expressions if (a < b) { if (x < 5) switch (i) {
Statements int t; x = x + 1; case 1: x = 5;
Control Flow else { break;
Arrays t = a; x = x + 2; case 3: x = 10;
Structures a = b; --y; default: x = 15;
Unions b = t; } }
Pointers
}
Functions
Input / Output
Std Library
Organization
Build Process
References
Std Library
Organization
Build Process
References
Module 01 A union is a special structure that allocates memory only for the
Partha Pratim
largest data member and holds only one member as a time
Das Declare Union:
typedef union _Packet { // Mixed Data Packet
int iData; // integer data
Objectives &
double dData; // floating point data
Outline
char cData; // character data
Recap of C } Packet;
Data Types
printf("size = %d\n", sizeof(Packet)); // Prints: size = 8
Variables
Literals
Operators
Initialize Union:
Expressions Packer p = {10}; // Initialize only with a value of the type of first member
Statements printf("iData = %d\n", p.iData); // Prints: iData = 10
Control Flow
Arrays
Structures Access Union members:
Unions p.iData = 2;
Pointers printf("iData = %d\n", p.iData); // Prints: iData = 2
Functions
p.dData = 2.2;
Input / Output
printf("dData = %lf\n", p.dData); // Prints: dData = 2.200000
Std Library p.cData = ’a’;
printf("cData = %c\n", p.cData); // Prints: cData = a
Organization
p.iData = 97;
Build Process printf("iData = %d\n", p.iData); // Prints: iData = 97
printf("dData = %lf\n", p.dData); // Prints: dData = 2.199999
References printf("cData = %c\n", p.cData); // Prints: cData = a
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 20
Pointers
References
Module 01
• Pointer-Array Duality • Pointer to a structure
Partha Pratim int a[] = {1, 2, 3, 4, 5}; struct Complex { // Complex Number
Das int *p; double re; // Real component
double im; // Imaginary component
p = a; } c = { 0.0, 0.0 };
Objectives &
printf("a[0] = %d\n", *p); // a[0] = 1
Outline
printf("a[1] = %d\n", *++p); // a[1] = 2 struct Complex *p = &c;
Recap of C printf("a[2] = %d\n", *(p+1)); // a[2] = 3
(*p).re = 2.5;
Data Types
p = &a[2]; p->im = 3.6;
Variables
Literals *p = -10;
Operators printf("a[2] = %d\n", a[2]); // a[2] = -10 printf("re = %lf\n", c.re); // re = 2.500000
Expressions printf("im = %lf\n", c.im); // im = 3.600000
Statements
Control Flow
Arrays • malloc-free • Dynamically allocated arrays
Structures
int *p = (int *)malloc(sizeof(int)); int *p = (int *)malloc(sizeof(int)*3);
Unions
Pointers
Functions
*p = 0x8F7E1A2B; p[0] = 1; p[1] = 2; p[2] = 3;
Input / Output printf("%X\n", *p); // 8F7E1A2B
printf("p[1] = %d\n", *(p+1)); // p[1] = 2
Std Library unsigned char *q = p; free(p);
printf("%X\n", *q++); // 2B
Organization printf("%X\n", *q++); // 1A
printf("%X\n", *q++); // 7E
Build Process
printf("%X\n", *q++); // 8F
References
free(p);
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 22
Module 01: End of Lecture 02
Std Library
Organization
Build Process
References
Std Library
Organization
Build Process
References
References
References return 0;
}
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 26
Functions
References
Organization
Circle: (2.300000, 3.600000, 1.200000)
Build Process Rect: (4.500000, 1.900000, 4.200000, 3.800000)
Triag: (3.100000, 2.800000, 4.400000, 2.700000)
References
References
Module 01
To write to or read from file:
Partha Pratim #include <stdio.h>
Das
int main() {
Std Library
Organization
Build Process
References
Partha Pratim
Das Component Data Types, Manifest Constants, Macros, Functions, ...
stdio.h Formatted and un-formatted file input and output including
Objectives & functions
Outline
• printf, scanf, fprintf, fscanf, sprintf, sscanf, feof,
Recap of C etc.
Data Types
Variables
stdlib.h Memory allocation, process control, conversions, pseudo-
Literals random numbers, searching, sorting
Operators
Expressions
• malloc, free, exit, abort, atoi, strtold, rand,
Statements bsearch, qsort, etc.
Control Flow
string.h Manipulation of C strings and arrays
Arrays
Structures • strcat, strcpy, strcmp, strlen, strtok, memcpy,
Unions memmove, etc.
Pointers
Functions math.h Common mathematical operations and transformations
Input / Output • cos, sin, tan, acos, asin, atan, exp, log, pow, sqrt, etc.
Std Library errno.h Macros for reporting and retrieving error conditions through
Organization
error codes stored in a static memory location called errno
• EDOM (parameter outside a function’s domain – sqrt(-1)),
Build Process • ERANGE (result outside a function’s range), or
References • EILSEQ (an illegal byte sequence), etc.
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 31
Source Organization for a C program
Module 01
Header Files
Partha Pratim
Das A header file has extension .h and contains C function
Objectives & declarations and macro definitions to be shared between several
Outline source files
Recap of C
Data Types There are two types of header files:
Variables
Literals
Operators
Files that the programmer writes
Expressions
Statements
Files from standard library
Control Flow
Arrays Header files are included using the #include pre-processing
Structures
Unions directive
Pointers
Functions
Input / Output
#include <file> for system header files
Std Library
#include "file" for header files of your own program
Organization
Build Process
References
Module 01
Partha Pratim
Example:
Das
// Solver.h -- Header files
int quadraticEquationSolver(double, double, double, double*, double*);
Objectives &
Outline // Solver.c -- Implementation files
#include "Solver.h"
Recap of C
Data Types int quadraticEquationSolver(double a, double b, doublec , double* r1, double* r2) {
Variables // ...
Literals // ...
Operators // ...
Expressions
return 0;
Statements
}
Control Flow
Arrays
Structures
// main.c -- Application files
Unions
#include "Solver.h"
Pointers
Functions int main() {
Input / Output double a, b, c;
double r1, r2;
Std Library
int status = quadraticEquationSolver(a, b, c, &r1, &r2);
Organization
return 0;
Build Process
}
References
Module 01
Partha Pratim
Das
Objectives &
Outline
Recap of C
Data Types
Variables
Literals
Operators
Expressions
Statements
Control Flow
Arrays
Structures
Unions
Pointers
Functions
Input / Output
Std Library
Organization
Build Process
References
Module 01
C Pre-processor (CPP) substitutes and includes functions,
Partha Pratim
Das headers and macros before compilation
int sum(int, int);
Objectives & int main() {
Outline int a = sum(1,2);
return a;
Recap of C }
Data Types
Variables
Literals The compiler translates the pre-processed C code into assembly
Operators
Expressions
language, which is a machine level code that contains
Statements
Control Flow
instructions that manipulate the memory and processor directly
Arrays
Structures The linker links our program with the pre-compiled libraries for
Unions
Pointers
using their functions
Functions
Input / Output In the running example, function.c and main.c are first
Std Library
compiled and then linked
Organization int sum(int a,int b) { return a+b; }
Module 01
Recap of C
Data Types
Variables
Literals
Operators
Expressions
Statements
Control Flow
Arrays
Structures
Unions
Pointers
Functions
Input / Output
Std Library
Organization
Build Process
References
Module 01
Partha Pratim
Das Kernighan, Brian W., and Dennis M. Richie. The C
Programming Language. Vol. 2. Englewood Cliffs:
Objectives &
Outline Prentice-Hall, 1988.
Recap of C
Data Types
King, Kim N., and Kim King. C programming: A Modern
Variables
Literals
Approach. Norton, 1996.
Operators
Expressions
Statements
Control Flow
Arrays
Structures
Unions
Pointers
Functions
Input / Output
Std Library
Organization
Build Process
References
Module 01
Std Library
Organization
Build Process
References
Module 01
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Recap of C
Srijoni Majumdar, TA [email protected] 9674474267
Data Types Himadri B G S Bhuyan, TA [email protected] 9438911655
Variables
Literals
Operators
Expressions
Statements
Control Flow
Arrays
Structures
Unions
Pointers
Functions
Input / Output
Std Library
Organization
Build Process
References
Partha Pratim
Das Module 02: Programming in C++
Objectives & Programs with IO & Loop
Outline
Hello World
Add numbers
Square Root
Standard Library
Sum Numbers Partha Pratim Das
Using bool
Summary
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur
[email protected]
Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan
Module 02
Summary
Module 02
printf("Sq. Root of %lf is:", x); cout << "Sq. Root of " << x;
printf(" %lf\n", sqrt_x); cout << " is: " << sqrt_x << endl;
return 0; return 0;
} }
Input number: Input number:
2 2
Square Root of 2.000000 is: 1.414214 Square Root of 2 is: 1.41421
• Math Header is math.h (C Standard Library) • Math Header is cmath (C Standard Library in C++)
• Formatting (%lf) needed for variables • Formatting is derived from type (double) of variables
• sqrt function from C Standard Library • sqrt function from C Standard Library
• Default precision in print is 6 • Default precision in print is 5 (different)
Partha Pratim • All names are global • All names are within std namespace
Das
• stdout, stdin, printf, scanf • std::cout, std::cin
Objectives &
• Use
Outline
Hello World using namespace std;
Add numbers
Square Root
to get rid of writing std:: for every standard
Standard Library
library name
Sum Numbers
Using bool
std::cout << "Hello World in C++" cout << "Hello World in C++"
<< std::endl; << endl;
return 0; return 0;
} }
Module 02
Summary for (i = 0; i <= n; ++i) for (int i = 0; i <= n; ++i) // Local Decl.
sum = sum + i; sum = sum + i;
return 0; return 0;
} }
• Using int and #define for bool • stdbool.h included for bool • No additional headers required
• May use Bool (C99) • Bool type & macros (C99):
bool which expands to Bool bool is a built-in type
true which expands to 1 true is a literal
false which expands to 0 false is a literal
Module 02
Module 02
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Hello World Srijoni Majumdar, TA [email protected] 9674474267
Add numbers
Square Root Himadri B G S Bhuyan, TA [email protected] 9438911655
Standard Library
Sum Numbers
Using bool
Summary
Partha Pratim
Das Module 03: Programming in C++
Objectives & Arrays and Strings
Outline
Arrays &
Vectors
Fixed Size Array
Arbitrary Size Partha Pratim Das
Array
Vectors
Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan
Module 03
Strings
Summary
Module 03
23 34 65 74 23 34 65 74
Module 03
This can be implemented in C (C++) in the following ways:
Partha Pratim
Das Case 1: Declaring a large array with size greater than the
Objectives &
size given by users in all (most) of the cases
Outline Hard-code the maximum size in code
Arrays &
Vectors
Declare a manifest constant for the maximum size
Fixed Size Array
Arbitrary Size
Case 2: Using malloc (new[]) to dynamically allocate
Array
Vectors space at run-time for the array
Strings
Summary
return 0; return 0;
} }
• MAX is the declared size of array • MAX is the declared size of vector
• No header needed • Header vector included
• arr declared as int [] • arr declared as vector<int>
NPTEL MOOCs Programming in C++ Partha Pratim Das 7
Program 03.04: Dynamically managed array size
• malloc allocates space using sizeof • resize fixes vector size at run-time
Module 03
String manipulations in C and C++:
Partha Pratim
Das C-String and string.h library
Objectives & C-String is an array of char terminated by NULL
Outline C-String is supported by functions in string.h in C
Arrays &
Vectors
standard library
Fixed Size Array
Arbitrary Size
string type in C++ standard library
Array
Vectors string is a type
Strings With operators (like + for concatenation) behaves like a
Summary built-in type
Module 03
Further,
Partha Pratim
Das operator= can be used on strings in place of strcpy
Objectives & function in C.
Outline
Arrays &
operator<=, operator<, operator>=, operator>
Vectors operators can be used on strings in place of strcmp
Fixed Size Array
Arbitrary Size
Array
function in C
Vectors
Strings
Summary
Module 03
Partha Pratim Working with variable sized arrays is more flexible with
Das
vectors in C++
Objectives &
Outline String operations are easier with C++ standard library
Arrays &
Vectors
Fixed Size Array
Arbitrary Size
Array
Vectors
Strings
Summary
Module 03
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Arrays &
Srijoni Majumdar, TA [email protected] 9674474267
Vectors Himadri B G S Bhuyan, TA [email protected] 9438911655
Fixed Size Array
Arbitrary Size
Array
Vectors
Strings
Summary
Partha Pratim
Das Module 04: Programming in C++
Objectives & Sorting and Searching
Outline
Sorting
Bubble Sort
Standard Library
Searching
Partha Pratim Das
Standard Library
Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan
Module 04
Objectives &
Outline
Sorting
Bubble Sort
Standard Library
Searching
Standard Library
STL:
algorithm
Summary
Module 04
STL:
algorithm
Summary
return 0; return 0;
} }
12 26 32 45 71 12 26 32 45 71
• Implementation is same in both C and C++ apart from the changes in basic header files, I/O functions
explained in Module 02.
STL: // Start ptr, # elements, size, func. ptr // Start ptr, end ptr, func. ptr
algorithm qsort(data, 5, sizeof(int), compare); sort (data, data+5, compare);
return 0; return 0;
} }
71 45 32 26 12 71 45 32 26 12
STL: return 0;
algorithm }
Summary 12 26 32 45 71
• Sort using the default sort function of algorithm library which does the sorting in ascending order only.
return 0; return 0;
} }
found! found!
Module 04
The algorithm library of c++ helps us to easily implement
Partha Pratim
Das commonly used complex functions. We discussed the functions
Objectives &
for sort and search. Let us look at some more useful functions.
Outline
Replace element in an array
Sorting
Bubble Sort
Standard Library
Rotates the order of the elements
Searching
Standard Library
STL:
algorithm
Summary
Summary
1 2 2 4 5 3 4 5 1 2
• 3rd element replaced with 2 • Array circular shifted around 3rd element.
Module 04
Summary
Module 04
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Sorting
Srijoni Majumdar, TA [email protected] 9674474267
Bubble Sort Himadri B G S Bhuyan, TA [email protected] 9438911655
Standard Library
Searching
Standard Library
STL:
algorithm
Summary
Partha Pratim
Das Module 05: Programming in C++
Objectives & Stack and its Applications
Outline
Stack in C
Reverse a String
Eval Postfix
Stack in C++
Partha Pratim Das
Reverse a String
Eval Postfix
Department of Computer Science and Engineering
Summary Indian Institute of Technology, Kharagpur
[email protected]
Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan
Module 05
Stack in C
Reverse a String
Eval Postfix
Stack in C++
Reverse a String
Eval Postfix
Summary
Module 05
Summary
Module 05
Some common C programs that use stack:
Partha Pratim
Das Reversing a string
Objectives & Input: ABCDE
Outline Output: EDCBA
Stack in C
Reverse a String
Evaluation of postfix expression
Eval Postfix
Input: 1 2 3 * + 4 - (for 1 + 2 * 3 - 4)
Stack in C++
Reverse a String
Output: 3
Eval Postfix Stack states:
Summary
1 2 3 6 7 4 3
1 2 1 7
1
Evaluation 3
Module 05
Partha Pratim C++ standard library provide a ready-made stack for any
Das
type of elements
Objectives &
Outline
To create a stack in C++ we need to:
Stack in C Include the stack header
Reverse a String Instantiate a stack with proper element type (like char)
Eval Postfix
Stack in C++
Use the functions of the stack objects for stack operations
Reverse a String
Eval Postfix
Summary
return 0; return 0;
} }
Module 05 // FileName:Postfix_Evaluation_c++.cpp
#include <iostream>
Partha Pratim #include <stack>
Das using namespace std;
int main() {
Objectives & // Postfix expression: 1 2 3 * + 4 -
Outline char postfix[] = {’1’,’2’,’3’,’*’,’+’,’4’,’-’}, ch;
stack<int> s;
Stack in C
Reverse a String
for(int i = 0; i < 7; i++) {
Eval Postfix
ch = postfix[i];
Stack in C++ if (isdigit(ch)) { s.push(ch-’0’); }
Reverse a String else {
Eval Postfix int op1 = s.top(); s.pop();
int op2 = s.top(); s.pop();
Summary switch(ch) {
case ’*’: s.push(op2 * op1); break;
case ’/’: s.push(op2 / op1); break;
case ’+’: s.push(op2 + op1); break;
case ’-’: s.push(op2 - op1); break;
}
}
}
cout << "\nEvaluation " << s.top();
return 0;
}
Module 05
Module 05
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Stack in C
Srijoni Majumdar, TA [email protected] 9674474267
Reverse a String Himadri B G S Bhuyan, TA [email protected] 9438911655
Eval Postfix
Stack in C++
Reverse a String
Eval Postfix
Summary