01 Cen103
01 Cen103
Computer Programming
Overview
2
Introduction
• Algorithm
• A set of explicit and unambiguous finite steps, which, when carried out for
a given set of initial conditions to produce the corresponding output and
terminate in finite time.
• Basically, they are a set of steps to be performed, which can be used to
perform a task/solve a problem.
• Program
• An implementation of an algorithm in a programming language that computer
can understand.
5
Programs
#include <iostream>
using namespace std;
6
High and low level languages
High-level Low-level
• Resemble human languages • It is difficult to write and debug
• Are designed to be easy to read and code in Low-Level Languages.
write • Assembly
• Use more complicated instructions ADD X Y Z
than the CPU can follow • Machine language
• Must be translated to zeros and – CPU can follow machine language
ones for the CPU to execute a – Assembly must be converted to
program machine language
• C, C++, Java, Visual Basic, etc.
0110 1001 1010 1011
• → Source Code
→ Object Code
7
High and low-level languages
8
Programmers?
9
In this course
• C++
– Derived from C
– C++ designer: Bjarne Stroustrup (1979)
– Powerful and complex
10
C++ basics
• Comments:
– used to explain the code or increase the readability
– Comments are ignored by compiler
– Single/ multi-lined
// looping over the array
/* looping over
the array*/
11
Processing a C++ program
12
Processing a C++ program
• Compiler →
– checks the program for syntax errors (set of rules which are
language specific)
– Compiler accepts almost any pattern of line breaks and indentation
– Translate into machine language (low-level language);
– Binary of “Hello World.”
01001000 01100101 01101100 01101100 01101111
00100000 01010111 01101111 01110010 01101100
01100100
• Execution
– from top to bottom
– from left to right
• Output
13
Program errors
• Syntax errors
– Violation of the grammar rules (syntax) of the language
– Discovered by the compiler
• Error messages may not always show the correct location of
errors
• Run-time errors
– Error conditions detected by the computer at run-time
• Logic errors
– Errors in the program’s algorithm
– Most difficult to diagnose
– Computer does not recognize an error
14
Hello World!
#include <iostream>
int main( ) {
15
Where to run the program?
• Offline:
– Dev-C++
– Visual Studio
– …
• Online:
– https://www.programiz.com/cpp-programming/online-compiler/
– https://www.tutorialspoint.com/compile_cpp_online.php
– https://www.w3schools.com/cpp/cpp_compiler.asp
[[let’s–run
…the first program]]
Try to write a few programs, which prints your name/ enrolment number/
branch/ institute, etc.
16
Where to run the program?
17
Why C++ (or programming) in Civil Engineering?
• AutoCAD → C++
• SUMO (open-source): https://sumo.dlr.de/ → C++
• 12 D solutions → C++
• FreeFEM: https://freefem.org/ → C++
• …
• Others (general) → C++
– Amazon
– Google web search engine
– Apple OS X (a few important parts)
– Adobe systems
– Bloomberg
– Sun: Open Office
– …
• Many other languages…
18
Special symbols
• + • ?
• - • ,
• * • <=
• / • !=
• . • ==
• ; • >=
19
Reserved keywords
• int • catch
• float • enum
• double • public
All small-case
• char • false
• const • true
• void • break
• return • continue
• switch • namespace
• while • throw
• do • static
• for • private
• this • …
20
C++ basic input, output
• For cout, insertion (<<) operators are used, whereas for cin
extraction (>>) operators are used
• Let’s look on the Hello World example TODO: try clog and cerr
21
cout
header (remember Name of the function;
directives)!! return type;
every program must have
#include <iostream> exactly one main()
function
int main( ) {
Check cout, insertion
// write the comment here… operator, semi colon
std::cout << “Hello world”;
return 0;
What is this? Can we
} get rid of it?
22
cout
This means, all functions under std namespace
#include <iostream> are available in the scope of this program
using namespace std; without explicitly prefixing “std::”
int main( ) {
23
cout
#include <iostream>
using namespace std;
What will be the output of this?
int main( ) {
24
cin
#include <iostream>
using namespace std;
int main( ) {
int num ;
cout << “Enter an Integer”;
cin >> num; // taking input
cout << “Square of the number is “ << num*num;
return 0;
25
C++ Program
26
Data types
27
Data types
28
Primitive Data types: char
29
Primitive Data types
31
Data types modifiers
1 2 4 8
33
Other Data types
34
Variable names in C++
35
Variable names in C++
• Syntax
datatype variable_name;
• Though, it is a matter of personal preference, descriptive
names are recommended for better readability of the code
• Unlike reserved words, predefined identifiers (e.g., cout,
cin) can be redefined, but don’t do that.
• Cases:
– Camel ageOfPerson
– Pascle AgeOfPerson
– Snake age_of_person
Different style for local, instance, static, variables may be adopted for clarity.
36
Variable names in C++
#include <iostream>
using namespace std;
int main( ) {
38
Variable names in C++
#include <iostream>
using namespace std;
int main( ) {
int num1;
int num2;
num1=34;
num2=90;
cout << num1 << endl;
cout << num2;
return 0;
}
39
Variable names in C++
#include <iostream>
using namespace std;
int main( ) {
40
Variable names in C++
#include <iostream>
using namespace std;
int main( ) {
41
Variable names in C++
#include <iostream>
using namespace std;
int main( ) {
Three variables can be entered separated by space or one number in each line
(newline separator).
42
Operators
1. Arithmetic
2. Assignment
3. Relational
4. Logical
5. Other
43
Arithmetic Operators
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
44
Arithmetic Operators
int main( ) {
int a =34, b=90;
cout << "a+b=" << (a+b) << endl;
cout << "a-b=" << (a-b) << endl;
cout << "a*b=" << (a*b) << endl;
cout << "a/b=" << (a/b) << endl;
cout << "a%b=" << (a%b) << endl;
return 0;
}
int main( ) {
int a =3;
Unary operators
int x = a++;
• Pre-increment ++x (also --x)
cout << x << endl;
• Post-increment x++ (also x-- )
cout << a << endl;
x = ++a;
cout << x << endl;
cout << a << endl;
return 0;
}
45
Assignment Operators
46
Assignment Operators
#include <iostream>
using namespace std;
int main( ) {
47
Order of Precedence
• All operations inside of () are evaluated first
• *, /, and % are at the same level of precedence and are evaluated next
• + and – have the same level of precedence and are evaluated last
48
Mixed expression
• Integral expression 2+3*6
49
Relational Operators
50
Logical Operators
Logical AND.
expression1 &&
&& True only if all the
expression2
operands are true.
Logical OR.
expression1 ||
|| True if at least one of
expression2
the operands is true.
Logical NOT.
! !expression True only if the
operand is false.
51
Logical Operators
#include <iostream>
using namespace std;
int main( ) {
52
other Operators
53
Mathematical Functions
#include<math.h>
• Examples:
– sin, cos, tan …
– asin, acos, atan …
– sqrt, abs, pow, floor, ceil …
– log, exp, …
– See https://www.cplusplus.com/reference/cmath/
54
Mathematical Functions
#include <iostream>
#include<cmath>
using namespace std;
int main( ) {
int a = 25;
cout << sqrt(a) << endl;
int b = 5;
int c = 3;
cout << pow(5,3);
return 0;
}
55
Conditional Statements
if (condition) {
// block of code to be executed if the condition is true
}
56
Conditional Statements
Truth Tables
57
Conditional Statements
58
Conditional Statements
59
Conditional Statements
60
Conditional Statements
61
Conditional Statements
int speed;
cin >> speed;
if (speed < 40) {
cout << “Good going…";
} else if (speed < 50) {
cout << “Just right …";
} else {
cout << “Too fast, slow down…";
}
62
Conditional Statements
In the above case, the else is connected with the inner conditional and not
the outermost conditional statement.
63
Conditional Statements
64
Conditional Statements
int day = 4;
switch (day) {
case 1:
cout << "Monday"; It breaks out of the switch
break; block, i.e., no more case
case 2: testing inside the switch
cout << "Tuesday";
block.
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
default:
cout << “Enjoying the Weekend";
}
65
Conditional Statements: nested
66
Loops
• Repetition
• To execute a block of code as long as a specific condition is met
• Loops are handy, saves time, reduce errors, and are more readable
67
Loops
int i = 0;
int max;
cin >> max;
do {
cout << i << "\n";
i++;
} while (i < max);
68
Loops
69
Loops
70
Loops
71
Loops
• Infinite loop
72
Loops: nested
73
Jumps with break, continue and goto
• break: The break statement exits from a switch or loop immediately. You can use
the break keyword to jump to the first statement that follows the switch or loop.
• continue: The continue statement can be used in loops and has the opposite effect
to break, that is, the next loop is begun immediately. In the case of a while or do-
while loop, the program jumps to the test expression, whereas a for loop is
reinitialized.
• goto: C++ also offers a goto statement and labels. This allows you to jump to any
given point marked by a label within a function. For example, you can exit from a
deeply embedded loop construction immediately. A label is a name followed by a
colon.
74
break
int i = 0;
while (i < 10) {
cout << i << "\n";
i++;
if (i == 4) {
break;
}
}
75
break
76
continue
int i = 0;
while (i < 10) {
if (i == 4) {
i++;
continue;
}
cout << i << "\n";
i++;
}
77
goto
78
goto
79
Control structure in C++
80
string in C++
81
string in C++
82
string in C++
83
string in C++
84
string in C++
85
String Concatenation
86
String Concatenation
int x = 10;
int y = 20;
int z = x + y; // output →??
string x = "10";
string y = "20";
string z = x + y; // output →??
87
String Access
88
String inserting and erasing
string s1("Miss Summer");
s1.insert(5, "Ashley "); // Insert at position: 5
89
String Access
string name;
cin >> name; // Enter “Amit Agarwal”
cout << name;
string name;
cout << "Enter your name" <<endl;
getline (cin, name);
cout << name;
90
Thanks …
amitfce@iitr.ac.in
91