CHAPTER 2 components of a programming language

Slides:



Advertisements
Similar presentations
Lecture 2 Introduction to C Programming
Advertisements

1 9/10/07CS150 Introduction to Computer Science 1 Data Types Section 2.7 – 2.12 CS 150 Introduction to Computer Science I.
Chapter 2: Basic Elements of C++
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
Data types and variables
Chapter 2: Basic Elements of C++
CS150 Introduction to Computer Science 1
Chapter 2 Data Types, Declarations, and Displays
Chapter 2: Basic Elements of C++
Chapter 2: Introduction to C++.
Chapter 2: Basic Elements of C++
Basic Elements of C++ Chapter 2.
CHAPTER 2 BASIC ELEMENTS OF C++. In this chapter, you will:  Become familiar with the basic components of a C++ program, including functions, special.
COMPUTER SCIENCE I C++ INTRODUCTION
Input and Output in Console Mode UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) ADNAN BABAR MT14028 CR
Objectives You should be able to describe: Data Types
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
CSC 125 Introduction to C++ Programming Chapter 2 Introduction to C++
Elements of a C++ program 1. Review Algorithms describe how to solve a problem Structured English (pseudo-code) Programs form that can be translated into.
A Variable is symbolic name that can be given different values. Variables are stored in particular places in the computer ‘s memory. When a variable is.
CS1 Lesson 2 Introduction to C++ CS1 Lesson 2 -- John Cole1.
C++ Basics Structure of a Program. C++ Source Code Plain text file Typical file extension .CPP Must compile the C++ source code without errors before.
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
1 Programs Composed of Several Functions Syntax Templates Legal C++ Identifiers Assigning Values to Variables Declaring Named Constants String Concatenation.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 2: Basic Elements of C++
Data & Data Types & Simple Math Operation 1 Data and Data Type Standard I/O Simple Math operation.
1 C++ Syntax and Semantics, and the Program Development Process.
Week 1 Algorithmization and Programming Languages.
C++ Programming: Basic Elements of C++.
Copyright © 2012 Pearson Education, Inc. Chapter 2: Introduction to C++
CHAPTER 7 DATA INPUT OUTPUT Prepared by: Lec. Ghader R. Kurdi.
Introduction to C++ Basic Elements of C++. C++ Programming: From Problem Analysis to Program Design, Fourth Edition2 The Basics of a C++ Program Function:
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 2: Introduction to C++
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
A first program 1. #include 2. using namespace std; 3. int main() { 4. cout
Chapter 3 – Variables and Arithmetic Operations. Variable Rules u Must declare all variable names –List name and type u Keep length to 31 characters –Older.
CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Basic Elements of C++
Chapter 2: Introduction to C++. Outline Basic “Hello World!!” Variables Data Types Illustration.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 2: Basic Elements of C++
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 2: Basic Elements of C++
PROGRAM ESSENTIALS. TOKENS  SMALLEST UNITS OF A PROGRAM LANGUAGE  Special Symbols  Mathematical Operators  Punctuation  Word Symbols  Key Words.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 2: Basic Elements of C++
Lecture 5 Computer programming -1-. Input \ Output statement 1- Input (cin) : Use to input data from keyboard. Example : cin >> age; 2- Output (cout):
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2 Introduction to C++
Chapter 2: Basic Elements of C++. Introduction Computer program – Sequence of statements whose objective is to accomplish a task Programming – Process.
C++ Programming: Program Design Including Data Structures, Fifth Edition Chapter 2: Basic Elements of C++
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 2: Basic Elements of C++
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 2: Basic Elements of C++
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 2: Basic Elements of C++
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 3: Input/Output Samples.
2.1 The Part of a C++ Program. The Parts of a C++ Program // sample C++ program #include using namespace std; int main() { cout
Chapter 1.2 Introduction to C++ Programming
Chapter 2: Basic Elements of C++
Chapter Topics The Basics of a C++ Program Data Types
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 2: Introduction to C++
BASIC ELEMENTS OF A COMPUTER PROGRAM
Basic Elements of C++.
Chapter 2: Basic Elements of C++
Basic Elements of C++ Chapter 2.
2.1 Parts of a C++ Program.
Variables T.Najah Al_Subaie Kingdom of Saudi Arabia
CHAPTER 2: COMPONENTS OF PROGRAMMING LANGUAGE
Chapter 2: Introduction to C++.
Presentation transcript:

CHAPTER 2 components of a programming language Introduction To Computer Programming (CSC425) CHAPTER 2 components of a programming language

Contents Variable Definition - Identifier, variable, constant - Standard data type (int, float, double, char) - Input/output structure - C++ block structure

