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

Week 1 - Introduction To C++ and Competitive Coding-1694802070673 3

Uploaded by

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

Week 1 - Introduction To C++ and Competitive Coding-1694802070673 3

Uploaded by

6y8zpdmjr4
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Intro To C++ and Competitive

Programming
Instructors :
Jatin Dahiya 8447218319
Krishna Sethiya 9109152231
Pratyush Suvarna 8828183656
Hridya Arora 7988005035
Objective of this course.

● Teach students basic syntax and techniques in c++ to start their


programming journey.
● Make students familiar with algorithms used in Competitive Programming,
all the way from basics to some intermediate ones.
● Give students a glimpse of the cp world, through questions and
assignments, even mock contests if time permits.
● Motivate and make you capable of pursuing cp after this course.
● The C++ Programming
Language - Bjarne Stroustrup

● AlgoManiaX CP Guide:

Materials bp-gc.in/algox-cp-guide

● Geeks for Geeks (website)

● freeCodeCamp (youtube)
Timeline
Learn a basic data
Learn the basics of structure, strings and
C++ and be able to be able to calculate Learn some advanced
write simple time complexity of a algorithms and
programs. program. number theory.

Week 1 Week 2 Week 3 Week 4-5 Week 6-8

Learn some basic


Learn conditional algorithms and C++
branching and STL for more data
functions. structures.
Why Use C++ ?

● Conciseness:
Programming languages allow us to express
common sequences of commands more concisely.
C++ provides some especially powerful shorthands.

● Maintainability:
Modifying code is easier when it entails just a few
text edits, instead of rearranging hundreds of
processor instructions.

● Portability:
Different processors make different instructions
available. Programs written as text can be
translated into instructions for many different
processors; one of C++’s strengths is that it can be
used to write programs for nearly any processor.
Hello World!

Output:
Tokens

● Tokens are the minimals chunk of program that have meaning to the compiler – the smallest
meaningful symbols in the language.
● Our code displays all 6 kinds of tokens, though the usual use of operators is not present here:
Line-By-Line Explanation

1. // indicates that everything following it until the end of the line is a comment: it is ignored by the
compiler. Another way to write a comment is to put it between /* and */

eg

A comment of this form may span multiple lines. Comments exist to explain non-obvious things
going on in the code.
Use them: document your code well!

2. Lines beginning with # are preprocessor commands, which usually change what code is actually
being compiled.

#include tells the preprocessor to dump in the contents of another file, here the iostream file,
which defines the procedures for input/output.
Line-By-Line Explanation

4. int main() {...} defines the code that should execute when the program starts up.

The curly braces represent grouping of multiple commands into a block. More about this syntax in
the next few lectures.

5.
cout << : This is the syntax for outputting some piece of text to the screen.

Namespaces: In C++, identifiers can be defined within a context – sort of a directory of names – called
a namespace.
When we want to access an identifier defined in a namespace, we tell the compiler to look for it in that
namespace using the scope resolution operator (::).
Here, we’re telling the compiler to look for cout in the std namespace, in which many standard C++
identifiers are defined.
Line-By-Line Explanation

A cleaner alternative is to add the following line below line 2:


using namespace std;

● This line tells the compiler that it should look in


the std namespace for any identifier we haven’t
defined. If we do this, we can omit the std::
prefix when writing cout.

This is the recommended practice.

Strings: A sequence of characters such as Hello, world is known as a string.


A string that is specified explicitly in a program is a string literal.
Line-By-Line Explanation

Escape sequences: The \n indicates a newline character.


It is an example of an escape sequence – a symbol used to represent a special character in a text literal.
Here are all the C++ escape sequences which you can include in strings:
Line-By-Line Explanation

7. return 0 indicates that the program should tell the operating system it has completed
successfully. This syntax will be explained in the context of functions; for now, just include it as the last
line in the main block.

Note that every statement ends with a semicolon (except preprocessor commands and blocks
using {}).

Forgetting these semicolons is a common mistake among new C++ programmers.


Values and Statements

First, a few definitions:


• A statement is a unit of code that does something – a basic building block of a program.

• An expression is a statement that has a value – for instance, a number, a string, the
sum of two numbers, etc.

4 + 2, x - 1, and "Hello, world!\n" are all expressions.

Not every statement is an expression.

It makes no sense to talk about the value of an #include statement, for instance.
Operators

We can perform arithmetic calculations with operators.

