Program Organization and Comments

Similar documents
First C or C++ Lab Paycheck-V1.0 Using Microsoft Visual Studio

Chapter 1 - What s in a program?

Getting started with C++ (Part 2)

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

! A literal represents a constant value used in a. ! Numbers: 0, 34, , -1.8e12, etc. ! Characters: 'A', 'z', '!', '5', etc.

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

Lab # 02. Basic Elements of C++ _ Part1

The C++ Language. Arizona State University 1

1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A.

BITG 1233: Introduction to C++

Should you know scanf and printf?

ROCK PAPER SCISSORS Rock Paper Scissors Lab Project Using C or C++

C++ Support Classes (Data and Variables)

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Add Subtract Multiply Divide

2. Numbers In, Numbers Out

Fundamentals of Programming Session 4

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

Understanding main() function Input/Output Streams

Fundamentals of Programming CS-110. Lecture 2

Chapter 2: Introduction to C++

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Tutorial 2: Compiling and Running C++ Source Code

Professor Terje Haukaas University of British Columbia, Vancouver C++ Programming

2. Numbers In, Numbers Out

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

WARM UP LESSONS BARE BASICS

printf( Please enter another number: ); scanf( %d, &num2);

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

Programming. C++ Basics

Computing and Statistical Data Analysis Lecture 3

Your First C++ Program. September 1, 2010

BEng (Hons) Electronic Engineering. Resit Examinations for / Semester 1

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

4. Structure of a C++ program

COMP s1 Lecture 1

Expressions, Input, Output and Data Type Conversions

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

Computer Programming : C++

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

CS 241 Computer Programming. Introduction. Teacher Assistant. Hadeel Al-Ateeq

Introduction to Programming EC-105. Lecture 2

LOGO BASIC ELEMENTS OF A COMPUTER PROGRAM

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma.

BTE2313. Chapter 2: Introduction to C++ Programming

Text File I/O. #include <iostream> #include <fstream> using namespace std; int main() {

CS16 Exam #1 7/17/ Minutes 100 Points total

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Chapter 2 Basic Elements of C++

Computer Science 2500 Computer Organization Rensselaer Polytechnic Institute Spring Topic Notes: C and Unix Overview

CpSc 111 Lab 5 Conditional Statements, Loops, the Math Library, and Redirecting Input

How to approach a computational problem

CMPE110 - EXPERIMENT 1 * MICROSOFT VISUAL STUDIO AND C++ PROGRAMMING

2 nd Week Lecture Notes

Chapter 1 Introduction to Computers and C++ Programming

Data Types Literals, Variables & Constants

Objectives. In this chapter, you will:

LECTURE 02 INTRODUCTION TO C++

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

A Fast Review of C Essentials Part I

Chapter 3. Numeric Types, Expressions, and Output

Introduction to C++: I

Programming Language. Functions. Eng. Anis Nazer First Semester

Preprocessor Directives

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

UEE1302 (1102) F10: Introduction to Computers and Programming

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

UNIT- 3 Introduction to C++

Integer Representation. Variables. Real Representation. Integer Overflow/Underflow

3.1. Chapter 3: The cin Object. Expressions and Interactivity

CS3157: Advanced Programming. Outline

My First Command-Line Program

gcc hello.c a.out Hello, world gcc -o hello hello.c hello Hello, world

Programming with C++ as a Second Language

Introduction to C++ Introduction to C++ 1

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

Fundamentals of Programming. Lecture 3: Introduction to C Programming

Introduction to C++ Programming. Adhi Harmoko S, M.Komp

Lab: Supplying Inputs to Programs

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

Introduction to C++ Systems Programming

Creating a C++ Program

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

A A B U n i v e r s i t y

BLM2031 Structured Programming. Zeyneb KURT

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

Use of scanf. scanf("%d", &number);

LAB #8. GDB can do four main kinds of things (plus other things in support of these) to help you catch bugs in the act:

C: How to Program. Week /Mar/05

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING

CS Introduction to Programming Midterm Exam #2 - Prof. Reed Fall 2015

Transcription:

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 like a bunch of funny letters and symbols, once you recognize the pattern of how things are organized it makes it much easier to understand what is happening in the program. 1

Program Organization The title block at the top of the program is made up of comments that briefly describe the program, date, version, programmer, etc. The include files come next. The name of the program section, in this case it is main, and its argument list. Curly braces { and } surround the block of code that belongs to main. The body of the program is organized into the list of variables, input, processing and output. Title Block Program Name, Date, Version Programmer Name #include <filenames> int main (int argc, char* argv[ ] ) { // list of variables // input // process // output A return statement ends the program. } return 0; Comments C and C++ Style Comments /* --- */ and //------- Title block File name, list of functions/subroutines and their arguments, programmer name, date and revision Variable descriptions Description for blocks of code or data Comments on lines 2