At The end of this class, student should be able to: Identify the basic elements needed in writing a program

Introduction Computer program: sequence of statements (instructions) designed to accomplish some task Programming: planning/creating a program Syntax: rules that specify which statements (instructions) are legal Programming language: a set of rules, symbols, and special words

C++ block structure // Introductory comments // file name, programmer, when written or modified // what program does #include <iostream.h> void main() { constant declarations ; variable declarations; executable statements ; }

Example of C++ program: //A simple C++ program #include <iostream.h>  compiler directive/header file   void main( ) main function { //display greeting message comment cout<<”Welcome to CSC 425 class”; statement } OUTPUT Welcome to CSC 425 class

Comments Important part of a program's documentation. It is used to explain the purpose of a program. Explain the parts of program and keep note regarding changes to the source code. Describe about the reason of the program and understand the program more clearly. Increased the user understanding of the program. Store the names of programmers for future reference. Used to make program documentation.

Comments Can be used in 2 ways: Using /* */ symbol Used for one or more than one line of comments in group Example: /* This is the example of comment in C++ program. This is the second line */

Comments 2. Using // symbol Used only for one line Example: // This is example of comments // This is the second line

Preprocessor Directive A line of code that begins with the # symbol.   Are processed by preprocessor (which is usually bundled into the compiler) before compilation. Are not executable code lines but instructions to the compiler. Each header file stores functions that are related to a particular application. The directive #include <iostream.h> tells the preprocessor to include the contents of the file <iostream.h>, which includes input-output operations (such as printing to the screen). 

Function Main Function Every C++ program contains one or more functions, one of which must be named main. Every C++ program has a main function. A function is a block of code that carries out a specific task. The word main is followed in the code by a pair of parentheses ( ).

Function Braces Right after these parentheses we can find the body of the main function enclosed in braces { }. What is contained within these braces is what the function does when it is executed. Braces used to mark the beginning and end of blocks of code. The open braces ({ ) are place in the beginning of code after the main functions and close braces ( }) are used to show closing of code. The code after the ( }) will not be read/evaluate by compiler

Function Statement A function consists of a sequence of statements that perform the work of the function. It consists of instructions or command which make the program work. Each statement in C++ ends with a semicolon (;). There are 3 type of statement : Input statement- cin>>statement; Output statement-cout<<“statement”; Operation statement-mathematical operation

VARIABLE DEFINITION Operation done by computer Receive input Produce output Assign value into storage Perform arithmetic and logic operation Make selection Repeating a set of actions

Program Elements Generally a computer program has the following elements: Input section Storage allocation Constants Variables Files Processing using arithmetic or logic operation and control with either sequential, selection or and repetition structure. Output Section

Program Elements Processing Input Output Storage int number1, number2, total; cin >> number1 >> number2; total = number1 + number2; cout << total << endl Arithmetic Logic cin >> number1 >> number2; Processing cout << total << endl total = number1 + number2; Input Output constant Storage variable int number1, number2, total;

Storage One of the essential resource of a program A location in computer memory that is allocated to the program Used to hold value of specific data type Categories: Constants Variables Files Data Types Integer number Floating point number Character Identifier is the name given to specific storage

Identifiers Example: int number; Data type Identifier

Identifiers Identifier naming rules: Examples of valid identifiers Must begin with a letter or _ Can be followed by a letter, number or underscore (‘_’) Cannot have space in between Cannot have keywords Examples of valid identifiers number1 averageScore latest_CGPA Examples of invalid identifiers 20score Student’sAge average Salary

Constant identifiers Constant To hold fixed value that cannot be altered during program execution. Examples: PI value  3.1416 Number of days per week  7 Constant declaration: const keyword is used to declare a constant and it must be initialized. Example: const double PI = 3.1416; const <data type> <identifier> = value;

Variables DataType identifier, identifier, . . .; To hold value that might be altered during program execution. Hold value on temporary basis Examples: score Temperature Speed Length The syntax for declaring one variable or multiple variable is : Example: int number; float score1, score2; int score; float number; int count = 0; //initialize count to 0 DataType identifier, identifier, . . .;

Data types Basic Data Types C++ Data Types Examples int score; Integer (90, 0, -78) int Floating point (4.5,1.0,-0.67) float or double Character (‘A’,’a’,’*’,’1’) char, char…[10] String (“Ali”, “Anson Road”) string Examples int score; float temperature; double accountBalance; char gender; char name[15]; string name=“”;

int DATA TYPE Memory allocated for the int type is 4 bytes signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295 Examples: -6728 78 Positive integers do not have to have a + sign in front of them No commas are used within an integer Commas are used for separating items in a list

Floating-Point Data Types C++ uses scientific notation to represent real numbers (floating-point notation)