Operators act on expressions to form a new expression.

For example, we could replace "Hello, world!\n" with (4 + 2) / 3, which would cause the program to
print the number 2. In this case, the + operator acts on the expressions 4 and 2 (its operands).

● Operator types:

• Mathematical: +, -, *, /, and parentheses have their usual mathematical meanings,


including using - for negation. % (the modulus operator) takes the remainder of two
numbers: 6 % 5 evaluates to 1.

• Logical: used for “and,” “or,” and so on. More on those later.

• Bitwise: used to manipulate the binary representations of numbers. We will not focus
on these for now.
Data Types

Every expression has a type – a formal description of what kind of data its value is.
For instance, 0 is an integer, 3.142 is a floating-point (decimal) number, and "Hello, world!\n" is a string
value (a sequence of characters).

Data of different types take a different amounts of memory to store. Here are the built-in datatypes we
will use most often:
Data Types

Notes on this table:

● A signed integer is one that can represent a negative number; an unsigned integer will
never be interpreted as negative, so it can represent a wider range of positive numbers.
Most compilers assume signed if unspecified.

● There are actually 3 integer types: short, int, and long, in non-decreasing order of
size (int is usually a synonym for one of the other two). You generally don’t need to
worry about which kind to use unless you’re worried about memory usage or you’re
using really huge numbers. The same goes for the 3 floating point types, float, double,
and long double, which are in non-decreasing order of precision (there is usually some
imprecision in representing real numbers on a computer).

● The sizes/ranges for each type are not fully standardized; those shown above are the
ones used on most 32-bit computers.
Data Types

● An operation can only be performed on compatible types. You can add 34 and 3, but you
can’t take the remainder of an integer and a floating-point number.

● An operator also normally produces a value of the same type as its operands; thus, 1 / 4
evaluates to 0 because with two integer operands, / truncates the result to an integer.
To get 0.25, you’d need to write something like 1 / 4.0.
Variables

● We might want to give a value a name so we can refer to it later. We do this using variables.
A variable is a named location in memory.

● For example, say we wanted to use the value 4 + 2 multiple times. We might call it x and
use it as follows:

(Note how we can print a sequence of values by “chaining” the << symbol.)
Variables

The name of a variable is an identifier token.


Identifiers may contain numbers, letters, and underscores (_), and may not start with a number.

● Line 5 is the declaration of the variable x. We must tell the compiler what type x will be so that it
knows how much memory to reserve for it and what kinds of operations may be performed on it.

● Line 6 is the initialization of x, where we specify an initial value for it. This introduces a
new operator: =, the assignment operator. We can also change the value of x later on in the
code using this operator.

We could replace lines 5 and 6 with a single statement that does both declaration and initialization:

This form of declaration/initialization is cleaner, so it is to be preferred.


Input

Now that we know how to give names to values, we can have the user of the program input
values. This is demonstrated in line 6 below:

Just as cout << is the syntax for outputting values,


cin >> (line 6) is the syntax for inputting values.

Memory trick: If you have trouble remembering which way the angle brackets go for cout and cin, think
of them as arrows pointing in the direction of data flow. cin represents the terminal, with data flowing
from it to your variables; cout likewise represents the terminal, and your data flows to it.
Debugging

There are two kinds of errors you’ll run into when writing C++ programs: compilation
errors and runtime errors.

Compilation errors are problems raised by the compiler, generally resulting from violations of the
syntax rules or misuse of types. These are often caused by typos and the like.

Runtime errors are problems that you only spot when you run the program: you did specify a legal
program, but it doesn’t do what you wanted it to. These are usually more tricky to catch, since the
compiler won’t tell you about them.
Eg. logic error, a division by zero error.
Flow Of Control

Normally, a program executes statements from first to last.


The first statement is executed,then the second, then the third, and so on, until the program reaches its
end and terminates.
A computer program likely wouldn't be very useful if it ran the same sequence of statements every
time it was run.
It would be nice to be able to change which statements ran and when, depending on the
circumstances.

For example, if a program checks a file for the number of times a certain word appears, it should be
able to give the correct count no matter what file and word are given to it.
Or, a computer game should move the player's character around when the player wants. We need to be
able to alter the order in which a program's statements are executed, the control flow.
Control Structures

Control structures are portions of program code that contain statements within them and, depending on the
circumstances, execute these statements in a certain way.
There are typically two kinds: conditionals and loops.

