Get Programming with C Zambak 1st Edition Osman Ay PDF ebook with Full Chapters Now
Get Programming with C Zambak 1st Edition Osman Ay PDF ebook with Full Chapters Now
https://ebookultra.com/download/ecology-zambak-1st-edition-osman-
arpaci/
https://ebookultra.com/download/programming-with-visual-c-concepts-
and-projects-1st-edition-james-allert/
https://ebookultra.com/download/public-figures-1st-edition-osman/
https://ebookultra.com/download/programming-and-problem-solving-with-
c-comprehensive-comprehensive-edition-nell-b-dale/
Professional Windows 8 Programming Application Development
with C and XAML 1st Edition Nick Lecrenski
https://ebookultra.com/download/professional-windows-8-programming-
application-development-with-c-and-xaml-1st-edition-nick-lecrenski/
https://ebookultra.com/download/real-world-functional-programming-
with-examples-in-f-and-c-1st-edition-tomas-petricek/
https://ebookultra.com/download/programming-c-1st-edition-jesse-
liberty/
https://ebookultra.com/download/earth-inferno-austin-osman-spare/
https://ebookultra.com/download/functions-zambak-1st-edition-cem-
giray/
Programming with C Zambak 1st Edition Osman Ay
Digital Instant Download
Author(s): Osman AY, Muhammed Akif HORASANLI
ISBN(s): 9789752662452, 9752662455
Edition: 1
File Details: PDF, 3.64 MB
Year: 2006
Language: english
M O D U L A R S Y S T E M
PROGRAMMING WITH
C++
Osman AY
Muhammed Akif HORASANLI
http://book.zambak.com
Copyright © 2006 Zambak Basým
Yayýn Eðitim ve Turizm Ýþletmeleri
Sanayi Ticaret A.Þ.
All rights reserved.
No part of this book may be
reproduced, stored in a retrieval
system, or transmitted in any form of
recording without the prior written
permission of the publisher.
Digital Assembly
Zambak Typesetting & Design
Page Design
Osman AY
Proofreader
Andy MARTIN
Publisher
Zambak Basým Yayýn Eðitim ve Turizm
Ýþletmeleri Sanayi Ticaret A.Þ.
Printed in
Ýstanbul - TURKEY
ISBN
978-975-266-245-2
DISTRIBUTION
ZAMBAK YAYINLARI
Bulgurlu Mah. Libadiye Cad. Haminne
Çeþmesi Sok. No. 20 34696
Üsküdar / ÝSTANBUL
_______________________
Tel : +90-216 522 09 00 (pbx)
Fax : +90-216 443 98 39
http://book.zambak.com
1. Introduction To Programming 3. Repetition Structures
Understanding the Programming . . . . . . . . . . . . . 6 Repetition Structures (Loops) . . . . . . . . . . . . . . . 38
The First C++ Program . . . . . . . . . . . . . . . . . . . . 6 The "while" Loop . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Breaking a Text into Multiple Lines . . . . . . . . . . . . 7 Increment and Decrement Operators . . . . . . . . . 40
Basic Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 Counter-Controlled and Sentinel-Controlled
Getting Data from the User (Input) . . . . . . . . . . . . 8 Repetitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . 9 The "do/while" Loop . . . . . . . . . . . . . . . . . . . . . . . 45
Precedence of Arithmetic Operators The "for" Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Fundamental C++ Variables . . . . . . . . . . . . . . . . 11 Syntax of “for” statement . . . . . . . . . . . . . . . . 47
ASCII Codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 The "break" and "continue" Statements . . . . . . . . 53
Reading and Printing Strings . . . . . . . . . . . . . . . . 15 Which loop should I use?. . . . . . . . . . . . . . . . . . . 54
Initialization of Variables . . . . . . . . . . . . . . . . . . . . 16 Nested Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Using Text Files as Input and Output. . . . . . . . . . 16 Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . 57
Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . 19 Programming Problems . . . . . . . . . . . . . . . . . . . . 58
Programming Problems . . . . . . . . . . . . . . . . . . . . 20 Flowchart Programming . . . . . . . . . . . . . . . . . . . . 61
Flowchart Programming . . . . . . . . . . . . . . . . . . . . 20 Making Loops . . . . . . . . . . . . . . . . . . . . . . . . . 61
Understanding Flowchart Programming . . . . 21 Pre-conditional Loops. . . . . . . . . . . . . . . . . . . 61
Flowchart Symbols . . . . . . . . . . . . . . . . . . . . . 22 Post-conditional Loops . . . . . . . . . . . . . . . . . . 62
6. Structs
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
Declaring Structs and Accessing Members . . . 112
Reading and Printing Structures . . . . . . . . . . 112
Hierarchical Structures . . . . . . . . . . . . . . . . . . . . 114
Array of Structs . . . . . . . . . . . . . . . . . . . . . . . . . . 120
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
Review Questions . . . . . . . . . . . . . . . . . . . . . . . . 123
Programming Problems . . . . . . . . . . . . . . . . . . . 124
Flowchart Programming . . . . . . . . . . . . . . . . . . . 126
Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
Understanding the Programming
Ibn Musa al-Khwarizmi Programming is instructing a computer to perform a task for you with the help of a
(Algorizm) (770 - 840 AD) was programming language. The instructing part requires a step by step solution to the
born in Uzbekistan. His task. This step by step solution is called an algorithm after the name of AlKharizmi.
parents migrated to Baghdad
when he was a child. He is People who make computer programs are called programmers. There are usually
best known for introducing the two difficulties for computer programmers; Finding a feasible algorithm (algorithm
mathematical concept design) and writing the program (implementation). People who use the programs are
Algorithm, which is so named
called end-users.
after his last name.
Al-Khwarizmi was one of the A computer program (software) contains a sequence of instructions for a computer.
greatest mathematicians who One program is usually composed of three parts:
ever lived. He was the founder
of several branches and basic Input part gets the data from an input device. Our programs, in the book, will get
concepts of mathematics. He the data from keyboard or from a text file.
is also famous as an
astronomer and geographer. Process part is the hardest working part of the program. It carries out the
He is recognized as the algorithm and finds out the desired result.
founder of Algebra, as he not
only initiated the subject in a
Output part gives the result of the program. Our programs will display the result
systematic form but also on the screen or print it into a text file.
developed it to the extent of
giving analytical solutions of
linear and quadratic The First C++ Program
equations. The name Algebra
is derived from his famous It is time to type our first C++ program. This program is going to prompt a line of
book Al-Jabr wa-al- text that says "Hello World!". This program has no input and no process but only
Muqabilah. He developed in output which says "Hello world!".
detail trigonometric tables
containing the sine functions. /*
Al-Khwarizmi also developed PROG: C1_01hello.cpp
the calculus of two errors, Understanding structure of a C++ program.
which led him to the concept Printing a line of text.
of differentiation. He also Using comments.
refined the geometric */
representation of conic
sections. #include <iostream>
//includes the declarations of the basic standard input-output
//library in C++, and its functionality is going to be used later
//in the program.
C++ programs consist of one or more modules. Each module performs a specific
task. These modules are called functions. The "Hello World!" program has only one
module that is the main function. Any C++ program is been started to execute from
the main function so each program must have this function.
Before the functions, the program has an "include" and "using namespace" part.
This part declares the libraries where the C++ commands we are going to use in
the program are defined. Flowchart of the Program
“01hello”.
Like each sentence ends with a period ('.'), each C++ statement ends with a
semicolon character (';').
A flowchart is a visual
Besides the program codes, the program has some comments. C++ has two ways representation of the
to insert comments into source code: Single line comment and multiple line algorithms. Is is made up of a
few symbols: terminal, input,
comment. Single line comments are written behind the double slash characters
process, decision, output, and
("//") and multiple line comments are enclosed between slash and asterisk ("/*") connector.
and asterisk and slash ("*/") characters. Comments are ignored by the compiler.
/*
PROG: C1_02hello.cpp
Using endl.
*/
#include <iostream>
using namespace std;
int main()
{
cout <<"Hello world!"<<endl; //move the cursor to the cout<<“Hello ”<<endl;
//beginning of the next line. and
cout <<"This is my C++ program."<<endl<<endl; cout<<“Hello \n”;
system("pause"); statemens print the same
return 0; output.
}
Hello world!
This is my C++ program.
Introduction to Programming 7
Basic Arithmetic
Any statement enclosed with double quotes (" ") in a cout statement is displayed
directly and any arithmetical or logical expression is evaluated and then the result
is displayed. The program below shows the result of the expression 3 + 5.
/*
PROG: C1_03sum.cpp
*/
#include <iostream>
using namespace std;
int main()
{
cout <<"5 + 3 = "<<5+3<<endl; //calculate and print the sum
system("pause");
return 0;
}
5+3=8
Flowchart of the Program Press any key to continue . . .
“03sum”
Getting Data from the User (Input)
Programs usually read the input data from the standard input (keyboard) or from
an input file. "cin" command is used to read data from the standard input. The
following program reads two integers, calculates their sum and then outputs the
result.
int num1, num2, sum; declares three variables. The names of the variables are
num1, num2 and sum. A variable is a named storage location that can contain
data that can be modified during program execution. This declaration specifies
that those variables can contain integer values (-45, 0, 11, 37, etc.). "num1" and
"num2" will be used to store the input data, and "sum" will be used to keep the
sum of input values in the program.
/*
PROG: C1_04sum.cpp
Getting data from keyboard, making sum of two integers,
understanding variables, and using assignment operator.
*/
#include <iostream>
using namespace std;
int main()
{
int num1, num2, sum; //num1, num2 and sum are three
//variables type of integer.
cout<<"Enter two integers:"<<endl;
cin >> num1 >> num2; //cin reads two values for
Flowchart of the Program //num1 and num2.
“04sum” sum = num1 + num2; //sum gets the value of num1+num2.
Addition + 5+4=9
Subtraction - 5 - 4 = 1 and 4 - 5 = -1 Beside the assignment and
the arithmetic operators C++
Multiplication * 5*4=9 has many others. The most
common C++ operators are:
Division (integer) / 15 / 3 = 5 and 12 / 5 = 2
assignment
Modulus % 12 % 5 = 2, 15 % 3 = 0, and 3 % 5 = 3 arithmetic
increment and decrement
/*
PROG: C1_05calculator.cpp string concatenation
Demonstrating arithmetic operators. Calculating sum, difference, relational
product, quotient, and remainder. Using (float) casting to get logical
floating-point quotient. conditional
*/ bitwise
#include <iostream>
using namespace std;
Introduction to Programming 9
cout <<num1 <<"*"<<num2<<"="<<num1*num2<<endl;
cout <<num2 <<"*"<<num1<<"="<<num2*num1<<endl<<endl;
system("PAUSE"); return 0;
}
7-3=4
3-7=-4
7*3=21
3*7=21
7/3=2
7/3=2.33333
3/7=0
3/7=0.428571
7%3=1
3%7=3
Size in
Type Values
Bytes
unsigned short int 2 0 to 65,535
short int 2 -32,768 to 32,767 Always name your variables
with a great care, and explain
unsigned int 4 0 to 4,294,967,295 them thoroughly.
int 4 -2,147,483,648 to 2,147,483,647
integer variables
unsigned long int 4 0 to 4,294,967,295
long int 4 -2,147,483,648 to 2,147,483,647
9.223.372.036.854 to
long long int 8
9.223.372.036.853
Integer variables store whole numbers (-4, 3, 51, etc). Unsigned integer type
variables cannot have negative values, whereas other integer type variables (signed
integers) may have negative and positive values.
Floating-point variables store decimal numbers (3.5, -5,123, 4.0, etc).
Introduction to Programming 11
Logical variables store the result of logical expressions and get only the values
true and false. False is represented with 0 and true is represented with a positive
value (usually 1) in C++. Logical expressions are usually used in decision and
repetition structures to control the flow of the program.
Character variables are used to store characters (letters, numbers, punctuation
characters, etc). Characters are enclosed with a pair of single quotes in C++, like
'a', 'B', '7', '+', etc.
The sizes of variables might be different from those shown in the table, depending
on the compiler and the computer you are using. Use sizeof() operator to measure
the sizes of variable types in your system. The sizeof() operator returns the number
of bytes in variable or type.
/*
PROG: C1_06sizeof.cpp
C++ variable types and their sizes in bytes
*/
#include <iostream>
using namespace std;
int main()
{
cout <<"int = "<<sizeof(int)<<endl;
cout <<"short int = "<<sizeof(short int)<<endl;
cout <<"long int = " <<sizeof(long int)<<endl;
cout << "long long int =" <<sizeof(long long int)<<endl;
system("pause"); return 0;
}
int = 4
short int = 2
long int = 4
long long int =8
float = 4
double =8
long double =8
bool =1
char =1
Press any key to continue . . .
Exercise: 1 or 0
.
int main()
const float PI = 3.14;
.
Make a program that gets two numbers (let's say A and B) and then displays .
1 if the first number is bigger then second one, otherwise displays 0.
Input: Two numbers A and B.
Process: Comparing A and B. Use bigger than operator in the comparison
(A>B).
Output: 1 if the first number is bigger, 0 if the first number is not bigger. Visit the site
http://www.asciitable.com to
see the ASCII table.
Introduction to Programming 13
a corresponding number, or ASCII code. For example, the character for the number
1 has the code 49, capital letter A has the code 65, and a blank space has the code
32. This encoding system not only lets a computer store a document as a series of
numbers, but also makes it possible to transfer data from one computer to another.
In an ASCII file, each alphabetic, numeric, or special character is represented with a
7-bit binary number (a string of seven 0s or 1s). 128 possible characters are defined.
There are also ASCII extensions in use which utilize 8 bit codes to represent
international characters in addition to the standard ASCII scheme.
cout prints the ASCII character of an ASCII code with “char” casting. The following
program reads an ASCII code (an integer) and prints its character.
/*
PROG: C1_07ascii.cpp
Displaying the ASCII character of an ASCII code.
*/
#include <iostream>
using namespace std;
int main()
{
int code;
cout <<"Enter the ASCII code [between 0 and 127] ";
cin >> code;
system("pause");
return 0;
}
Introduction to Programming 15
Initialization of Variables
You can give the initial values to the variables during the declaration in C++. The
following program demonstrates how to declare different type of variables. Notice
that string objects can be initialized in two ways. You may use either of them in your
programs.
/*
PROG: c1_09init.cpp
Initializtion of variables.
*/
#include <iostream>
#include <string>
using namespace std;
int main()
{
string st1("I am learning "); //st1 is been initialized to
//"I am learging "
string st2 = "C++"; //st2 is been initialized to "C++"
int int1 = 8, int2 = 5; //int1 is been initialized to 8, and
//int2 to 5
float flt1 = 7.5, flt2 = 3.9; //flt1 is been initialized to
//7.5, and flt2 to 3.9
char ch1 = 'A'; //ch1 is been initialized to 'A'
bool bl1 = true, bl2 = false; //bl1 is been initialized to
//true, and bl2 to false
/*
PROG: c1_10file.cpp
Using input and output files.
*/
#include <fstream>
using namespace std;
int main()
{
ifstream fin("numbers.in"); //open input file
ofstream fout("numbers.out");//create and open output file
53 sum is 8
difference is 2
product is 15
integer quotient is 1
floating-point quotient is 1.66667
Introduction to Programming 17
SUMMARY
An algorithm is a set of ordered steps for solving a particular problem. A computer program is series of
instructions or statements, in a form acceptable to a computer, to cary out an algorithm. A programming
language is a human-created language that translates instructions from programmers to computers.
C++ is an object-oriented programming (OOP) language and the primary programming languages for
computers of today. Any C++ program consists of modules that are called functions. The primary function of
a C++ program is “main”. C++ uses cout and cin for printing and getting the data.
Operators are symbols (such as +, *, /) used to perform arithmetic, relational, logical, assignment, string,
bitwise etc. operations.
A variable is a named item used to represent data that can be changed while the program is running. Like a
variable, a constant is a named item but it has a fixed value that does not change.
ASCII (American Standard Code of Information Interchange) is an international code standard for
representation of characters, numbers, symbols and control characters, for use in data communication and
data storage. ASCII text does not include special formatting features and therefore can be exchanged and read
by most computer systems.
A string is a series of alphanumeric characters of any length. Strings are enclosed by double quotes in C++.
File processing consists of creating a file, storing data into a file, and retrieving data from a file. C++ performs
file processing with ifstream() and ofstream() functions that are defined in the <string> header file.
Introduction to Programming 19
PROGRAMMING PROBLEMS
1. (Sum of digits) Make a program that reads a three-digit integer from the file "number.in" and then
calculates sum of the digits and writes the result into the file "sum.out". Use the format of the sample
output in the file "sum.out". (Hint: Use the modulus (%) and integer division (/) operators.)
number.in sum.out
2. (Swapping) You are given two integer variables, let's say a and b. How can you interchange the values
of those two variables? In other words, a should get the value of b, and b should get the value of a.
a. Use a temporarily third variable
b. Do not use any additional variable
c. Use the swap function (swap(a, b);).
3. (To Upper) Make a program that reads a letter from the keyboard and then converts the letter to upper
case, if the letter is lower case.
a. Change the ASCII code of the letter.
b. Use the toupper function (a = toupper(a);).
Introduction to Programming 21
Flowchart Symbols
Terminal (Start, End)
The terminal symbol marks where the flowchar starts and where it
ends. Usually a starting terminal contains the word “START” or
“BEGIN”, and an ending terminal contains the word “END” or
“FINISH”.
The following code prints "passed" or "failed" depending on the average of the
student by using two separate if structures.
if (average<=60)
{
cout<<"failed"; //if the average is less than or equal
//to 60 print failed.
}
The first if structure checks whether the average is greater than 60, if so writes
"passed" to the output. The second if structure checks whether the average is less
than or equal to 60 if so writes "failed" to the output.
If we have a single statement in a "if" then it can be written without braces; but if we
have a compound statement to be executed we need to enclose them between
braces ({ }).
Truth in C++
C++ has a very simple logic
to cope with truth. Any value
other than zero is regarded as
true. Thus 1 and -2 are both
true just like 0.0001.Since they
are all different from zero. In
If any student passed, namely the average is bigger than 60, it is unnecessary to
the same logic 0, 0.0 or +0.0
check if he failed. If he passed it is obvious that he didn't fail, and in the same manner and -0 are all accepted as
if he didn't pass it is obvious that he failed. false.
Decision Structures 25
if (average>60)
cout<<"passed"; //if the average is greater than 60
prints passed.
else
cout<<"failed"; //if condition does not hold then
prints failed.
Let's improve our average example. What if we have an average value less than 0?
As a programmer we should always keep in mind the unexpected cases. We would
be able to respond to the user that any value less than 0 is not valid.
if (average>60)
{
cout<<"Passed";
}
else if (average<0)
{
cout<<"Wrong Input";
}
else
{
cout<<"Failed";
}
The if/else structure above checks the first condition, if it is satisfied, prints "Passed"
and skips the rest of the structure. If the first condition is not satisfied, the second
condition is checked, and so on. If none of the conditions is held, the last statement
is executed.
Exercise: Sign
! (Logical Not) operator has only one operand (unary operator) and returns the X !X
opposite of it. Not Operator gives true if the operand is false, and gives false if the
operand is true. For example: 0 1
!(5 > 7) //evaluates to true. 1 0
!true //evaluates to false.
The Truth Table of the NOT
Operator (!)
&& (Logical And) operator has two operands (binary operator). It returns true only if
both operands are true, and returns false otherwise. So we may need this operator X Y X && Y
when we have to perform a task if two conditions are fulfilled at the same time. For 0 0 0
example we want to determine if a given integer (num) is divisible by 3 and 7.
0 1 0
if ((num % 3 == 0) && (num % 7 == 0)) 1 0 0
cout<<"It is divisible by 3 and 7";
1 1 1
The Truth Table of the AND
Operator (&&)
|| (Logical Or) operator has two operands. It returns false if both operands are false,
and returns true otherwise. It can be used in a case if at least one of two conditions X Y X && Y
has to be true to perform a task. For example we want to check if a number is 0 0 0
divisible by 3 or 7.
0 1 1
if ((num % 3 == 0) || (num % 7 == 0))
cout<<"It is divisible by 3 or 7"; 1 0 1
1 1 1
Exercise: Letter The Truth Table of the OR
Operator (||)
Write a program that checks if an entered character is between 'a' and 'z' or 'A'
and 'Z'. Namely check if it is a letter or not.
Input: One character.
Output: "IT IS A LETTER" or "IT IS NOT A LETTER".
Decision Structures 27
Let's have a look how to use logical operators to determine whether a given year is
a leap year. Leap years are years with an extra day (February 29); this happens
almost every four years. Generally, leap years are divisible by four, but century years
are special, they must also be divisible by 400. Given a year decide whether it is a
leap year or not.
We know that the set of numbers divisible by 400 is a subset of the set of numbers
divisible by 100. And the set of numbers divisible by 100 is a subset of numbers
divisible by 4.
Implement the leap year problem without logical operators (by nested if/else)
Input: An integer for year value.
Output: "IT IS A LEAP YEAR" or "IT IS NOT A LEAP YEAR".
if (average>60)
cout<<"passed";
cout<<((average>60) ? "passed" : "failed");
else
cout<<"failed";
Decision Structures 29
cout<<"it is september";
break;
case 10 :
cout<<"it is october";
break;
case 11 :
cout<<"it is november";
break;
case 12 :
cout<<"it is december";
break;
default :
cout<<"wrong input";
}
Switch evaluates the value of expression and performs all of the instructions starting
from the true case of the expression's value till the ending brace.
If none of the cases has the value of expression then instructions under default part
are executed. You can have only one default statement in a switch statement block.
The break statement at the end of the case statement tells C++ to exit the switch
statement. C++ does not generate an error message if you omit a break statement.
However, if you omit it, C++ executes all the statements in the following case
statement, even if that case is false. In nearly all circumstances, this is not what you
want to do.
Sometimes we need to group the cases since we have the same operation for some
values. This can be understood better by an example. Again we are getting the
month number from the user but this time printing how many days this month has to
the screen.
/*
PROG: c2_02months.cpp
Read the order of a month and print how many days it has.
*/
switch (month)
{
case 2 : cout<<"it has 28 days"; break;
case 4 : case 6 : case 9 : case 11:
cout<<"it has 30 days"; break;
default : cout<<"it is 31 days"; break;
}
SUMMARY
Decision Structures 31
REVIEW QUESTIONS
1. What are the possible four outputs of the following 3. What is the final value of x?
program segment depending on the values of c1
and c2 ? int x=1;
if (c1) if (x >= 0) x += 5;
if (c2) if (x >=5) x += 2;
cout <<"if"<<endl; else x*=3;
else
cout <<"if/else"<<endl;
else if (!c2)
cout <<"?"<<endl;
else
cout <<"switch"<<endl;
c = (a>b) ? a : b;
a b c Expression Result
5 3 1 c && (a>b) true
0 4 4 (b==c) || a
((!a) && (b!=c)) &&
0 5 4
(b <= c )
4 2 3 (a > b) && (c < a)
0 20 F
21 40 D
41 60 C
61 80 B
81 100 A
if (avg > 0)
mark = F;
else if (avg > 20)
mark = D;
else if (avg > 40)
mark = C;
else if (avg > 60)
mark = B;
else if (avg > 80)
mark = A;
Decision Structures 33
PROGRAMMING PROBLEMS
1. (2nd Degree Equation) Make a program that reads three integers (a, b, c) from a user as coefficients
of a quadratic equation and calculate the solution set (x1, x2) of the equation.
For ax2+bx+c=0
delta = b2-4ac
x1= (- b + sqrt (delta)) /2a
x2= (- b - sqrt (delta)) /2a)
C++ provides us with sqrt() function to perform square root operations. It is defined under <math.h>
library. e.g. x=sqrt(y) x becomes square root of y. Sqrt funtion returns a value type of double.
sample inputs sample outputs
1 3 -10 x1=2 and x2= -5
1 -4 4 x1=2 and x2=2
1 -2 4 No real roots
2. (Mini Calculator) Write a program which reads two integers as operands and a character as an operator
between them, and prints the result.
sample inputs sample outputs
3*7 21
5 - 12 -7
32767 / 1024 31
3. (Character Recognizer) Write a program that reads a character from the user and tells if it is a letter
('a'..'.z', 'A'…'Z'), digit ('1'…'9') punctuation mark ('.','?',',','!' etc.) or special character (other than these).
sample inputs sample outputs
a letter
5 digit
? punctuation mark
/ special character
Making A Decision
The diamond-shaped symbol is used to make a decision in flowchart programming.
This symbol is unique in that it has two arrows coming out of it, from the right point
and bottom point, one corresponding to Yes or True, and one corresponding to No
or False.
Example: Positive
Exercise: Sum
Make a flowchart that gets two numbers (A and B), and then prints the sum of
these numbers (A+B) if the first number is bigger than the second number
(A>B).
input : Two numbers: A and B
output : A + B if A>B
Decision Structures 35
Example: Negative or Positive
Make a flowchart that gets an integer and then prints “Positive” if the integer
is bigger than zero, and prints “Negative” if the number is smaller than zero, or
prints “Zero” otherwise.
input : A number : A
output : “Positive” if A is bigger than zero
FCPro Logical Operators:
“Negative” if A is less than zero
! : Not
&& : And “Zero” if A is equal to zero
|| : Or
Exercise: Triangle
A C
Make a flowchart that gets three numbers and then determines if these three
numbers represent the length of all sides of a triangle.
Executing a block of code is one of the most basic but useful tasks in programming.
Many programs or Web sites that produce complex output are really only executing
a single task many times.
Let's make a basic program to understand the while loop. The following program
prints the numbers from 1 to 10. It prints the value of a variable (that is a counter)
one at a time, and repeats this process ten times. To print the numbers from 1 to 10,
the variable counter is initialized to one, and its value is increased by 1 in each
iteration. On the other hand, the condition "counter <= 10" checks if the counter
exceeds its final value.
The key concepts of looping are, the counter, the initial value of the counter, the final
value of the counter, increment or decrement factor of the counter, the condition and
the statements to be executed.
The variable "counter" is our counter in this program. Since it gets only the whole
numbers from 1 to 10, its type is integer. The initial value of counter is 1, the final
value of counter is 10, and the increment factor of the counter is 1.
"counter <=10" is the condition of the loop. The while loop checks the condition at
the header of the structure. This condition states that the statement will be executed
while the counter is not bigger than 10.
"cout <<counter<<" ";" is the statement that is executed each time in the looping
process. The purpose of the program is to print the consecutive numbers from 1 to
10 thus the value of the counter must get those values one by one in each turn.
Repetition Structures 39
The following three "counter++" increases the value of counter by one. This statement can be written as
statements are all the same: "counter = counter + 1". C++ used this syntax at the first time. Usually
c++; programmers use only 'c' instead of "counter" as a variable name, so "c++" means
c = c+1;
increase the value of a counter “c” by one. I think, this is where the name of this
programming language is comes from.
c += 1;
/*
PROG: C3_01while.cpp
Printing the numbers from 1 to 10 increasing by 1.
*/
#include <iostream>
using namespace std;
int main()
{
int counter = 1; //initialize the counter to its
//starting value
while (counter <= 10) //continue looping until counter
//is less than its final value
{
cout <<counter<<" "; //print the current value of the
//counter
counter++; //counter gets its next value
}
system("PAUSE"); return 0;
}
Flowchart of the Program
“while”
1 2 3 4 5 6 7 8 9 10 Press any key to continue . . .
int main()
{
int a=5;
cout <<"initial a is "<<a<<endl;
cout <<"after a++ is "<<a++<<endl;
cout <<"current value of a is "<<a<<endl;
cout <<"after ++a is "<<++a<<endl;
system("pause"); return 0;
}
initial a is 5
after a++ is 5
current value of a is 6
after ++a is 7
current value of a is 7
after --a is 6
Press any key to continue . . .
Example: Molecules
chem.in chem.out
2 18
12
16 1
/*
PROG: c3_03molecules.cpp
*/
#include <fstream>
using namespace std;
int main()
{
int n, weight, quantity;
int sum=0, counter=1;
ifstream fin("chem.in");
ofstream fout("chem.out");
Repetition Structures 41
fin >> n; //How many kinds of atoms?
fin.close();
fout.close();
system("pause");
return 0;
Exercise: Molecules
Exercise: Train
A train leaves the first station with N passengers and visits K stations before
it arrives at the last station. In each station some passengers got off the train
and some passengers got on the train. Everybody in the train got off at the last
station. Make a program that calculates how many passengers got off the train
at the last station.
The first line of the input has two integers N and K. Each of the following K lines
contains two integers, the first one denotes the number of passengers who got
off the train at that station, and the second one denotes the number of
passengers got on the train at that station. The output should hava a single
integer that is number of passengers who got off the train at the last station.
Input file: train.in
output file: train.out
int main()
{
int N, total, mark, counter;
Repetition Structures 43
counter++; //Increment the counter.
}
system ("pause");
return 0;
}
Sentinel-Controlled Repetition
In the case when users don't know the number of the repetitions in advance, a
sentinel-controlled repetition can be used instead of a counter-controlled repetition.
The idea of a sentinel controlled repetition is that there is a special value (the
"sentinel") that is used to say when the loop is done. The sentinel value must be
chosen carefully so that it cannot be confused with a legitimate value. Sentinel-
controlled repetition is called "indefinite repetition" because the number of repetitions
is not known in advance.
/*
PROG: c3_05sentinelcont.cpp
Class average with a sentinel-controlled loop. Make a program to
calculate average of a class after an exam. Your program will
process an arbitrary number of the marks. The marks are between 1
and 5. Use 0 as sentinel value to end the program execution.
*/
#include <iostream>
using namespace std;
int main()
{
int total, mark, nrMarks;
//Get the first mark and set the nrMarks to 1.
cout<<"Enter the first mark: ";
cin >> mark;
total = mark;
nrMarks = 1; //We have got one mark so far.
Flowchart of the Program //Get the rest of the marks one by one and add to total.
“sentinelcont” while (mark != 0) //Continue if mark is not sentinel
Repetition Structures 45
Another Random Scribd Document
with Unrelated Content
The Project Gutenberg eBook of The Diamond
Ship
This ebook is for the use of anyone anywhere in the United States
and most other parts of the world at no cost and with almost no
restrictions whatsoever. You may copy it, give it away or re-use it
under the terms of the Project Gutenberg License included with this
ebook or online at www.gutenberg.org. If you are not located in the
United States, you will have to check the laws of the country where
you are located before using this eBook.
Language: English
BY
MAX PEMBERTON
To
CONTENTS.
CHAPTER PAGE
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookultra.com