Floating-Point Data Types (continued) float: represents any real number Range: -3.4E+38 to 3.4E+38 (7 digits) Memory allocated for the float type is 4 bytes Float values are called single precision double: represents any real number Range: -1.7E+308 to 1.7E+308 (15 digits) Memory allocated for double type is 8 bytes Double values are called double precision Precision: maximum number of significant digits

char DATA TYPE The smallest integral data type Memory allocated for the char type is 1 byte Used for characters: letters, digits, and special symbols Each character is enclosed in single quotes Some of the values belonging to char data type are: 'A', 'a', '0', '*', '+', '$', '&' A blank space is a character and is written ' ', with a space left between the single quotes Find the range of char datatype?

string Data Type Programmer-defined type supplied in standard library Sequence of zero or more characters Enclosed in double quotation marks Null: a string with no characters Each character has relative position in string Position of first character is 0, the position of the second is 1, and so on Length: number of characters in string

Data Types - String #include <iostream> OUTPUT #include<string> using namespace std; void main() { int number; string name; cout<<”Enter a number:”; cin>>number; cout<<”Enter a name:”; getline (cin, name); cout<<”Your number is:”<<number<<endl; cout<<”Your name is:”<<name<<endl; } OUTPUT Enter a number: 5 Enter a name: Ali Ahmad Your number is 5 Your name is Ali Ahmad Press any key to continue_

Data types - Examples Example (integer) #include <iostream.h> void main() { int num1, num2, sum; cout<<"Enter first number:"; cin>>num1; cout<<"Enter second number:"; cin>>num2; sum=num1+num2; cout<<"The sum of two number is:"<<sum<<endl; }

Data types - Examples Example (float/double/const) #include <iostream.h> void main() { const double PI=3.142; float radius; double area; cout<<“Enter radius:”; cin>>radius; area=2*PI*radius; cout<<“The area is:”<<area<<endl; }

Data types - Examples Example (char/char []) #include <iostream.h> void main() { char gender; char name[15]; cout<<"Please enter your name:"; cin.getline(name, 15); cout<<name; cout<<" Enter you gender (M or F):"; cin>>gender; }

Data types - Examples Example (string) #include <iostream> NOT <iostream.h> #include <string> using namespace std; void main() { string name=“”; cout<<"Please enter your name:”; cin>>ws;  remove whitespaces at the start getline(cin, name); cout<<name; }

Input Data must be loaded into main memory before it can be manipulated Storing data in memory is a two-step process: Instruct the computer to allocate memory Include statements to put data into allocated memory

Example 1 3.1416 ? ? #include <iostream.h> PI radius area //program to calculate area of a circle main() { //variable and constant allocation const double PI = 3.1416; int radius; double area; //input section cout << “Enter a radius : ”; cin >> radius; area = PI * radius * radius; //processing //output section cout << “Area of the circle is ” << area << endl; return 0; }//end main() PI 3.1416 radius ? area ?

Example 1 - Output Enter a radius : __ Example: user enter number 8 Area of the circle is 201.0624

Example 1 - Output PI 3.1416 radius 8 area 201.0624 #include <iostream.h> //program to calculate area of a circle main() { //variable and constant allocation const double PI = 3.1416; int radius; double area; //input section cout << “Enter a radius : ”; cin >> radius; area = PI * radius * radius; //processing //output section cout << “Area of the circle is ” << area << endl; return 0; }//end main() PI 3.1416 radius 8 area 201.0624

Input and Output Statement Input Statement To received input from keyboard or read input from a file. Using cin keyword and input stream operator (>>). Syntax: cin >> <variable>; Example cin >> number; cin >> number1 >> number2;

Input and Output Statement Example of a good input statement: cout << “Enter a score : ”; cin >> score; Prompt user to enter a number Read a number

Input and Output Statement To display output on screen or to write output into file. Using cout keyword and output stream operator (<<). Syntax: cout << <string/constant/variable/expression>;

Input and Output Statement Examples: Statements Output cout << “Hello World”; Hello World cout << 80; 80 cout << area; content of area cout << 8 + 4; 12

Input and Output Statement What is the output of the following statements? Statements Output cout << “Total is ” << 8 + 2; ? cout << “8 + 2 = ” << 8 + 2; ?

Input and Output Statement End of line (newline) endl keyword will force the cursor to begin at new line. Examples: Code fragment Output cout << 14; 1416 cout << 16; cout << 14 << endl; 14 cout << 16 << endl; 16 cout << 14 << ‘\n’; 14 cout << 16 << ‘\n’; 16 cout<<“Hi”<<endl; Hi cout<<“\nHi”; Hi