Reasons for Comments Comments are written in a human language to help you or the next person better understand what the computer language is doing. Put good comments in your code even if you think that no one else will ever see them. There have been times that I was deeply involved in a project and knew every part of the project and did not think that I needed to comment my code because I knew it so well. I then started a new project and later returned to my first project and had to spend an extra amount of time and effort to figure out what I had done in the old project because I did not have good comments. The TITLE Comment Block 1) Use a comment block at the top of each file to indicate the program s name, the programmer s name, the date and version of the program, and a brief description of the program and any input or output parameters. The helps identify what the file or program is used for without needing to read the program code and try and figure out what it does. 3

Comment Each Paragraph 2) English essays either use a blank line between paragraphs or indent each paragraph with a few spaces at the beginning of the paragraph. When you use several lines of code that are related to each other and do a specific task, put a blank line and a comment to briefly describe the code. Comment Tricky Code 3) Put a comment on individual lines of code if you did anything that may take some extra work figuring out what the code is doing. 4

C and C++ Style Comments C++ comments // Project Name: dogyears (C++ project) // Description: Convert dog years to human // Programmer: Dan McElroy /* Project Name: dogyears (C-project) // Date: October 9, 2013 Description: Convert dog years to human Programmer: Dan McElroy #include "stdafx.h // for Microsoft VC++ Date: October 9, 2013 #include <iostream> // for cin and cout */ using namespace std; #include <stdio.h> /* for printf and scanf */ int main() { int main() // define and initialize the variables double age = 0; double dogyears = 0; { C comments /* define and initialize the variables */ double age = 0; double dogyears = 0; 1. The Visual Studio editor puts comments in green 2. Most modern compilers will accept both C++ style comments and C style comments 3. C++ comments start with a double slash // and stop at the end of line 4. C-style comments start with /* and end with */ Header Files - #include The #include statement is used to merge code from another file into your program as the program is being compiled. Header files get their name because the #include statement is placed at the top of the program. Although you might not believe it, C and C++ make programming easier by providing header files. The header files provide information to the compiler needed to compile the rest of your program. 5

Header Files The compiler needs to know the data type for each input parameter and return value for every function/procedure that will be used in your program, and for each function/procedure that they may in turn reference. Instead of you needing to declare all of these things, they are placed in files located in the compiler s header sub-folder. All you need to do is provide the name of the header file as part of a #include statement. Easy? Header Files C-language scanf and printf provide formatted input and output routines. To use these routines, put #include <stdio.h> at the top of your program. Note: stdio is pronounced standard I/O. To use the math functions such as sin, cos, tan, sqrt, use #include <math.h> C++ language cin and cout are used for input and output. To use these routines, put #include <iostream> at the top of your program. To use the math functions such as sin, cos, tan, sqrt, use #include <math> Note: C++ includes math not math.h The math header file for C++ does a few things of its own, then internally includes math.h #include stdafx.h This header file shows up only on some versions of Microsoft Visual Studio. If it is there, the other #include statements must occur after the #include stdafx.h. Do not use this include file for non-microsoft C++ programs. 6

Header Files When to use angle brackets or quotes Use the angle brackets < > around the file name if the header file is part of the compiler and located in the compiler s header subfolder. Example: #include <math.h> Use quotes around the file name if the header file is located in a sub-folder that is part of your project. These would typically be header files that you have written (or in the case of Microsoft Visual C++ the stdafx.h header file) Example: #include mystuff.h C++ Header Files - #include C and C++ // Project Name: dogyears (C++ project) // Description: Convert dog years to human // Programmer: Dan McElroy // Project Name: dogyears (C-project) // Date: October 9, 2013 // Description: Convert dog years to human // Programmer: Dan McElroy #include "stdafx.h // for Microsoft VC++ // Date: October 9, 2013 #include <iostream> // for cin and cout using namespace std; #include <stdio.h> /* for printf and scanf */ int main() int main() { { // define and initialize the variables /* define and initialize the variables */ double 1. age Header = 0; files are merged into your program when it is compiled double age = 0; double dogyears = 0; 2. Header files located in the compiler s double dogyears directory are = 0; identified by the angle brackets <filename> 3. Header files located in your program s directory are identified by double quotes filename 4. Some versions of Microsoft s Visual-C++ use the stdafx.h file. Don t include this line if you are not using Microsoft 7

