Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

CPE 112-Chapter2 - Updated2019

Download as pdf or txt
Download as pdf or txt
You are on page 1of 39

CMPE 112

CMPE112,CTPR112,ITEC112,MISY112,IT112,COMP112,CPE112

Computer Programming

Chapter 1 – Introduction to C/C++ programming, program


flow, input and output operations.
Why do we learn
C/C++ programming? (1)
 C has been used successfully for every type of programming
problem imaginable from operating systems to spreadsheets
to expert systems - and efficient compilers are available for
machines ranging in power from the Apple Macintosh to the
Cray supercomputers.

 The largest measure of C's success seems to be based on


purely practical considerations including but not limited to:

 The portability of the compiler;


 The standard library concept;
 a powerful and varied repertoire of operators;
 an elegant syntax;
Why do we learn
C programming? (2)
 C is often called a "Middle Level" programming language. This
is not a reflection on its lack of programming power but more a
reflection on its capability to access the system's low level
functions.

 Most high-level languages (e.g. Java, C#) provides everything


the programmer might want to do already built into the
language. A low level language (e.g. assembler) provides
nothing other than access to the machines basic instruction
set. C stands just in the middle of these and can handle both
ends effectively.
Learning C
through C++ structure
 In this lecture, we will learn C programming language via C++
syntax.

 This means that you will be learning the structured


programming pattern (i.e. C) and not the object oriented
programming (C++).

 However, we will be using C++ syntax such as cin and cout


statements due to their practical and easy structure.
C program

 Always remember that, a C program is a combination of


functions.

 A function is the combination of a set of instructions to


perform a specific task.

 Every C language program contains at least one function


(e.g. the main function as it is the entry to the console
applications).
First C/C++ program
Include the contents of a standard input/output header.

Inject all the names of entities that exist in the std


namespace into the global namespace. Like cout, cin,
endl input/output header.

The main function of a program where the execution


will start.
int means that main function "returns" an integer
value.
void means that main function does not take an input.

Entire line called a statement. All statements must end


with a semicolon (;).
Prints the string of characters within quotes (" ").

Every C language program must end with a return 0 to


Curly brackets, used to
tell the Operating System that the program finished
indicate a function body.
(terminated) successfully.
The value 0(zero) represents successful termination.
Following the Correct
Syntax
 C/C++ is a compiler language, which needs to recognize every
single statement, library and command in order to run.

 The statements mentioned below are going to be a scaffold for


all of the programs you are going to write within this course
content

You will modify and put extra bits in each


program you write but the pattern you
see on the right would exist in each
program you write
Splash Screen Problems
 During your C programming practices, you might encounter a
difficulty in viewing the console output screen as the generated
C++ program would run the command prompt so fast that the
entire program would be executed in the blink of an eye.

 This is a generic problem in Windows Environment and often referred


to as the Splash Screen problem. The splash screen particularly
happens outside of Borland compilers and can be solved by
pausing the output screen meaning that until you enter a character
or press any key - the screen would be frozen. There are multiple
ways to solve this problem.

 One easy way of addressing this issue is using System(“Pause”);


statement.
System(“Pause”);
creates problems
 While System(“Pause”); solves the splash screen problem to some
extent, the code is incredibly nasty and a Windows Specific
command.

 System(“Pause”); could cause more problems than it actually solves.



 Additionally, it creates a backdoor in the application which might
allow your applications to be violated.

 Hence, we do not recommend the use of System(“Pause”); To


solve the Splash Screen problem, you can use the following two
statements: cin.ignore(); cin.get();

 These two statements would freeze the screen in a relatively efficient


way until you press a key on your keyboard. More importantly, the
statements given above are platform independent and would work
in any Operating Systems (OS).
Standard Output
 cout is our standart output function and the monitor of a
computer is the standard output device.
 The backslash (\) is called an escape character. It
indicates that cout is supported to do something out of the
ordinary.
 When encountering a backslash in a string, the compiler
looks ahead at the next character and combines it with
the backslash to form an escape sequence.
 Some common escape sequences are as follows;
Escape Sequence Description
\n Newline. Position the cursor at the beginning of the next line.

\t Horizontal tab. Move the cursor to the next tab stop.


\a Alert. Sound the system bell.
\\ Backslash. Insert a backslash character in a string.

\" Double quote. Insert a double quote character in a string.


E.g. Standard Output
C Program C Program Output

#include <iostream> #include <iostream> Hello


using namespace std; using namespace std; World
int main(void) int main(void)
{ {
cout<<"Hello"; cout<<"Hello\nWorld";
cout<<"\n";
cout<<"World"; return 0;
}
return 0;
}

C Program C Program Output

#include <iostream> #include <iostream> Hello World


using namespace std; using namespace std;
int main(void) int main(void)
{ {
cout<<"Hello"; cout<<"Hello\tWorld";
cout<<"\t";
cout<<"World"; return 0;
}
return 0;
}
E.g. Standard Output
C Program C Program Output

#include <iostream> #include <iostream> HelloWorld


using namespace std; using namespace std;
int main(void) int main(void)
{ {
cout<<"Hello"; cout<<"HelloWorld";
cout<<"World";
return 0;
return 0; }
}

C Program C Program Output

#include <iostream> #include <iostream> Hello World


using namespace std; using namespace std;
int main(void) int main(void)
{ {
cout<<"Hello "; cout<<"Hello World";
cout<<"World";
return 0;
return 0; }
}
E.g. Standard Output
C Program Output

#include <iostream> Hello


using namespace std; World
int main(void) Hello World
{
cout<<"Hello";
cout<<"\nWorld\n";
cout<<"Hello";
cout<<"\tWorld";

return 0;
}

C Program Output

#include <iostream> “Hello World”


using namespace std;
int main(void)
{
cout<<"\"Hello World\"";

return 0;
}
Variables
 A variable is a storage location which contains some
known or unknown quantity or information, particularly a
value generated during the run-time of the program.

 A variable is usually a non-constant value that changes


during the program according to the actions of the users.

 If a variable is initialized to a value by default and this


never changes throughout the run-time, the variable is
called a Constant.

 In C/C++, the constant values are defined with const


keyword.
Variable naming rules
 Consist of letters (a,b,c,d, ...), digits (0,1,2,3, ...) and
underscore (_)
 Cannot start with a number or dash
 Cannot contain blank space or dash between the
characters
 Cannot contain special characters (with the exception of
_, $, £)
 Cannot be programming reserved words

Correct Incorrect
ali74 74Ali
monthly_Salary Monthly salary
firstNameOfCustomer first-name-of-customer
multiply *
Variable definition
 In order to use a variable in C, we must first declare it specifying
which data type we want it to be.

 Variables are just a position in the memory (RAM) to which you


can give a name. Rather than using the address #A234DE987211,
we give the variable a name such as height

 The syntax to declare a new variable is to write the specifier of


the desired data type (like int, char, float...) followed by a valid
variable identifier.
Data types Storage size Detail Examples
int 2 or 4 bytes Integer int num;
float 4 bytes Floating point int x,y,z;
double 8 bytes Floating point char word;
char 1 byte Character double w; char key;
Variable initialization
 Variables can be initialized (assigned an initial value) in
their definition or after definition.

Examples Examples
int num; num=2; int x=85, n=5;
int num=2;
double y=0.5, z=3.14;
char word; word=‘a’;
char word=‘a’; char w=‘k’; key=‘C’;

As discussed before, if a variable is initialized to a value by


default and this never changes throughout the run-time, the
variable is called a Constant.
Variable/Identifier
 In programming Memory locations are called VARIABLES.
For example;
 int x=5;
 statement will create a new variable to keep integer
numbers inside. The name of the variable will be x and
initial value of x will be 5, as shown in the below memory
layout;

...
1230H
1231H 5 x
1232H
1233H
1234H
...
Examples
C Program C Program Output

#include <iostream> #include <iostream> 58


using namespace std; using namespace std;
int main(void) int main(void)
{ {
int x; int x=58;
x=58; cout<<x;
cout<<x;
return 0;
return 0; }
}

C Program C Program Output

#include <iostream> #include <iostream> 582


using namespace std; using namespace std;
int main(void) int main(void)
{ {
int x,y; int x=58,y=2;
x=58; cout<<x;
y=2; cout<<y;
cout<<x<<y;
return 0;
return 0; }
}
Examples
C Program C Program Output

#include <iostream> #include <iostream> 0.5 a


using namespace std; using namespace std;
int main(void) int main(void)
{ {
double m=0.5; double m=0.5; char k=‘a’;
char k=‘a’; cout<<m;
cout<<m<<”\t”<<k; cout<<”\t”<<k;

return 0; return 0;
} }

C Program Output

#include <iostream> result is as follows:


using namespace std; b
int main(void) 2.33 8
{
double m=2.33;
char k=‘b’;
int num_1=8;
cout<<”result is as follows:\n”;
cout<<k<<”\n”<<m<<”\t”<<num_1;

return 0;
}
Standard Input
 cin is our standard input function and the keyboard of a
computer is the standard input device.

1 Waits user to enter a value:

2 User enters a value, ex 3:

3 User press enter:


E.g. Standard Input
C Program C Program Output

#include <iostream> #include <iostream> 56


using namespace std; using namespace std;
int main(void) int main(void)
{ {
int x,y; int x,y;
cin>>x; cin>>x>>y;
cin>>y; cout<<x<<y;
cout<<x<<y;
return 0;
return 0; }
}
E.g. Standard Input
Expressions
 Expressions are combinations of operators and their
operands which are used to modify the values of
variables.

Arithmetic operators
Operation Operator Expression

Multiplication * b*m
Division / x/y
Modulus % r%s
Addition + f+7
Subtraction - p-c

a=b+3 Operands: a b 3
Operators: = +
Comparison Operators
Equality & relational operators

Operator Expression Explanation


== x == y x is equal to y
!= x != y x is not equal to y
> x>y x is greater than y
< x<y x is less than y
>= x >= y x is greater than or equal to y
<= x <= y x is less than or equal to y

a <= 3 Operands: a 3
Operators: <=
Expressions
Assignment operators
Assume: int c = 3, d = 5, e = 4, f = 6, g = 12;
Operator Expression Explanation Assigns
+= c += 7 c=c+7 10 to c
-= d -= 4 d=d-4 1 to d
*= e *= 5 e=e*5 20 to e
/= f /= 3 f=f/3 2 to f
%= g %= 9 g=g%9 3 to g

a += 3 Operands: a 3
Operators: +=
Expressions
Increment & decrement operators

Operat Expressi Explanation


or on
++ ++a Increment a by 1
then use the new value of a in the expression.
++ a++ Use the current value of a in the expression,
then increment a by 1.
-- --b Decrement b by 1
then use the new value of b in the expression.
-- b-- Use the current value of b in the expression,
then decrement b by 1.

Assume: int x = 3, y = 3, a = 9, b = 9
Operator Expression Explanation Firstly Secondly
assigns assigns
++ c= x++ + 7 c= (x++) + 7 10 to c 4 to x
++ c= ++y + 7 c= (++y) + 7 4 to y 11 to c
-- c= a-- + 7 c= (a--) + 7 16 to c 8 to a
-- c= --b + 7 c= (--b) + 7 8 to b 15 to c
Exercise 1:
 Write a complete C program for the following problem; Get
two numbers from the user, and calculate and display the
average of numbers.

Exercise 2:
 Write a complete C program for the following problem; Get
three numbers from the user, and calculate and display the
product (multiplication) of numbers.

Exercise 3:
 Write a complete C program for the following problem; Get
a number from the user, and calculate and display the
square of that number.
𝑁𝑁𝑁𝑁𝑁𝑁𝑁𝑁𝑁𝑁𝑁𝑁 = 5 => 𝑆𝑆𝑆𝑆𝑆𝑆𝑆𝑆𝑆𝑆𝑆𝑆 𝑜𝑜𝑜𝑜 𝑁𝑁𝑁𝑁𝑁𝑁𝑁𝑁𝑁𝑁𝑁𝑁 = 52 = 5 ∗ 5 = 25

𝑁𝑁𝑁𝑁𝑁𝑁𝑁𝑁𝑁𝑁𝑁𝑁 = 8 => 𝑆𝑆𝑆𝑆𝑆𝑆𝑆𝑆𝑆𝑆𝑆𝑆 𝑜𝑜𝑜𝑜 𝑁𝑁𝑁𝑁𝑁𝑁𝑁𝑁𝑁𝑁𝑁𝑁 = 82 = 8 ∗ 8 = 64


Exercise 4:
 Write a complete C program for the following problem; Get
two sides of rectangle from the user, and calculate and
display the area.

l𝑒𝑒𝑒𝑒𝑒𝑒𝑒𝑒𝑒 = 4 𝑤𝑤𝑤𝑤𝑤𝑤𝑤𝑤𝑤 = 5 => 𝐴𝐴𝐴𝐴𝐴𝐴𝐴𝐴 = 𝑙𝑙𝑙𝑙𝑙𝑙𝑙𝑙𝑙𝑙𝑙 ∗ 𝑤𝑤𝑤𝑤𝑤𝑤𝑤𝑤𝑤 = 4 ∗ 5 = 20


Exercise 5:
 Write a complete C language program to display the
digits of a 3 digit integer on separate lines.

#include <iostream>
using namespace std;
int main(void)
{ Steps of trace x dg output
int x,dg;
cin>>x; 1 863
2 863/100=8
dg = x / 100; 3 863%100=63
x = x % 100;
cout<< dg ; 4 8
5 63/10=6
dg = x / 10; 6 63%10=3
x = x % 10;
7 6
cout<< dg ;
8 3/1=3
dg = x / 1; 9 3%3=0
x = x % 1; 10 3
cout<< dg ;

return 0;
}
Exercise 6:
 Write a complete C language program to evaluate the
following equation. Users should be able to input x and z
from the keyboard. Then, calculate and display the value
of y. The formula is defined for floating point numbers.

𝑥𝑥−2 ×4
a) 𝑦𝑦 =
𝑧𝑧+8

