[go: up one dir, main page]

0% found this document useful (0 votes)
6 views91 pages

01 Cen103

The document provides an overview of computer programming, focusing on the definition of programming, algorithms, and the structure of programs. It introduces C++ as a programming language, explaining its syntax, data types, and basic operations. The document also highlights the importance of programming in civil engineering and offers examples of simple C++ programs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views91 pages

01 Cen103

The document provides an overview of computer programming, focusing on the definition of programming, algorithms, and the structure of programs. It introduces C++ as a programming language, explaining its syntax, data types, and basic operations. The document also highlights the importance of programming in civil engineering and offers examples of simple C++ programs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 91

INDIAN INSTITUTE OF TECHNOLOGY ROORKEE

Computer Programming
Overview

Prof. Amit Agarwal


amitfce@iitr.ac.in amit.agarwal@mfs.iitr.ac.in
What do you think of
programming (one word)?

ⓘ Start presenting to display the poll results on this slide.

2
Introduction

• Computer: (Definition by Oxford Dictionary)

“an electronic device for storing and processing data, …,


according to instructions given to it in a variable program.”

• Complex system consisting of hardware and software


– Hardware: physical parts (e.g., input media, motherboard, etc.)
– Software: a set of programs used by a computer

• Programming is a process of writing instructions (a set of


commands) to solve a specific problem.

• Algorithm is a step-by-step problem-solving process.


3
Basics components

Main memory consists of a long


list of numbered locations called
memory locations (a few
thousands to millions);
Secondary memory (or storage)
The contents of these locations
is the memory that is used for
can change and contain the same
keeping a permanent record of
number of 0s and 1s → binary
information after (and before) the
digit or a bit ➔ most computers
computer is used. Also referred as
contains 8 bits (i.e., byte) → The
auxiliary memory, auxiliary
number that identifies a byte is
storage, external memory, and
called its address.
external storage
4
Programs

Input to the program


Set of instructions

• 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

Algorithm Program (in C++)

#include <iostream>
using namespace std;

Input A, B, C int main() {


int A, B, C, Sum;
Sum = A + B + C
cin>>A>>B>>C;
Print Sum Sum = A + B + C;
cout<<Sum;
return 0;
}

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

• How to write programs?

• Program → a set of instructions → special notation or


syntax (i.e., programming language)

• C++
– Derived from C
– C++ designer: Bjarne Stroustrup (1979)
– Powerful and complex

• We will cover only a part of C++….

10
C++ basics

• Syntax: language-specific statements (instructions/


notations/ rules) which are legal

• 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*/

• Every instruction/ command is terminated by semi-colon “;”

11
Processing a C++ program

• Editor → simply writing the set of instructions as per the


syntax (many text editors support syntax/ color highlighting)

• Preprocessor → these are directives which give instructions


to the compiler to pre-process the information
– Starts with # (only whitespace is allowed before this)
– these are filenames in the Standard C++ Library.

#include <iostream>  this is a C++ standard library header