1. Conditionals
In order for a program to change its behavior depending on the input, there must a way to test that input.
Conditionals allow the program to check the values of variables and to execute (or not execute) certain
statements. C++ has if and switch-case conditional structures.
Control Structures

1.1 Operators
Conditionals use two kinds of special operators: relational and logical.
These are used to determine whether some condition is true or false.

The relational operators are used to test a relation between two expressions:
Control Structures

They work the same as the arithmetic operators (e.g., a > b) but return a Boolean value of
either true or false, indicating whether the relation tested for holds. (An expression that
returns this kind of value is called a Boolean expression.)

For example, if the variables x and y have been set to 6 and 2, respectively, then x > y returns true.
Similarly, x < 5 returns false.

The logical operators are often used to combine relational expressions into more complicated
Boolean expressions:
Control Structures

The operators return true or false, according to the rules of logic:

The ! operator is a unary operator, taking only one argument and negating its value:
Control Structures

Examples using logical operators (assume x = 6 and y = 2):

Of course, Boolean variables can be used directly in these expressions, since they hold true
and false values.

In fact, any kind of value can be used in a Boolean expression due to a quirk C++ has:
false is represented by a value of 0 and anything that is not 0 is true.

So, “Hello, world!” is true, 2 is true, and any int variable holding a non-zero value is true.
This means !x returns false and x && y returns true!
Control Structures

1.2 if, if-else and else if

The if conditional has the form:


The condition is some expression whose value is being tested.

If the condition resolves to a value of true, then the statements are


executed before the program continues on.

Otherwise, the statements are ignored.

If there is only one statement, the curly braces may be omitted, giving the form:
Control Structures

The if-else form is used to decide between two sequences of statements referred to as blocks:

If the condition is met, the block corresponding to the if is executed.

Otherwise, the block corresponding to the else is executed.

Because the condition is either satisfied or not, one of the blocks in an


if-else must execute.

If there is only one statement for any of the blocks, the curly braces for that block may be omitted:
Control Structures

The else if is used to decide between two or more blocks based on multiple conditions:

If condition1 is met, the block corresponding to the if is executed. If not, then


only if condition2 is met is the block corresponding to the else if executed.

There may be more than one else if, each with its own condition. Once a block
whose condition was met is executed, any else ifs after it are ignored.

Therefore, in an if-else-if structure, either one or no block is executed.

An else may be added to the end of an if-else-if.

If none of the previous conditions are met, the else block is executed. In this structure, one of the
blocks must execute, as in a normal if-else.
Control Structures

Here is an example using these control structures:


Control Structures

2. Loops
Conditionals execute certain statements if certain conditions are met; loops execute certain
statements while certain conditions are met. C++ has three kinds of loops: while, do-while,
and for.
Control Structures

2.1 while and do-while

The while loop has a form similar to the if conditional:

As long as condition holds, the block of statements will be repeatedly executed. If there is only
one statement, the curly braces may be omitted.
Control Structures

Here is an example:

This program will print x is 10.


Control Structures

The do-while loop is a variation that guarantees the block of statements will be executed at
least once:

The block of statements is executed and then, if the


condition holds, the program returns to the top of the
block.

Curly braces are always required.

Also note the semicolon after the while condition.


Control Structures

2.2 for
The for loop works like the while loop but with some change in syntax:

The for loop is designed to allow a counter variable that is initialized at the beginning of the
loop and incremented (or decremented) on each iteration of the loop.

Curly braces may be omitted if there is only one statement.


Control Structures

Here is an example:

Output:
Control Structures

If the counter variable is already defined, there is no need to define a new one in the
initialization portion of the for loop.

Therefore, it is valid to have the following:

Output:

Note that the first semicolon inside the for loop's parentheses is still required.
Control Structures

A for loop can be expressed as a while loop and vice-versa.

Recalling that a for loop has the form: we can write an equivalent while loop as
Control Structures

Using our example above,

is converted to

The incrementation step can technically be anywhere inside the statement block, but it is good
practice to place it as the last step, particularly if the previous statements use the current value of the
counter variable.
Control Structures

2.3 Nested Control Structures


It is possible to place ifs inside of ifs and loops inside of loops by simply placing these
structures inside the statement blocks.
This allows for more complicated program behavior.

Here is an example using nesting if conditionals:

Output:
Control Structures

Here is an example using nested loops:

Output:

You might also like