Exercise 1 Write a program that does the following : Prompts the user to input two decimal numbers and display the two numbers. #include <iostream.h> void main () { double a, b; cout<<“Enter two decimal number”; cin >> a>> b; cout<<“Number 1 : “ <<a<<endl; cout<<“Number 2 : “ <<b<<endl; }

Exercise 2 Write a program to display the following: Student name Student MatricNo Student Program Student’s CGPA

#include <iostream> #include <string> using namespace std; void main () { string StudName, MatricNo, program; double cgpa; cout<<"Enter Student Name :"; cin >> ws; getline(cin,StudName); cout<<"Enter Matric Number:"; getline(cin,MatricNo); cout<<"Enter Program:"; getline(cin,program); cout<<"Enter CGPA:"; cin >> cgpa; cout<<"STUDENT NAME: "<<StudName<<endl; cout<<"MATRIC NUMBER:"<<MatricNo<<endl; cout<<"PROGRAM :"<<program<<endl; cout<<"CGPA:"<<cgpa<<endl; }

#include <iostream.h> void main () { char StudName[30], MatricNo [12], program[10]; double cgpa; cout<<"Enter Student Name :"; cin.getline(StudName,30); cout<<"Enter Matric Number:"; cin.getline(MatricNo,30); cout<<"Enter Program:"; cin.getline(program,10); cout<<"Enter CGPA:"; cin >> cgpa; cout<<"STUDENT NAME: "<<StudName<<endl; cout<<"MATRIC NUMBER:"<<MatricNo<<endl; cout<<"PROGRAM :"<<program<<endl; cout<<"CGPA:"<<cgpa<<endl; }

Formatting Program Output Besides displaying correct results, it is extremely important for a program to present its output attractively. To include manipulators within an output display, must include the header file using the preprocessor command as follows : #include <iomanip.h> Most commonly used manipulators in a cout statement : setw(n) - Set field width to n setfill(n) - Sets fill character to n setprecision(n) - Sets floating-point precision to n Semester Jan – Apr 2010 CSC425 : INTRODUCTION TO COMPUTER PROGRAMMING

I/O Manipulator Most system divides a page of text output into twenty five rows and eighty columns. Example: Suppose you want to create three column of output: person’s name, person’s student id and person’s code program.

I/O Manipulator cout<<“\n\n” // skip 2 lines <<setw(15)<<“NAME” // display heading <<setw(22)<<“STUDENT ID” <<setw(23)<<“CODE”<<endl; cout<<setw(15)<<“----” // display underline <<setw(22)<<“-------” <<setw(23)<<“-----”<<endl; Output Screen: 15 column 22 column 23 column CODE NAME S T U D E N T I D

I/O Manipulator setfill(n) Specifies character for blank space in field Single quotes required around character enclosed in parentheses Example: num = 165.48; cout<<setw(10)<<setfill(‘*’)<<num; Output: ****165.48

I/O Manipulator Generating Left-Justified Value Specifies character for blank space in field cout.setf(ios::left); By default, when we use setw(n) to print values or information, the values are right justified. So to put as left justify we must write the above statement.

I/O Manipulator Generating Decimal Point Value cout.setf(ios::fixed); cout.precision(n); Statement cout.setf(ios::fixed) forces the compiler to generate a fixed decimal output without exponential, or e, notation. Meanwhile cout.precision(n) dictates the number of decimal places to the right of decimal point to be generated.

I/O Manipulator Generating Currency Output cout.setf(ios::fixed); cout.setf(ios::showpoint); // the two means two decimal places cout.precision(2); The showpoint function forces the decimal point to always be displayed.

I/O Manipulator Example for set precision: #include<iostream.h> #include<iomanip.h>   void main() { double x= 123.4, y = 456.0; cout.setf(ios::fixed); cout.precision(6); cout<<x<<endl; cout<<y<<endl; }

I/O Manipulator #include<iostream.h> #include<math.h> #include<iomanip.h> void main() { double circumference,area,radius; double PI = 3.142; cout<<"Enter Radius : "; cin>>radius; circumference = 2 * PI * radius; area = PI * pow(radius,2); cout.setf(ios::left); cout.setf(ios::fixed); cout.precision(2); cout<<setw(20)<<"Radius"; cout<<setw(20)<<"Circumference"; cout<<setw(20)<<"Area"<<endl; cout<<setw(20)<<"------"; cout<<setw(20)<<"-------------"; cout<<setw(20)<<"-----"<<endl; cout<<setw(20)<<setfill('*')<<radius; cout<<setw(20)<<setfill('*')<<circumference; cout<<setw(20)<<setfill('*')<<area<<endl; }

I/O Manipulator