for input-output stream
#define PI 3.14

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( ) {

// hello world program


std::cout << “Hello world”;
return 0;

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

• cout → sends the output from main memory to standard


devices (e.g., console screen)

• cin → takes the input from standard devices (e.g.,


keyboard, mouse) to the main memory

• header (required): #include <iostream>

• 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?

Return statement; optional


but some compilers expect it
to be included as the last line
of the main() function

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( ) {

// write the comment here…


cout << “Hello world”;
return 0;

Let’s look on another example

23
cout

#include <iostream>
using namespace std;
What will be the output of this?

int main( ) {

cout << “Hel” << “lo” <<“Wo” << “rld”;


return 0;

Let’s look on another example

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

• Primitive data types


• Derived data types
• User defined data types

27
Data types

28
Primitive Data types: char

• “hello” is a string literal


• char is stored in the computers as an integer
• enclosed in single quotes
• American Standard Code for Information Interchange
(ASCII)
• Visit:
– https://www.ascii-code.com/
– https://en.cppreference.com/w/cpp/language/ascii
• Newline character ‘\n’ is one of the non-printing characters
(e.g., \n, \t).
• Size 1 byte
• Range: -128 to 127 or 0 to 255 (on most compilers)

29
Primitive Data types

Data type Meaning Size (in bytes) Other details


int Integer 4 Range: -2147483648 to
int age = 24; 2147483647; usually of 4
bytes
float Floating point 4 Precision = 7 places
float speed = 60.5; (decimals)
double Double floating 8 Higher precision than
double dist = 4.45; point float (14)
char Character 1 Inside single quotes; an integer
value is stored rather than the
char te = ‘t’; character itself (see
https://en.cppreference.com/w/c
std::cout << int(te) ; Do you really need 1 pp/language/ascii and
byte for bool? https://www.ascii-code.com/ )
Range: -127 to 127 or 0 to
255
bool Boolean 1 Two possible values: true,
bool val = false; false
30
Primitive Data types

31
Data types modifiers

• signed: int, char, long-prefix


• unsigned: int, char, long-prefix
• short: int
• long: int, double
• Execute the following and try to understand the results
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of signed int : " << sizeof(signed int) << endl;
cout << "Size of unsigned int : " << sizeof(unsigned int) << endl;
cout << "Size of unsigned long int : " << sizeof(unsigned long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;
cout << "Size of long double : " << sizeof(long double) << endl;
cout << "Size of signed char : " << sizeof(signed char) << endl;
cout << "Size of unsigned char : " << sizeof(unsigned char) << endl;
32
Data types modifiers

1 2 4 8

33
Other Data types

• Derived data types: array, pointers, functions, etc.


• User defined: Class, Structure, Union, Enum, etc.

34
Variable names in C++

• Unique names (called as identifiers)


• This is basically, a name given to the memory location
• Variables must be declared before use.
• It could be short as (i,j,k or long as volume, speed)
• It may contain letters, digits, underscores (_)
• It must begin with a letter or underscore (i.e., it cannot begin with a
number)
• Names are case sensitive
• Names cannot contain white spaces or special characters
• Reserved words cannot be used.
• Examples:
age _age A_ge a_g_e
age23 a23ge a ageOfPerson

What will happen if you write wrong names? Try it.

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++

int age = 24;

data_type variable_name value (initialize)

int time, speed;

What will be output of the following?

float number = 1/10;


std::cout << number <<std::endl;
What will be output of the following?

float number = 1.0/10.0;


std::cout << number <<std::endl;
What will be output of the following?

int number = 1.0/10.0;


std::cout << number <<std::endl;
37
Variable names in C++

#include <iostream>
using namespace std;

int main( ) {

int num ; // declaration


num = 23; // initialization or assignment
return 0;

A variable must be initialized before it is used (not necessarily during declaration).

A variable can be initialized by assignment and by taking from inputs.

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( ) {

int num1 =34, num2=90; // declaration and initialization


cout << num1 << endl;
cout << num2;
return 0;
}

40
Variable names in C++

#include <iostream>
using namespace std;

int main( ) {

int num1 =34, num2=90;


cout << num1 << endl;
cout << num2 <<endl;
int num3 = num1 +num2; /* expression (on the right) is
evaluated first and then assigned to num3 */
cout << num3;
return 0;
}

41
Variable names in C++

#include <iostream>
using namespace std;

int main( ) {

int hours, minutes, seconds;


cin>> hours >> minutes >> seconds; // order is important
cout<< hours << ":" << minutes << ":" << seconds;
return 0;
}

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

Modulo Operation (Remainder


%
after 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

Operator Example Equivalent to


= a = b; a = b;
+= a += b; a = a + b;
-= a -= b; a = a - b;
*= a *= b; a = a * b;
/= a /= b; a = a / b;
%= a %= b; a = a % b;

46
Assignment Operators

#include <iostream>
using namespace std;

int main( ) {

int a =3, b=9;


cout << “Old value of a:" << a << endl;
a += b
cout << “New value of a:" << a << endl;
return 0;

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

• When operators are on the same level


• Performed from left to right (associativity)

48
Mixed expression
• Integral expression 2+3*6

• Floating expression 2.5 + 3.1 * 3.2

• Mixed expression evaluation: 2 + 3.5 / 2


• If operator has same types of operands
• Evaluated according to the type of the operands

• If operator has both types of operands


• Integer is changed to floating-point
• Operator is evaluated
• Result is floating-point

• Entire expression is evaluated according to precedence rules

49
Relational Operators

Operator Meaning Example

== Is Equal To 3 == 5 gives us false

!= Not Equal To 3 != 5 gives us true

> Greater Than 3 > 5 gives us false

< Less Than 3 < 5 gives us true

Greater Than or Equal


>= 3 >= 5 give us false
To

<= Less Than or Equal To 3 <= 5 gives us true

50
Logical Operators

Operator Example Meaning

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( ) {

bool out = (3 != 5) && (3 < 5); // 1 (true)

bool out2 = !(5 == 2); // 1 (true)

bool out3 = !(5 == 5); //0 (false)


return 0;

52
other Operators

Operator Description Example

sizeof returns the size of data type sizeof(int); // 4

string result = (5%2==0) ?


?: returns value based on the condition
"even" : "odd"; // "even"

represents memory address of the


& &num; // address of num
operand

accesses members of struct variables or


. s1.marks = 92;
class objects

used with pointers to access the class or


-> ptr->marks = 92;
struct variables

<< prints the output value cout << 5;

>> gets the input value cin >> num;

53
Mathematical Functions

• Large number of mathematical functions are available in


standard C++

• To use them, include:


#include<cmath>

#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 num = -10;


cout << abs(num) << endl;

int a = 25;
cout << sqrt(a) << endl;

int b = 5;
int c = 3;
cout << pow(5,3);
return 0;
}

55
Conditional Statements

• Remember Relational and logical operators

• Use if to execute a block of code, if a condition is met (i.e., true)

• Use else to execute a block of code, if the same condition is false

• Use else if to test a new condition, if the first condition is false

• Use switch to execute many alternative blocks based on different criteria of a


variable

if (condition) {
// block of code to be executed if the condition is true
}

if (35 >= 20) {


cout << “35 is greater than or equal to 20";
}

56
Conditional Statements
Truth Tables

57
Conditional Statements

58
Conditional Statements

Unary operators are right-associative,


meaning that if multiple unary operators
are applied to the same operand, they are
evaluated from right to left

59
Conditional Statements

int speed = 30;


if (speed < 40) {
cout << “Good going…";
} else {
cout << “Too fast, slow down…";
}

int speed = 30;


if (speed < 40) {
cout << “Good going…";
} else if (speed < 50) {
cout << “Just right …";
} else {
cout << “Too fast, slow down…";
}

60
Conditional Statements

61
Conditional Statements

int speed = 30;


if (speed < 40) {
cout << “Good going…";
} else {
cout << “Too fast, slow down…";
}

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

int speed = 30;


string message = (speed < 40) ? "Good going…" : “Too fast, slow down…";
cout << message;

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

int speed = 30;


int vehicle = 1; // 1→ car, 2→ MTW
if (speed < 40) {
if (vehicle == 1) {
cout << “Good going…";
} else {
cout << “Be careful, out there.";
}
} else {
if (vehicle == 1) {
cout << “Too fast, slow down …";
} else {
cout << “Dangerous speed…";
}
}

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

The while loop loops through


while (condition) { a block of code as long as a
// code block to be executed specified condition is true.
}
This loop will execute the code block
once, before checking if the condition
do { is true, then it will repeat the loop as
// code block to be executed long as the condition is true.
}
while (condition);
If it is known that a block of
for (initialization; condition; update) { code is to be executed ‘n’
// code block to be executed times, use the for loop
} instead of a while loop:

67
Loops

int i = 0; for (int i = 0; i < max; i++) {


int max; cout << i << "\n";
cin >> max; }
while (i < max) {
cout << i << "\n";
i++;
}

int i = 0;
int max;
cin >> max;
do {
cout << i << "\n";
i++;
} while (i < max);

68
Loops

• Compute the average of numbers as long as a user enters the numbers

69
Loops

• Multiple variables in the loop

70
Loops

• Multiple variables in the loop

71
Loops

• Infinite loop

72
Loops: nested

for (int i = 0; i < max; i++) {


for (int j = 0; j < max; j++) {
cout << i << "\n";
}
}

How can we get the following?


*
**
***
****
*****
How can we get the following?
*****
****
***
**
*

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

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


if (i == 4) {
break;
}
cout << i << "\n";
}

int i = 0;
while (i < 10) {
cout << i << "\n";
i++;
if (i == 4) {
break;
}
}

75
break

76
continue

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


if (i == 4) {
continue;
}
cout << i << "\n";
}

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++

• string is a variable, which is a collection of characters


• Surrounded by double quotes (“my string”)
string age = “34";
• Example
string message("Good morning!");
Try to use sizeof(age) and Note that: sizeof only
age.size();
• Size of string see the output. Does it
reports the memory
occupied by the
age.length(); make sense? variable

81
string in C++

• Each character has a relative position in the string


– Position of the first character is 0

• The length of a string is the number of characters in it


– Example: length of “Good Morning!" is 13

82
string in C++

• endl → causes insertion point to move to beginning of next


line
• Escape sequence:

83
string in C++

• Relational operators can be applied to strings


• Strings are compared character by character, starting with
the first character
• Comparison continues until either a mismatch is found, or
all characters are found equal
• If two strings of different lengths are compared and the
comparison is equal to the last character of the shorter
string
– The shorter string is less than the larger string

84
string in C++

string str1 = "Hello";


string str2 = "Hi";
string str3 = "Air";
string str4 = "Bill";
string str5 = "Big";

What will be the output of…


str1 < str2; // true
str1 > “Hen”; // false bool out = 'H' < 'h';
str3 < “An”; // true std::cout << std::boolalpha<< out << std::endl;
str1 ==“hello”; // false
str3 <= str4; // true
str2 > str4; // true
Str4 >= “Billy”; //false
Str5 <= “Bigger” // true

You may need https://en.cppreference.com/w/cpp/language/ascii

85
String Concatenation

• The + operator can be used between two strings to make a


new string
• White space can also be concatenated.
string firstName = “Amit ";
string lastName = “Agarwal";
string fullName = firstName +
lastName;
cout << fullName;

• A string is an object, thus append() can also be used to


concatenate strings.
string firstName = “Amit ";
string lastName = “Agarwal";
string fullName
= firstName.append(lastName);
cout << fullName;

86
String Concatenation

• Append allows part of a string.


str1.append(str2, 0, 5);

What will be the output of…

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

• String index starts at 0 (i.e., first character)


• The characters in the string can be accessed using index
numbers inside [ ]
What will be the output of…

string myString = "Hello";


cout << myString[1]; // output →??

• It can also replace the existing character


What will be the output of…

string myString = "Hello";


myString[0] = 'J';
cout << myString;

88
String inserting and erasing
string s1("Miss Summer");
s1.insert(5, "Ashley "); // Insert at position: 5

string s(“The summer-time");


s.erase(4,7); // position: 4, quantity 7

89
String Access

• Taking a string as input with whitespace in it.

What will be the output of…

string name;
cin >> name; // Enter “Amit Agarwal”
cout << name;

• cin considers a space (whitespace, tabs, etc.) as a terminating


character, which means that it can only display a single word

What will be the output of…

string name;
cout << "Enter your name" <<endl;
getline (cin, name);
cout << name;

90
Thanks …
amitfce@iitr.ac.in

91

You might also like