CMU Statistics Summer Computing 2013 Day 2: Introduction to C/C++
|
|
- Meagan Holt
- 5 years ago
- Views:
Transcription
1 1) QH1 Problems 1 to 3 CMU Statistics Summer Computing 2013 Day 2: Introduction to C/C++ 2) QH1 Problem 4: Setting up C and quick intro to C 3) Preview of HW1 and discussion of documentation (suggest viewing draft R coding conventions) 4) C is a compiler that converts your source code into native machine language for whichever operating system and computer architecture you are using. Therefore it is fast! It requires more work and skill than R (an interpreter rather than a compiler) and is far more dangerous, e.g., it is easy to change variables accidentally. 5) C++ is an object oriented compiler that adds many high level features to C (especially features similar to objects and methods in R). It is a bit harder to learn the C, but tends to be much safer. Its speed is close to C (use of safer features does tend to slow it down some). It allows more complex programming that C with fewer lines of code. It is often a better choice than C when you are writing complex code, particularly with complex, user defined data types. We will use C++ because if you happen to need any of it s features, it will be easy to add them to your existing code. 6) I will assume that you are using GNU g++. Besides being free, well maintained, well documented ( widely used, and widely accepted, it has the GNU Scientific Library (GSL) and support for the best matrix algebra system (BLAS). It is on the department machines and may already be on your Mac. If you have a Windows PC, the options include a. install the mingw version of GNU C on your PC b. install Visual C++ (expensive but very good) or Visual C++ Express (free with some limitations) c. SSH into a Department or University Linux computer (also a Mac choice). 7) Quick Unix/Linux primer a. ssh into unix.andrew.cmu.edu or another machine, allowing security as needed. b. Commands and file names are case sensitive! c. Directory levels are separated by slash not back-slash. Tilde (~) at the beginning of a file name starts at your home directory. Slash (/) starts at the computer s home directory. E.g., ls ~/projects/ shows the files in the projects subdirectory of your home directory and ls /bin shows the files in the system bin directory. 1
2 d. Environmental variables hold key information. The printenv command shows the current values. The value of the PATH variable indicates where programs will be looked for. Use setenv myvar myvalue to set a variable. e. Ending a command with & makes it run independently, so your terminal is not tied up and you get a new command prompt to run other things simultaneously. f. Basic commands are i. List files in the current ( working ) directory: ls ii. Print working directory: pwd iii. Change directories (absolute or relative): cd 1. Starting with ~ or / is absolute, e.g., ls ~ 2.../ goes up one level form the current location, e.g., ls../over 3. subdirname goes down a level, e.g., ls mysub iv. Make a new directory (absolute or relative): mkdir v. Rename or move a file: mv, e.g., mv old new or mv old.. vi. Delete a file: rm vii. Edit a file: xemacs myfile & viii. Run a program in your path: progname & ix. Run a program in your current directory:./progname & x. List currently running jobs: jobs xi. Kill currently running job #1: kill %1 xii. Filename completion with tab. Ctrl-a / ctrl-e to start / end of line. 8) Here are the steps to writing a program in C++ a. Plan your program and testing procedures. Break down the problem into a main program and useful functions. Consider details of input and output including command line arguments. b. Using a text editor create the main() function and all of the additional functions, usually in separate.cpp files (.c for plain c). Create.h header files with macros, prototypes and includes as needed. Much of C++ functionality is not built in per se, but comes from libraries, and you must include the corresponding header files to have access to named constants and appropriate function prototypes. Include appropriate commenting. 2
3 c. Compile each.cpp (or.c) file using -Wall warning level. Correct syntax errors and warnings. A sample command is g++ -c -Wall myfile1.cpp, and this produces the object file myfile1.o. (Correct syntax errors and re-run.) d. Link the object files together with the standard library and any necessary additional libraries to create the executable program. (The last two steps are greatly facilitated by a make file.) A sample command is g++ -o myprog myfile1.o myfile2.o and this produces the executable program myprog. (If you forget the -o outfile, the program will be called a.out.) e. Test and debug your program. (It s nice to add. to your PATH.) f. Simple first example: In a file named hello.cpp put: /* This is hello.cpp, a simple C++ program */ /* compile: g++ -c -Wall hello.cpp */ /* link: g++ -o hello hello.o */ /* run: hello */ #include <iostream> /* using namespace std; */ int main() { std::cout << "C++ rules!\n"; return(0); } Then at the Unix prompt type g++ -c -Wall hello.cpp to convert the source code to object code (assuming no syntax errors). Then at the Unix prompt type g++ -o hello hello.o to create the executable hello program from the object file hello.o and the standard C++ library functions. The hello file is run by typing hello at the Unix prompt (if your path does not include., you ll need./hello to run it), and what we see is: C++ rules! 9) Variables in C++ a. Your variable names (identifiers) must start with a letter, and then may be followed by up to 30 more letters and numbers plus underscore ( _ ). Identifiers are case sensitive. Make the names meaningful to aid others who may read your code (including your future self)! Here is a list of reserved keywords that cannot be used as variable names: i. C keywords: auto, const, double, float, int, short, struct, unsigned, break, continue, else, for, long, signed, switch, void, case, default, enum, goto, register, sizeof, typedef, volatile, char, do, extern, if, return, static, union, while ii. Additional C++ keywords: asm, dynamic_cast, namespace, reinterpret_cast, try, bool, explicit, new, static_cast, typeid, catch, false, 3
4 operator, template, typename, class, friend, private, this, using, const_cast, inline, public, throw, virtual, delete, mutable, protected, true, wchar_t, and, bitand, compl, not_eq, or_eq, xor_eq, and_eq, bitor, not, or, xor iii. Also, these, while not keywords, are pre-defined identifiers: cin, endl, INT_MIN, iomanip, main, npos, std, cout, include, INT_MAX, iostream, MAX_RAND, NULL, string b. Basic Variable Types i. char: one byte (8 bits) representing -128 to This can be interpreted as holding one standard ASCII character. These are represented as something like 'A', '4', and '\n', where the latter is the ASCII newline character (code 10). Note that the quotes must be single, and the contents must be only one character or a predefined '\*' symbol. ii. int: the natural size of an integer for the machine, typically 32 or 64 bits (4 or 8 bytes) on modern machines but not guaranteed to be bigger than 2 bytes. 32 bit integers go from -2,147,483,648 to 2,147,483,647. (The rarely used short int is allowed to be implemented in as few as 16 bits). iii. float: a single precision floating point number typically not used in statistical computing. These are 32 bit IEEE 754 representations with about 7 significant (decimal) figures. Float constants can be typed as decimals followed by the letter f, e.g., 3.4f. iv. double: a double precision floating point number using for representing non-integer numeric data in statistical computing. These are 64 bit (8 byte) IEEE 754 representations of real numbers or their best approximations. The format has approximately 16 significant (decimal) figures and a range of approximately 10 +/-308. Double constants can be typed as decimals (using a trailing.0 for whole numbers) or in scientific notation as, e.g., -3.45e-12. v. By default, the above are signed, but unsigned versions of char and int are available. The unsigned versions go from 0 to 255 and (for 32 bit systems) 0 to 4,294,967,295 (2 32-1). vi. Also, a long versions of int is available that is guaranteed to be at least 4 bytes. A long double is at least 8 bytes, but may use 10 or 16 bytes. vii. The header files <climits> and <cfloat> contains the actual limits for whichever system you are using. (Use, e.g., <float.h> in plain C.) viii. C++ also has wchar_t which is holds Unicode multi-byte text. ix. A const modifier makes a variable unchangeable, e.g. (from math.h), const double pi =
5 c. Pointer variables contain the location of another variable. You can add or subtract something from a pointer to get another pointer which may or may not point to appropriate information. Pointers are powerful and dangerous. You can create a pointer to: i. Any other variable, including a class object or another pointer ii. A function Pointer variables are declared to point to a specific type of variable, and incrementing or decrementing by 1 changes their value by the number of bytes of whatever it is pointing to (see sizeof() operator). This allows implementation of efficient one-dimensional arrays if an appropriate block of memory is available. The size of a pointer variable itself is the computer s word size: 32 or 64 bits. d. Structure variables are user defined complex data types, similar to lists in R. Union variables allow a stretch of memory to be interpreted in multiple ways. e. Classes such as string are a powerful C++ improvement over structures. String class objects are easier to manipulate and less subject to misuse (though a bit slower) than c style strings which are really a character array with a terminating NULL (ASCII 0) character. They may contain various data elements and functions that operate on those data elements. f. Using variables i. A variable declaration introduces an identifier (variable) and describes its type: native data type, object, or function. A declaration is what the compiler needs to accept references to an identifier that is defined elsewhere. Unless the variable is defined somewhere in your program, the code will compile, but fail at linkage time. Multiple (identical) declarations for the same variable are allowed. A declaration must occur before the first use of a variable in any program unit. ii. A variable definition actually instantiates/implements an identifier. It is what the linker needs in order to link references to those entities. It tells the compiler to allocate space for variables and optionally how to initialize the variables. Each full program must define each variable exactly once. All definitions are also declarations. 5
6 iii. The form type identifier; is used to declare a variable of a given type with a specific name. When used with native data types, this form is also a definition (without initialization). Also type identifier = initialvalue; is a definition with initialization. The alternate form extern type identifier; ensures that the statement is just a declaration. For functions and classes, the extern is optional and the lack of a body for the function or class is enough to ensure that the statement is only a declaration. A class or function definition is of the form class identifier {body}; or returntype function(argument list) identifier {body};. Here are some definitions: int numkids; double height = 3.4; char first_letter = A ; double function sqr(double x) { return(x*x); } And here are some declaration examples: extern double height; extern char first_letter; double function(double x); The last declaration is also called a function prototype. iv. A pointer is declared or defined using an asterisk: int *pkidnum; /* int* pkidnum is also allowed */ double *pheight; double (*pfun)(int); /* pointer to function with int argument and double return */ v. An array is defined using square brackets: int kidspersubject[numsubjects]; double riverlengths[3]; char name[17]; /* 16 char. name + terminator */ char names[nsubjects][17]; The array variable is a pointer to a block of memory. You cannot be sure what the initial values are with the above forms. Arrays can be initialized at definition like this: double myarray[3] = { 0.0, 0.0, 0.0 }; Declarations to arrays use empty brackets: extern double myarray[ ]; or equivalently: extern double *myarray; 6
7 Future references with [ ] access elements, numbered 0 to length-1. Future references without the [ ] are pointers to the first element. Multidimensional arrays are simulated. E.g., in the above example of an array of length nsubjects, each element is an array of length 17. The variable name itself is a pointer to an array of nsubjects pointers each of which points to a character array of length 17. C-style strings (as opposed to C++ strings from the string class) are an array of characters terminated by a '\0' (ASCII code 0) null character. They may be initialized using double quotes: int name[ ] = "Hello"; This creates a memory block with 6 bytes including the terminal null. It can be change to hold any string up to 5 characters long. You can also use, e.g.: int name[256] = "Hello"; to hold any string up to 255 characters long. vi. Dynamic memory allocation uses the keyword new : int * array_of_ints;... array_of_ints = new int[5000];... delete [] array_of_ints;... array_of_ints = new int[10000]; The first statement allocates a single uninitialized pointer to a potential array of integers. The new statement allocates space for 5000 integers and sets the pointer to point to them. The delete statement returns the memory to the operating system. The second new allocates a new, larger block of space. If the dynamic memory allocation does not occur within a try/catch block, the program ends with the message terminate called after throwing an instance of 'std::bad_alloc'. An alternate approach if you want to internally recover from an attempt to allocate too much memory is: double *ages = new (nothrow) double[nsubjects]; The added (nothrow) will cause the pointer to be equal to NULL if not enough memory is available, and you can test and die with a nice message if needed instead of using the more complex try/catch approach. 7
8 vii. Function declarations, also called function prototypes, tell the compiler how functions are defined in terms of the object type returned and the object type(s) of the arguments (if any). Functions may return type void, which is essentially returning nothing. Each file is compiled separately and should (must in most circumstances) be told the prototype of every function it calls (and may be told the prototype of functions it does not use without any penalty). Therefore, it is common, good practice to put all of the prototypes of your project into an include (.h) file and include that file at the top of every.cpp file in your project. Prototypes look like function definitions but have no function body. Examples are: double powerfun(double value, int power); char *wordreverser(char *word); void printinfo(char *word, int times, double v); Special syntax exists for a variable number of arguments. viii. Variables have a storage class which determines their lifetime, i.e., when they occupy memory during the program run. The storage classes are: 1. Automatic: allocated and initialized automatically when a function is called (includes parameters) and/or a braced { } block is entered, and automatically destroyed when these complete. The stack mechanism manages these automatic variables. 2. Static: allocated and initialized when the program starts, and destroyed when it ends. 3. Dynamically allocated: these data are stored on the heap. If you don t manage their pointers appropriately, memory fragmentation and/or leak will occur. (A garbage collector may help with this problem.) E.g., if you have an automatic local pointer in a function named *pdata, and you use new to assign to it the location of a dynamically allocated block of heap memory, and then the function returns to its caller without running delete [ ], that memory block will be orphaned until the program ends. ix. Variables have a scope, which is the portion of the program within which they are available. 1. Local variables are visible only within the function or smaller braced {} block where they are defined and are completely invisible if a nested {} block creates a new variable of the same name. They are also invisible when another function is entered. 2. Global variables are defined outside of any functions and are visible throughout the program. They are not directly available if another variable using the same name is in scope, but are indirectly available from everywhere using a form like ::myglobalvar. 3. Static variables have a scope limited to the function where they are defined using the static keyword prefix, but have a full program lifetime. 8
9 10) Functions in C/C++ use pass-by-value. This means that a copy of each argument from the calling program is passed to the function. Therefore the original value cannot be changed by the function. Normally some variable in the original program is changed by using the form var = function(var, othervar);. To change more than one variable in the calling function, you can pass a pointer to the variable, which gives the calling program full access to the original variable (but has some danger). In addition to the opportunity to use the pointer to any single variable, all arrays are passed by reference, i.e., the name of any array is really a pointer to the first value, so the called function, which receives a copy of the pointer, can modify it. Use const if you want to prevent the called function from potentially changing the array contents. 11) Source code in C++ consists of preprocessor directives, variable (data) declarations and definitions function prototypes (declarations), function definitions, and class declarations and definitions. Functions are not variables in the same way as they are in R. Instead, they are special primary objects, and most C++ code is just function and class definitions. 12) Almost all C++ programs contain some preprocessor directives. These start with # and do not end in a semicolon. The main directives are: a. #include <somestandardincludefile> or #include "myincludefile.h" which simply adds in the code of that file at the point of the directive b. #define IDENTIFIER VALUE to define either a macro or a constant c. #if/#ifdef/#ifndef/#elif/#else/#endif to include or exclude specific bits of code Although any valid C++ code be in the include file, typically it consists of constant definitions, macro definitions, declarations (including prototypes), and directives to include other include files. 13) Comments can occur anywhere and are bracketed by /* and */ in C or C++ or just preceded by // in C++. 14) C++ has a fairly small vocabulary. The keywords include those for function, class and variable declaration, those for program control (e.g., if/else, continue/break, for, switch/case/default, do/while), several used for casting, plus sizeof and return. 15) C/C++ code syntax: simple code lines end with a semicolon ( ; ) while complex ones consist of a series of semicolon-terminated simple commands enclosed in a set of curly braces ( { and } ). All practical functions consist of a single complex command. 9
10 16) Math is fairly standard, but be careful of integer arithmetic. doublevar = intvar/5; /* assigns 4.0 if intvar=24 */ doublevar = intvar/5.0; /* assigns 4.8 if intvar=24 */ Times and divide have higher precedence than add and subtract. A%B computes A modulo B. There is no power operator (but you can use the pow(x,y) function to compute x y ). Shortcut operators exist for changing variables directly: i++; /* is the same as i=i+1, while i--; subtracts 1 */ i+=3; /* adds 3 to i. *=, /= and -= also work */ Special bitwise operators are occasionally useful. The sizeof() operator finds the size of a variable or variable type in bytes. The dereferencing operator is *. If you declare pch to be a pointer to char, and if you set pch to point to some allocated memory, *pch refers to the character itself. The & operator extracts the address of a variable, i.e., it creates a pointer to the variable. The + and - operators (as well as ++, --, +=, and -=) work on pointers, so you can use: char string[] = " ABCDEF; char *palpha = string+10; // points to "ABCEDEF" char Dee, Eff; palpha +=3; // now points to "DEF Dee = *palpha; // Dee holds 'D' Eff = palpha[2]; // Eff holds 'F' 17) The keyword const can be used in definitions and declarations to help C++ help you avoid common errors. It assures that, after the initial definition some memory location(s) cannot be changed in the future. E.g., const int pi= ; assures that variable pi cannot be accidentally modified. As another example, const char * name; is a pointer to a c-style string that can be changed to point to a different string, but cannot be (accidentally) used to change any name because name[j]= K ; gives a compiler error. As an example, consider this code fragment: char name1[7] = "Howard"; char name2[8] = "Seltman"; const char *pc = name1; cout << "name1 is " << name1 << "\n"; pc = name2; // pc[3]='k'; // error: "assignment of read-only location" cout << "name2 is " << name2 << "\n"; 18) Casting is an important and somewhat confusing topic. It is similar to the as.xxx functions in R. a. Explicit casting: either I = int(d); or I = (int) d; takes the integer part of double d and stores it in I, truncated, not rounded. b. static_cast: I = static_cast<int>(d); is the newer way to do the above. 10
11 c. const_cast can be used (carefully) to reinterpret the const-ness of a variable. d. dynamic_cast performs run time checking for appropriateness, and is useful for complex use of classes. 19) Output to the terminal can be of the form: cout << "string text" << variable << "more" << another << "\n"; or if you really want to flush the terminal cout << "string text" << variable << "more" << another << endl; 20) Input from the keyboard can be of the form cin >> var; but this cause problems because it leaves everything after the first space for the next cin >> var statement. Usually you want to use something like: string intext; cout << "Enter an number> "; getline(cin, intext); d = atof(intext.c_str()); cout << "Your number is " << d << endl; The getline() function safely stores a line of input of any size in the C++ string class string intext (automatically allocating an appropriate amount of space). The c_str() string class member function returns a pointer to an old c-style string, which is what the atof() function needs to convert the text to a double (despite the fact that it should be named atod() ). There is no error checking, and numbers followed by non-numerics are read as the number, while initial non-numerics cause a zero result. 21) A good place to look for pre-defined functions to do whatever task you need is 22) Logical expressions can use ==,!=, <, >, <=, and >= as well as (),!(), &&, and some other operators. 11
12 23) The syntaxes for program control are: if (someexpression) somecommand; if (someexpression) { somecommands; } else if (otherexpression) { someothercommands; } else { evenmorecommands; } for (i=0; i<5; i++) { /* do something with i in {0,1,2,3,4) */ if (someexpression) continue; /* next i, without commands below */ if (otherexpression) break; /* leave the loop now! */ } switch (somevariable) { case somevalue: somecommands; break; case othervalue: othercommands; break;... default: defaultcommands; } while (someexpression) { commandspossiblydone; } do { commandsdoneatleastonce; } while (someexpression); 24) Include files and warnings #include <somename> /* loads from installed source code somewhere */ #include myinclude.h /* loads from the current directory */ If you use a function which has a prototype in an include file that you did not include, you ll get a warning like: arrtest.c:10: warning: implicit declaration of function exit arrtest.c:10: warning: incompatible implicit declaration of built-in function exit In Unix, just type man S3 exit to see that it is stdlib.h that you need to include. 12
13 25) Namespaces Namespaces are a feature designed to allow you to use functions, classes, and constants from several different libraries or different parts of one of your large projects, even if they happen to use the same name. Essentially, C++ actually uses a long name of the form namespace::function to refer to any of these. All of the built in functions are in the std namespace, so should be typed in as, e.g., as std::cout. The cheap, dirty, and slow way to handle this is to have a using namespace std; statement at the top of your file, after the #include s and before the main code. It s probably better to have several separate statements like using std::cout;, or even safer, explicitly type std::cout each time instead of importing the entire namespace. The namespaces control only what goes into the object files at compile time. If you refer to anything outside the standard library, you still need to tell the linker where to find those items at link time. 26) Command line arguments and return codes: The pre-defined arguments for the main() function are main(int argc, char **argv), and argc will be the argument count including the program name as argument 0. All arguments are stored as strings (char[ ]) and argv is a vector of these, so argv[1] is the first supplied argument and is in the form of a \0 terminated string. You can use atoi(argv[j]) or atof(argv[j]) to convert to int or double respectively. The value inside the final return(); is passed to the operating system when the program ends as the return code. By convention, you should return 0 if the program ends successfully and some non-zero code(s) if it fails. This allows shell scripts to do different things based on success or failure of your program. 27) Redirection of input and output Unix and command-line Windows allow a file or the output of another program to substitute for keyboard input and/or to capture terminal output. The syntax is: myprog <altinput.txt >altoutput.txt Also: myprog1 myprog2 > altoutput.txt uses the output of myprog1 as the input for myprog2. 13
Variables. Data Types.
Variables. Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable. We had to write several lines of code, compile them, and then execute the resulting
More informationUniversity of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.
University of Technology Laser & Optoelectronics Engineering Department C++ Lab. Second week Variables Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable.
More informationIntroduction to C++ Systems Programming
Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions
More informationBasic Types, Variables, Literals, Constants
Basic Types, Variables, Literals, Constants What is in a Word? A byte is the basic addressable unit of memory in RAM Typically it is 8 bits (octet) But some machines had 7, or 9, or... A word is the basic
More informationIntroduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts
Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter
More informationChapter 15 - C++ As A "Better C"
Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference
More informationIntroduction to Programming
Introduction to Programming session 6 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Spring 2011 These slides are created using Deitel s slides Sharif University of Technology Outlines
More informationNon-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words.
, ean, arithmetic s s on acters Comp Sci 1570 Introduction to C++ Outline s s on acters 1 2 3 4 s s on acters Outline s s on acters 1 2 3 4 s s on acters ASCII s s on acters ASCII s s on acters Type: acter
More informationAppendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things.
A Appendix Grammar There is no worse danger for a teacher than to teach words instead of things. Marc Block Introduction keywords lexical conventions programs expressions statements declarations declarators
More informationProgramming with C++ Language
Programming with C++ Language Fourth stage Prepared by: Eng. Samir Jasim Ahmed Email: engsamirjasim@yahoo.com Prepared By: Eng. Samir Jasim Page 1 Introduction: Programming languages: A programming language
More informationAPPENDIX A : KEYWORDS... 2 APPENDIX B : OPERATORS... 3 APPENDIX C : OPERATOR PRECEDENCE... 4 APPENDIX D : ESCAPE SEQUENCES... 5
APPENDIX A : KEYWORDS... 2 APPENDIX B : OPERATORS... 3 APPENDIX C : OPERATOR PRECEDENCE... 4 APPENDIX D : ESCAPE SEQUENCES... 5 APPENDIX E : ASCII CHARACTER SET... 6 APPENDIX F : USING THE GCC COMPILER
More informationBasics of C++ // my first program in C++ Hello World! #include <iostream> using namespace std; int main () { cout << "Hello World!
Basics of C++ // my first program in C++ Hello World! cout
More informationTokens, Expressions and Control Structures
3 Tokens, Expressions and Control Structures Tokens Keywords Identifiers Data types User-defined types Derived types Symbolic constants Declaration of variables Initialization Reference variables Type
More informationObjectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program
Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates
More informationChapter 2: Basic Elements of C++
Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates
More informationChapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction
Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers
More informationProgramming. C++ Basics
Programming C++ Basics Introduction to C++ C is a programming language developed in the 1970s with the UNIX operating system C programs are efficient and portable across different hardware platforms C++
More informationME240 Computation for Mechanical Engineering. Lecture 4. C++ Data Types
ME240 Computation for Mechanical Engineering Lecture 4 C++ Data Types Introduction In this lecture we will learn some fundamental elements of C++: Introduction Data Types Identifiers Variables Constants
More informationC++ Basics. Lecture 2 COP 3014 Spring January 8, 2018
C++ Basics Lecture 2 COP 3014 Spring 2018 January 8, 2018 Structure of a C++ Program Sequence of statements, typically grouped into functions. function: a subprogram. a section of a program performing
More informationShort Notes of CS201
#includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system
More informationChapter 2 - Control Structures
Chapter 2 - Control Structures 1 Outline 2.1 Introduction 2.2 Algorithms 2.3 Pseudocode 2.4 Control Structures 2.5 if Selection Structure 2.6 if/else Selection Structure 2.7 while Repetition Structure
More informationCS201 - Introduction to Programming Glossary By
CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with
More informationC++ Programming: From Problem Analysis to Program Design, Third Edition
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine
More informationCS3157: Advanced Programming. Outline
CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching
More informationObjectives. In this chapter, you will:
Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic expressions Learn about
More informationIS 0020 Program Design and Software Tools
1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Spring 2005 Lecture 1 Jan 6, 2005 Course Information 2 Lecture: James B D Joshi Tuesdays/Thursdays: 1:00-2:15 PM Office Hours:
More informationChapter 2. Procedural Programming
Chapter 2 Procedural Programming 2: Preview Basic concepts that are similar in both Java and C++, including: standard data types control structures I/O functions Dynamic memory management, and some basic
More informationEEE145 Computer Programming
EEE145 Computer Programming Content of Topic 2 Extracted from cpp.gantep.edu.tr Topic 2 Dr. Ahmet BİNGÜL Department of Engineering Physics University of Gaziantep Modifications by Dr. Andrew BEDDALL Department
More informationFundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University
Fundamental Data Types CSE 130: Introduction to Programming in C Stony Brook University Program Organization in C The C System C consists of several parts: The C language The preprocessor The compiler
More informationA Fast Review of C Essentials Part I
A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types
More informationChapter 2 - Control Structures
Chapter 2 - Control Structures 1 2.1 Introduction 2.2 Algorithms 2.3 Pseudocode 2.4 Control Structures 2.5 if Selection Structure 2.6 if/else Selection Structure 2.7 while Repetition Structure 2.8 Formulating
More informationUNIT- 3 Introduction to C++
UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage
More informationManual. Subject Code: CS593. Computer Science and Engineering
Programming Practices using C++ Laboratory Manual Subject Code: CS593 Computer Science and Engineering B-Tech (5 th Semester) Structure of a program Probably the best way to start learning a programming
More informationINTRODUCTION 1 AND REVIEW
INTRODUTION 1 AND REVIEW hapter SYS-ED/ OMPUTER EDUATION TEHNIQUES, IN. Programming: Advanced Objectives You will learn: Program structure. Program statements. Datatypes. Pointers. Arrays. Structures.
More information1
History of C++ & what is C++ During the 60s, while computers were still in an early stage of development, many new programming languages appeared. Among them, ALGOL 60, was developed as an alternative
More informationC++ INDEX. Introduction: Instructions for use. Basics of C++: Structure of a program Variables. Data Types. Constants Operators Basic Input/Output
INDEX Introduction: Instructions for use Basics of : Structure of a program Variables. Data Types. Constants Operators Basic Input/Output Control Structures: Control Structures Functions (I) Functions
More informationFundamental of Programming (C)
Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering
More informationBasic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable
Basic C++ Overview C++ is a version of the older C programming language. This is a language that is used for a wide variety of applications and which has a mature base of compilers and libraries. C++ is
More informationThe C++ Language. Arizona State University 1
The C++ Language CSE100 Principles of Programming with C++ (based off Chapter 2 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University
More informationQuiz Start Time: 09:34 PM Time Left 82 sec(s)
Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability
More informationCOMP322 - Introduction to C++ Lecture 02 - Basics of C++
COMP322 - Introduction to C++ Lecture 02 - Basics of C++ School of Computer Science 16 January 2012 C++ basics - Arithmetic operators Where possible, C++ will automatically convert among the basic types.
More informationCS201 Latest Solved MCQs
Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability
More informationcs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers.
cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... today: language basics: identifiers, data types, operators, type conversions, branching and looping, program structure
More informationCS201 Some Important Definitions
CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data
More informationProgramming with C++ as a Second Language
Programming with C++ as a Second Language Week 2 Overview of C++ CSE/ICS 45C Patricia Lee, PhD Chapter 1 C++ Basics Copyright 2016 Pearson, Inc. All rights reserved. Learning Objectives Introduction to
More informationChapter 2 Basic Elements of C++
C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2-1 Chapter 2 Basic Elements of C++ At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion
More informationLecture 03 Bits, Bytes and Data Types
Lecture 03 Bits, Bytes and Data Types Computer Languages A computer language is a language that is used to communicate with a machine. Like all languages, computer languages have syntax (form) and semantics
More informationC: How to Program. Week /Mar/05
1 C: How to Program Week 2 2007/Mar/05 Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers
More informationLab # 02. Basic Elements of C++ _ Part1
Lab # 02 Basic Elements of C++ _ Part1 Lab Objectives: After performing this lab, the students should be able to: Become familiar with the basic components of a C++ program, including functions, special
More informationBinghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program
Syntax What the Compiler needs to understand your program 1 Pre-Processing Any line that starts with # is a pre-processor directive Pre-processor consumes that entire line Possibly replacing it with other
More informationIntro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?
Intro to Programming & C++ Unit 1 Sections 1.1-4 and 2.1-10, 2.12-13, 2.15-17 CS 1428 Spring 2019 Jill Seaman 1.1 Why Program? Computer programmable machine designed to follow instructions Program a set
More informationUEE1302 (1102) F10: Introduction to Computers and Programming
Computational Intelligence on Automation Lab @ NCTU Learning Objectives UEE1302 (1102) F10: Introduction to Computers and Programming Programming Lecture 00 Programming by Example Introduction to C++ Origins,
More informationProgram Organization and Comments
C / C++ PROGRAMMING Program Organization and Comments Copyright 2013 Dan McElroy Programming Organization The layout of a program should be fairly straight forward and simple. Although it may just look
More informationSTUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING
OBJECT ORIENTED PROGRAMMING STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING 1. Object Oriented Programming Paradigms 2. Comparison of Programming Paradigms 3. Basic Object Oriented Programming
More informationChapter 2 - Control Structures
Chapter 2 - Control Structures 1 Outline 2.1 Introduction 2.2 Algorithms 2.3 Pseudocode 2.4 Control Structures 2.5 if Selection Structure 2.6 if/else Selection Structure 2.7 while Repetition Structure
More informationComputer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary
GATE- 2016-17 Postal Correspondence 1 C-Programming Computer Science & Information Technology (CS) 20 Rank under AIR 100 Postal Correspondence Examination Oriented Theory, Practice Set Key concepts, Analysis
More informationPIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics
PIC 10A Pointers, Arrays, and Dynamic Memory Allocation Ernest Ryu UCLA Mathematics Pointers A variable is stored somewhere in memory. The address-of operator & returns the memory address of the variable.
More informationProgramming Fundamentals and Methodology. COMP104: C++ Basics
Programming Fundamentals and Methodology COMP104: C++ Basics Dr. Brian Mak Dr. Pedro Sander Dr. Zhen Zhou Department of Computer Science & Engineering The Hong Kong University of Science and Technology
More informationH.O.#2 Fall 2015 Gary Chan. Overview of C++ Programming
H.O.#2 Fall 2015 Gary Chan Overview of C++ Programming Topics C++ as a problem-solving tool Introduction to C++ General syntax Variable declarations and definitions Assignments Arithmetic operators COMP2012H
More informationUNIT-2 Introduction to C++
UNIT-2 Introduction to C++ C++ CHARACTER SET Character set is asset of valid characters that a language can recognize. A character can represents any letter, digit, or any other sign. Following are some
More informationComputer Programming : C++
The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2003 Muath i.alnabris Computer Programming : C++ Experiment #1 Basics Contents Structure of a program
More informationChapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers 2.4 Memory Concepts 2.5 Arithmetic
More informationC++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay
C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming
More informationReview of the C Programming Language for Principles of Operating Systems
Review of the C Programming Language for Principles of Operating Systems Prof. James L. Frankel Harvard University Version of 7:26 PM 4-Sep-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights
More informationCS 376b Computer Vision
CS 376b Computer Vision 09 / 25 / 2014 Instructor: Michael Eckmann Today s Topics Questions? / Comments? Enhancing images / masks Cross correlation Convolution C++ Cross-correlation Cross-correlation involves
More informationChapter 2. Outline. Simple C++ Programs
Chapter 2 Simple C++ Programs Outline Objectives 1. Building C++ Solutions with IDEs: Dev-cpp, Xcode 2. C++ Program Structure 3. Constant and Variables 4. C++ Operators 5. Standard Input and Output 6.
More informationCSCI 123 Introduction to Programming Concepts in C++
CSCI 123 Introduction to Programming Concepts in C++ Brad Rippe C++ Basics C++ layout Include directive #include using namespace std; int main() { } statement1; statement; return 0; Every program
More informationTutorial-2a: First steps with C++ programming
Programming for Scientists Tutorial 2a 1 / 18 HTTP://WWW.HEP.LU.SE/COURSES/MNXB01 Introduction to Programming and Computing for Scientists Tutorial-2a: First steps with C++ programming Programming for
More informationCpt S 122 Data Structures. Introduction to C++ Part II
Cpt S 122 Data Structures Introduction to C++ Part II Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Objectives Defining class with a member function
More informationc++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.
Chapter 1 File Extensions: Source code (cpp), Object code (obj), and Executable code (exe). Preprocessor processes directives and produces modified source Compiler takes modified source and produces object
More informationCS2141 Software Development using C/C++ C++ Basics
CS2141 Software Development using C/C++ C++ Basics Integers Basic Types Can be short, long, or just plain int C++ does not define the size of them other than short
More informationExpressions and Data Types CSC 121 Spring 2015 Howard Rosenthal
Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types
More informationProcedures, Parameters, Values and Variables. Steven R. Bagley
Procedures, Parameters, Values and Variables Steven R. Bagley Recap A Program is a sequence of statements (instructions) Statements executed one-by-one in order Unless it is changed by the programmer e.g.
More information6.096 Introduction to C++ January (IAP) 2009
MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. Welcome to 6.096 Lecture
More informationFeatures of C. Portable Procedural / Modular Structured Language Statically typed Middle level language
1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC
More informationC++ for Python Programmers
C++ for Python Programmers Adapted from a document by Rich Enbody & Bill Punch of Michigan State University Purpose of this document This document is a brief introduction to C++ for Python programmers
More informationBITG 1233: Introduction to C++
BITG 1233: Introduction to C++ 1 Learning Outcomes At the end of this lecture, you should be able to: Identify basic structure of C++ program (pg 3) Describe the concepts of : Character set. (pg 11) Token
More informationC Review. MaxMSP Developers Workshop Summer 2009 CNMAT
C Review MaxMSP Developers Workshop Summer 2009 CNMAT C Syntax Program control (loops, branches): Function calls Math: +, -, *, /, ++, -- Variables, types, structures, assignment Pointers and memory (***
More informationC++ Quick Guide. Advertisements
C++ Quick Guide Advertisements Previous Page Next Page C++ is a statically typed, compiled, general purpose, case sensitive, free form programming language that supports procedural, object oriented, and
More informationCharacter Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Uppercase Alphabets Lowercase Alphabets Character Set A, B, C, Y, Z a, b, c, y, z Digits
More informationCS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010
CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011 Lectures 1-22 Moaaz Siddiq Asad Ali Latest Mcqs MIDTERM EXAMINATION Spring 2010 Question No: 1 ( Marks: 1 ) - Please
More informationCS101 Linux Shell Handout
CS101 Linux Shell Handout Introduction This handout is meant to be used as a quick reference to get a beginner level hands on experience to using Linux based systems. We prepared this handout assuming
More informationUNIT - I. Introduction to C Programming. BY A. Vijay Bharath
UNIT - I Introduction to C Programming Introduction to C C was originally developed in the year 1970s by Dennis Ritchie at Bell Laboratories, Inc. C is a general-purpose programming language. It has been
More informationChapter 1. C++ Basics. Copyright 2010 Pearson Addison-Wesley. All rights reserved
Chapter 1 C++ Basics Copyright 2010 Pearson Addison-Wesley. All rights reserved Learning Objectives Introduction to C++ Origins, Object-Oriented Programming, Terms Variables, Expressions, and Assignment
More informationC OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure
C Overview Basic C Program Structure C OVERVIEW BASIC C PROGRAM STRUCTURE Goals The function main( )is found in every C program and is where every C program begins speed execution portability C uses braces
More information2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program
Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Parts of a C++ Program Parts of a C++ Program // sample C++ program
More informationThis tutorial adopts a simple and practical approach to describe the concepts of C++.
About the Tutorial C++ is a middle-level programming language developed by Bjarne Stroustrup starting in 1979 at Bell Labs. C++ runs on a variety of platforms, such as Windows, Mac OS, and the various
More information3. Java - Language Constructs I
Educational Objectives 3. Java - Language Constructs I Names and Identifiers, Variables, Assignments, Constants, Datatypes, Operations, Evaluation of Expressions, Type Conversions You know the basic blocks
More informationC++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.
EEE-117 COMPUTER PROGRAMMING Basic Elements of C++ Objectives General Questions Become familiar with the basic components of a C++ program functions, special symbols, and identifiers Data types Arithmetic
More informationBy the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program
1 By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program variables. Apply C++ syntax rules to declare variables, initialize
More informationCE221 Programming in C++ Part 1 Introduction
CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab
More informationLecture 2, September 4
Lecture 2, September 4 Intro to C/C++ Instructor: Prashant Shenoy, TA: Shashi Singh 1 Introduction C++ is an object-oriented language and is one of the most frequently used languages for development due
More informationCompiler Construction. Lecture 10
Compiler Construction Lecture 10 Using Generated Scanner void main() { FlexLexer lex; int tc = lex.yylex(); while(tc!= 0) cout
More informationThis watermark does not appear in the registered version - Slide 1
Slide 1 Chapter 1 C++ Basics Slide 2 Learning Objectives Introduction to C++ Origins, Object-Oriented Programming, Terms Variables, Expressions, and Assignment Statements Console Input/Output Program Style
More informationProgramming Fundamentals. With C++ Variable Declaration, Evaluation and Assignment 1
300580 Programming Fundamentals 3 With C++ Variable Declaration, Evaluation and Assignment 1 Today s Topics Variable declaration Assignment to variables Typecasting Counting Mathematical functions Keyboard
More informationCOMP322 - Introduction to C++
COMP322 - Introduction to C++ Winter 2011 Lecture 2 - Language Basics Milena Scaccia School of Computer Science McGill University January 11, 2011 Course Web Tools Announcements, Lecture Notes, Assignments
More informationC++ Programming Basics
C++ Programming Basics Chapter 2 and pp. 634-640 Copyright 1998-2011 Delroy A. Brinkerhoff. All Rights Reserved. CS 1410 Chapter 2 Slide 1 of 25 Program Components Function main P Every C/C++ program has
More informationAbsolute C++ Walter Savitch
Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents
More informationExpressions and Data Types CSC 121 Fall 2015 Howard Rosenthal
Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and
More informationANSI C Programming Simple Programs
ANSI C Programming Simple Programs /* This program computes the distance between two points */ #include #include #include main() { /* Declare and initialize variables */ double
More information