𝑥𝑥 − 𝑧𝑧/3
b) 𝑦𝑦 =
2𝑧𝑧−7
Trace & Output Type
Questions
 Throughout the course, you will come across to a point
where you will be given the source code and asked to
find the output.

 These type of questions are trace or output questions.

 These questions help you to understand an already


written code which would be a frequent case in the
business world as you will often be asked to modify an
existing code rather than writing everything from scratch.
Exercise 7:
 What is the output of the following C program?

OUTPUT:
Exercise 8:
 Write a C program that will ask the user to enter his/her
name, surname and student number. Accept up to 41
characters for name and surname.
 The program will display the entered name, surname
and student number on the screen
Exercise 8 - Sln:
Exercise 9:
 Write a C program to receive 3 numbers from
keyboard and print them in reverse order on the
screen.
Exercise 9 - Sln:
Exercise 10:
 What is the output of the following C program?

#include <iostream>
= i + j * 2 –i / 3
using namespace std;

int main(void)
{
= 14 + 5 * 2 –14/3
int i=14, j=5, k=3;

int answer=0;
= 14 + 10 –4
answer=i+j*2-i/3;
= 24 –4
cout<<”answer = ”<< answer;

return 0;
= 20
}
Revision
 First C program

 Standard Input & Output

 Variables

 Expressions
 Arithmetic operators

 Equality and relational operators

 Assignment operators

 Increment and decrement operators

 Exercises

You might also like