Header Files - #include C++ C and C++ // Project Name: dogyears (C++ project) // Description: Convert dog years to human // Programmer: Dan McElroy // Project Name: dogyears (C-project) // Date: October 9, 2013 // Description: Convert dog years to human // Programmer: Dan McElroy #include "stdafx.h" // for Microsoft VC++ // Date: October 9, 2013 #include <iostream> // for cin and cout using namespace std; #include <stdio.h> /* for printf and scanf */ int main() int main() { { // define and initialize the variables /* define and initialize the variables */ double 1. age The = C++ 0; console in (cin) and console out (cout) need iostream double age = 0; double dogyears = 0; 2. The C-console in (scanf) and double console dogyears out (printf) = need 0; stdio.h stdio is pronounced Standard-I-O 3. The namespace feature in C++ is provided to make it easier to keep parts of large programs separate from each other 4. There is a semicolon ; at the end of using namespace std; but not at the end of the #include statements. int main ( The int main( statement is used to start all C and C++ console application programs. There are several ways that the int main( statement can be written. In each case, the only space that is required is after the keywords int or void. int main( ) int main(int argc, char* argv[]) 8

Microsoft version of int main( Microsoft likes to make their stuff incompatible with everyone else, so they start Visual Studio C and C++ programs int _tmain(int argc, _TCHAR* argv[]) and then they convert it back to normal before compiling. If you are using Microsoft, you can leave the int main( the way they defined it, or you can use the standard version of int main. Both work fine. int main parameter list When declaring a function such as main, an optional set of parameters can be placed within the parentheses ( ). This permits another part of the program to pass information to the function. main is usually declared with the int argc and char* argv[] parameters inside the parentheses, but these parameters do not need to be supplied if they are not used inside main. int argc identifies the number of arguments passed char* argv[ ] provides an array of pointers to the character strings supplied when the program was started. More detail will be provided when these parameters are used in a program. 9

int main or void main Placing a data type in front of a function declaration indicates the type of data passed back by the return statement to a higher level program or program routine. The C and C++ console programs are called/launched by the operating system and have the ability to return a single integer indicating the exit status of the program. A console program that starts with int main should have a return 0; statement at the end of the program to indicate successful completion of the program. A program that starts with void main can have a return; statement, but it can not return an integer (like 0). List of Variables and Constants Variables in C and C++ are declared as follows and can be initialized at the same time they are declared: data_type variable_name semicolon Examples: int length; int count = 20; double price; Constants are declared with the keyword const before the data type. The value of a constant can not be changed after it is defined. const double TaxRate = 0.0875; // 8.75% 10

Input Data to be Processed Data must be input into the program before it can be processed. Data can be input from the keyboard or another device such as a disk file. When data is input from the keyboard, it is necessary to provide a prompt message on the screen that asks for the data, otherwise the user may just see a flashing cursor _ and not know that they need to do anything, or what type of data should be input. The Prompt Message The word prompt comes from the theater. A person might hold up a card to help the actor remember what line he or she needs to say next. TV shows use a machine called a teleprompter. C++ cout << "Hours worked: "; // prompt cin >> hours; // input the hours C printf ("Hours worked: "); /* prompt */ scanf ("%lf", &hours); /* input the hours */ Provide a colon : and a space at the end of the prompt to keep the user s input from sitting right next to the prompt message. If using the C language, don t forget the ampersand & inside of scanf. 11

Process the Data The processing of the data will be dependent on the requirements of the program. You may need to create variables in addition to the variables needed for the input and output data. Output the Result Outputting a text string in C or C++ is fairly easy. cout << "You passed the test"; // C++ printf ("You passed the test"); /* C */ or char message[] = "You passed the test"; cout << message; // C++ printf ("%s", message); /* C */ The %s in the printf statement is part of the format string that indicates that a string will be output. In this case, the string to be output is the contents of the variable message. 12

cout Formatted Output cout will display a floating point number (double) any way it wants. It could show up with no digits past the decimal point, a whole lot of digits, or the display may be in scientific notation. C++ provides several routines that are part of the I/O manipulation package. You need to use #include <iomanip> at the top of your program to use these routines. cout Formatted Output Sample of using cout to display a double with two decimal places: #include "stdafx.h" // Only for Microsoft #include <iostream> #include <iomanip> using namespace std;. double Paycheck = 183.75; cout << setiosflags(ios::fixed); cout << setiosflags(ios::showpoint); cout << setprecision(2) << Paycheck << endl; The endl represents end-of-line and is used to move the cursor to the next line on the screen. Make sure that you type the last character of endl as a small L and not a 1. 13

printf Formatted Output printf can be much easier to than the cout routines, but the full documentation on printf is several pages long. The example below shows only how to use printf to display a double with two decimal places. #include <stdio.h>. double Paycheck = 183.75; printf ("%.2lf\n", Paycheck); The lower-case letters LF indicate that a long-float value is supplied. A long-float is a double. In this case the value is supplied by the contents of Paycheck. The \n represents end-of-line and is used to move the cursor to the next line on the screen. ACKNOWLEDGEMENTS VIDEO EDITING SOFTWARE Roxio Creator TM NXT Pro 2 14