C Basics v3 PDF
C Basics v3 PDF
TRANSPORTATION
Introduction and basics
Principles
http://aturingmachine.com
What is an algorithm?
• An algorithm is a sequence of unambiguous instructions for solving a
problem, i.e., for obtaining a required output for any legitimate input
in a finite amount of time
• The instructions are in some language:
• I will teach you (a little) C++;
• the compiler translates those languages
to machine language
https://en.wikipedia.org/wiki/List_of_programming_languages
http://codetojoy.blogspot.com/2007/07/seven-wonders-of-programming-languages.html
The right language is not all
• Python with quicksort algorithm: elapsed time becomes 0.0021 s
• Can you choose a language that has the right tools?
Python is way better than C++ for text processing and file manipulation.
• Is your algorithm part of a standard library or a library you can download/buy?
Millions of programmers, just like you, have needed linear algebra algorithms.
Most of what you could need already exists!
http://www.hpc.cineca.it/content/introduction-object-oriented
https://www.geeksforgeeks.org/the-c-standard-template-library-stl/
https://en.cppreference.com/w/cpp/links
http://www.open-std.org/jtc1/sc22/wg21/docs/standards
Details
• C++ is standardized as ISO/IEC 14882. Currently, there are two versions:
• C++98 (ISO/IEC 14882:1998): First standard version of C++.
• C++03 (ISO/IEC 14882:2003): minor "bug-fix" to C++98 with no change to the language. Commonly
refer to as C++98/C++03 or First C++ standard.
• C++11 (ISO/IEC 14882:2011): Second standard version of C++. Informally called C++0x, as it
was expected to finalize in 200x but was not released until 2011. It adds some new features
to the language; more significantly, it greatly extends the C++ standard library and standard
template library (STL).
• C++14: Infomally called C++1y, is a small extension to C++11, with bug fixes and small
improvement.
• C++17: informally called C++1z.
• C++2a: the next planned standard in 2020.
Clean coding principles
• Use meaningful names (Try to figure out what f14() does)
• Code should be clear: Keep It Simple, Student (KISS)!
• Program units should have one clear function (Micorservices)
• Any functionality should be implemented only once:
Don't Repeat Yourself
The output
The program
http://harmful.cat-v.org/software/c++/linus
http://www.stroustrup.com/ieee_interview.html
Rules for Developing Safe, Reliable, and Secure Systems
• There are rules to help programmers ensure that their C++ code
reduces security flaws by following secure coding best practices
https://www.securecoding.cert.org./confluence/pages/viewpage.action?pageId=88046682
• An example
Visual studio: tutorials…
https://tutorials.visualstudio.com/cpp-console/intro
https://visualstudio.microsoft.com/it/vs/getting-started/
https://blogs.msdn.microsoft.com/vcblog/2017/04/21/getting-started-
with-visual-studio-for-c-and-cpp-development/
File extensions
Edit, compile, run file.cc
Exercise: make a file with the following lines: file.cp
//#include “stdafx.h“ in visual studio file.cxx
#include <iostream> file.cpp
file.CPP
using namespace std;
file.c++
int main() { file.C
return 0; C++ source code
}
and compile it. file.h
file.hh
Run this program (it gives no output). file.H
file.hp
file.hxx
Add this line
file.hpp
file.HPP
cout << "Hello world!" << endl; file.h++
//system(“pause“); if the output window closes file.tcc
immediately
C++ header file
Details
• MAIN: In C the main function is always a free function that appears outside the context of any
class. in Java everything appears within the context of a class. C++ is an object-oriented
language like Java, but not everything in C++ is required to be object oriented.
• Include statements: System includes are denoted by the use of angle brackets around the
included file name and are used to import declarations related to the C++ standard library and
other resources. User includes are denoted by quote marks around the included file name are
used to import declarations stored in header files
#include <string>
#include "Example.h"
• Comments
//single row
/* ….. */
• Keywords (main, for, return…)
Details - Namespaces
• Java uses the package mechanism to reduce the potential for name conflicts. All classes are
required to belong to a package. Two classes with the same name can coexist, as long as the
two classes belong to separate packages.
• C++ namespaces serve the same purpose. To create a namespace
namespace MyStuff { // Declare classes, functions, and variables in here }
Since we are mostly going to be writing small programs in this course we won't need to create
namespaces frequently. Items that are not explicitly declared in a namespace land in the global
namespace.
• If you want to use something that was declared inside a namespace you have to do one among
1. std::string str = "Some text";
2. using std::string; // Import string from the std namespace, at the beginning or within a function body
3. using namespace std; // Imports names from the entire std space
• With 2 and 3 then
string str = "Some text"; // Now we can use string without std::
Details – I/O
• In C++ the expectation is that programmers will frequently write applications
that use text input and output in a console window. Consequently, C++ makes
it much easier to write console applications.
• The basic mechanism for doing text input and output is the iostreams facility.
To use this facility, you place the include statement
#include <iostream>
at the top of any source file where you want to do text input and/or output.
• To do text output, use the std::cout object in combination with the stream
injection operator <<. The endl output manipulator causes a line break in the
output, so that the next thing that gets output appears on the following line in
the output.
int x = 5; float y = 6.3;
std::cout << "x is " << x << " and y is " << y << std::endl;
A first example
Main: int or void?
• Normal exit is generally represented by 0.
• Abnormal termination is a non-zero value.
But there is no standard for how non-zero codes
are interpreted…
A second example
You can declare variables “everywhere” in the code.
• A long literal is identified by a suffix 'L' or 'l' (avoid lowercase, which can be confused with the
number one). A long long int is identified by a suffix 'LL'. You can also use
suffix 'U' for unsigned int, 'UL' for unsigned long, and 'ULL' for unsigned long long int.
Literals (i.e. specific constant values)
• A number with a decimal point, such as 55.66 and -33.44, is treated as
a double, by default. You can also express them in scientific notation,
e.g., 1.2e3, -5.5E-6, where e or E denotes the exponent in power of 10.
You could precede the fractional part or exponent with a plus (+) or minus
(-) sign. Exponent shall be an integer. There should be no space or other
characters (e.g., space) in the number.
• You MUST use a suffix of 'f' or 'F' for float literals, e.g., -1.2345F. For
example,
• float average = 55.66; // Error! RHS is a double. Need suffix 'f' for float.
• float average = 55.66f;Use suffix 'L' (or 'l') for long double.
Operations
• A printable char literal is written by enclosing the character with a pair
of single quotes, e.g., 'z', '$', and '9'. In C++, characters are represented using
8-bit ASCII code, and can be treated as a 8-bit signed integers in arithmetic
operations. In other words, char and 8-bit signed integer are
interchangeable. You can also assign an integer in the range of [-128, 127] to
a char variable; and [0, 255] to an unsigned char.
• char letter = 'a'; // Same as 97
• char anotherLetter = 98; // Same as the letter 'b’
• cout << letter << endl; // 'a' printed
• cout << anotherLetter << endl; // 'b' printed instead of the number
• anotherLetter += 2; // 100 or 'd’
• cout << anotherLetter << endl; // 'd' printed
• cout << (int)anotherLetter << endl; // 100 printed
Special form
• Update:
x = x+2; y = y/3;
// can be written as
x += 2; y /= 3;
• Integer add/subtract one:
i++; j--; /* same as: */ i=i+1; j=j-1;
• Pre/post increment:
x = a[i++]; /* is */ x = a[i]; i++;
y = b[++i]; /* is */ i++; y = b[i];
A third example
Input/output manipulators
• boolalpha | noboolalpha :
switches between textual and numeric representation of booleans
• showpos | noshowpos :
controls whether the + sign used with non-negative numbers
• dec | hex | oct :
changes the base used for integer I/O
• setw :
changes the width of the next input/output field
• fixed | scientific :
changes formatting used for floating-point I/O
• left | right :
sets the placement of fill characters
• Uppercase | nouppercase :
controls whether uppercase characters are used for exadecimal
and exponent
Exercise
• Write a program that has several variables.
• Assign values either in an initialization or in an assignment.
• Print out the values.
• Check overflows condition.
Solution - overflow
Expressions
• Expression looks pretty much like in math.
• With integers: 2+3
• with reals: 3.2/7
• Use parentheses to group 25.1*(37+42/3.)
• There is no `power' operator: library functions. Needs a line
• #include <cmath>
• http://www.cplusplus.com/reference/cmath/
• Modulus: %
• 5 % 2 → 1; -5 % 2 → -1
Expressions
Careful with types
• double pow (double base , double exponent);
• float powf (float base , float exponent);
• long double powl (long double base, long double exponent);
• You cannot omit the multiplication symbol '*’
is (1+2*a)/3 + (4*(b+c)*(5-d-e))/f - 6*(7/g+h).
Correct version
Exercise
Converting between Celsius and Fahrenheit:
• Get a value in input
• Get if C or F
• Celsius = (5/9)(Fahrenheit–32)
• Fahrenheit = (9/5)Celsius+32
Solution
Don’t mix int and double!
• YES Double(9)/double(5)
• YES 9.0/5.0
• NO double (9/5)
Expressions
BOOLEAN
• Testing: == != < > <= >=
• Not, and, or: ! && ||
• if ( x>=0 && sqrt(x)<5 ) {}
BITWISE
• Bitwise: & | ^
• Bitwise operators are good for saving space
Arrays
• An array is a list of elements of the same type, identified by a pair of
square brackets [ ].
• To use an array, you need to declare the array with 3 things:
a name, a type and a dimension (or size, or length).
• The syntax is: type arrayName[arraylength];
• arraylength can be a literal or a variable
Arrays
• ATTENTION: you need to known the length (or size) of the array in advance, and
allocate accordingly. Once an array is created, its length is fixed and cannot be
changed. At times, it is hard to ascertain the length of an array (e.g., how many
students in a class?).
• This is probably the major drawback of using an array. C++ has a vector template
class (and C++11 added an array template class), which supports dynamic
resizable array. Otherwise use POINTERS.
• C/C++ does not perform array index-bound check. In other words, if the index is
beyond the array's bounds, it does not issue a warning/error. For example,
• int numbers[5];
// Can compiled and run, but could pose very serious side effect!
numbers[88] = 999;
cout << numbers[77] << endl; // What happens? Try it
Arrays
// Declare and initialize an int array of 3 elements
int numbers[3] = {11, 33, 44};
// If length is omitted, the compiler counts the elements
int numbers[] = {11, 33, 44};
// Number of elements in the initialization shall be equal to or less than length
int numbers[5] = {11, 33, 44}; // Remaining elements are zero. Confusing! Don't do this
int numbers[2] = {11, 33, 44}; // ERROR: too many initializers
// Use {0} or {} to initialize all elements to 0
int numbers[5] = {0}; // First element to 0, the rest also to zero
int numbers[5] = {}; // All element to 0 too
Multi-dimensional array
• int[2][3] = { {11, 22, 33}, {44, 55, 66} };
• For 2D array (table), the first index is the row number, second index is the
column number. The elements are stored in a so-called row-
major manner, where the column index runs out first.
• Pay attention to the performance!
• Use linear array:
Declare a[rows*cols]
p[ (1*cols) + 2] = 1
//equivalent to a[1][2] = 1;
Strings
• C++ supports two types of strings:
• the original C-style string: A string is a char array, terminated with
a NULL character '\0' (Hex 0). It is also called Character-String or C-style string.
• the new string class introduced in C++98. Later..
• The "high-level" string class is recommended, because it is much
easier to use and understood. However, many legacy programs used
C-strings; many programmers also use "low-level" C-strings for full
control and efficiency; furthermore, in some situation such as
command-line arguments, only C-strings are supported. Hence, you
may have to understand both sets of strings. However, avoid C-string
unless it is absolutely necessary.
C-String
A string is a char array terminated by a NULL character '\0'
Example
Structures
• structure is another user defined data type which allows you to
combine data items of different kinds.
• Structures are used to represent a record: suppose you want to keep
track of your books in a library.
• struct [structure tag] {
member definition;
...
member definition; } [one or more structure variables];
Pointers
3 3 0x1514010
4 4 0x1514014
5 5 0x1514018
0 0x1514014
Pointers and structures
"switch-case" is an alternative to the "nested-if". You can use either an int or char variable as the case-selector.
In a switch-case statement, a break statement is needed for each of the cases. If break is missing, execution will flow
through the following case.
Conditional Operator: A conditional operator is a ternary (3-operand) operator, in the form
booleanExpr ? trueExpr : falseExpr.
max = (a > b) ? a : b;
abs = (a > 0) ? a : -a;
Loop flow
The difference between while-do and do-while lies in the order of the body and condition.
In while-do, the condition is tested first. The body will be executed if the condition is true and the process
repeats. In do-while, the body is executed (at least once ) and then the condition is tested.
Interrupting Loop Flow - "break" and "continue"
• The break statement breaks out and exits the current (innermost) loop.
• The continue statement aborts the current iteration and continue to the next iteration of the current loop.
• These are poor structures as they are hard to read and hard to follow. Different solutions exist.
Command-line arguments
• The full declaration of main looks like this:
int main ( int argc, char *argv[] )
• The integer, argc is the ARGument Count (hence argc). It is the
number of arguments passed into the program from the command
line, including the name of the program.
• The array of character pointers is the listing of all the arguments.
argv[0] is the name of the program. After that, every element number
less than argc is a command line argument.
• You can use each argv element just like a string, or use argv as a two
dimensional array.
Example
#include <iomanip> test\a.exe "Peter Piper" picked a
#include <iostream> peck of "pickled peppers "
using namespace std;
The name used to start the program:
test\a.exe
int main( int argc, char* argv[] )
Arguments are:
{ 1: Peter Piper
cout << "The name used to start the program: " << argv[ 0 ] 2: picked
<< "\nArguments are:\n"; 3: a
for (int n = 1; n < argc; n++) 4: peck
5: of
cout << setw( 2 ) << n << ": " << argv[ n ] << '\n';
6: pickled peppers
return 0;
}
Exercise
• Take in input via shell 3 parameters: number1 number2 operation
(*+-/)
• Perform the operation and print to the screen the resut
• Use
• Argc and argv (slide 80)
• Switch (slide 76)
• atoi(argv[1]) and include cstdlib
• Op = argv[3][0]
#include "stdafx.h"
#include <iostream>
Solution cout << "The result of " << op << " is: ";
#include <cstdlib>
using namespace std; switch (op) {
case '+':
cout << x + y << endl; break;
int main(int argc, char* argv[]) { case '-':
if (argc != 4) { cout << x - y << endl; break;
cout << "usage: program num1 num2 op" case '*':
<< endl; cout << x * y << endl; break;
system("pause"); case '/':
return -5; cout << x / y << " (and % " << x%y << " ) " << endl; break;
} default:
cout << "Wrong operation\n"; break; return -6;
}
int x = atoi(argv[1]);
int y = atoi(argv[2]); system("pause");
char op = argv[3][0]; return 0;
}