0% found this document useful (0 votes)
25 views55 pages

Chapter 2

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1/ 55

Programming With C/C++

Chapter 2: Variables, Data Types & Operators

Dr. Umair Ali Khan


Associate Professor & Chairman,
CSE Department, QUEST, Nawabshah
Email: umair.khan@quest.edu.pk
Website: https://umair-khan.quest.edu.pk
Contents
 Escape sequences
 Variables and Constants
 Data Types or Types of Variables
 The scanf ( ) function
 Address Operator
 The getch ( ) function
 Different types of Operators
Escape Sequence
 Character combinations consisting of a backslash (\)
followed by a letter are called "escape sequences."
 To represent a newline, single quotation mark, or certain
other characters, you must use escape sequences.
 Escape sequences are non-printing characters.
 \n new line
 \t tab
 \r carriage return
 \a alert
 \\ backslash
 \” double quote
Variables
 Variables are the most fundamental aspect of any
computer language.
 A variable is a space in the computer’s memory set
aside for a certain kind of data and given a name for
easy reference.
 Therefore, variables are used so that the same space in
memory can hold different values at different times. (But
one value at a time).
 Variable names correspond to locations in computer
memory.
 Every variable has a name, type and value.
 Data values processed in the program are stored in
memory locations and referenced through variables.
Variables . . .
 Same idea used in algebra: y = 3x +5
x and y are the ‘variables’;
3,5 are the ‘constants’
 Inside the computer:
a variable is a reserved location in
memory, and holds data that are allowed
to change.
Variables
 ALWAYS declare a variable before use!
 forgot? error messages …

 ALWAYS set a variable’s value before use!


 forgot? starting value will be unpredictable…

 What does ‘declaring’ a variable do?


 reserve a memory location that will store the value of
the variable.
 assign the variable name to that location.
How to ‘declare’ Variables?
 Any variable must be declared (defined) before it can be used in
the program.
 The same variable cannot be defined more than once within the
same block.
 The general form of a variable declaration:
 data_type variable_name ;
 Example: int counter;
 Where? Declare variables at the start of a function, right after
the opening brace {
 Variables of the same type can be defined in one declaration:
 data_type var_name1 , var_name2 , … , var_namen;
Assigning value to variable
• A programmer can assign a unique value to the
variable.
• The general form of an assignment statement is
type var-name = value;
OR
var-name = value;
• For example:
int year = 2001;
int number = 6;
Variables - declaring
var name memory loc
main() hours ? 4278
{ payrate ? 427C
float hours; 4280
float payrate; grosspay ?
float grosspay; j ? 4284
int j;
Variables - declaring
var name memory loc
main() hours 40.0 4278
{ payrate ? 427C
float hours; 4280
float payrate; grosspay ?
float grosspay; j ? 4284
int j;

hours = 40.0;
Variables - declaring
var name memory loc
main() hours 40.0 4278
{ payrate 20.0 427C
float hours; 4280
float payrate; grosspay ?
float grosspay; j ? 4284
int j;

hours = 40.0;
payrate = 20.00;
Variables - declaring
var name memory loc
main() hours 40.0 4278
{ payrate 20.0 427C
float hours;
float payrate; grosspay 800.00 4280
float grosspay; j ? 4284
int j;
note: referencing a
variable only "reads"
hours = 40.0; it (non-destructive).
payrate = 20.00; Assigning to a
grosspay = hours * payrate variable overwrites
whatever was there
(destructive).
Variables - declaring
var name memory loc
main() hours 40.0 4278
{
float hours; payrate 20.0 427C
float payrate; grosspay 800.00 4280
float grosspay; j 5 4284
int j;
note: referencing a
hours = 40.0; variable only "reads"
payrate = 20.00; it (non-destructive).
grosspay = hours * payrate Assigning to a
variable overwrites
j = 5;
whatever was there
(destructive).
Variables - declaring
var name memory loc
main() hours 40.0 4278
{
float hours; payrate 20.0 427C
float payrate;
float grosspay; grosspay 800.00 4280
int j; j 5 6 4284
hours = 40.0; note: referencing a
payrate = 20.00; variable only "reads"
grosspay = hours * payrate it (non-destructive).
j = 5; Assigning to a
j = j + 1;
variable overwrites
}
whatever was there
(destructive).
Rules for Naming Variables in C
 In C, variable names are built from:
 the letters of the alphabet (A-Z, or a-z)
 the digits 0 through 9
 the underscore. (no other special characters!)
 A variable name must start with a letter or an underscore.
 Spaces are not allowed in variable name.
 Only the 32 characters of a variable name are significant.
 Identifiers are case sensitive: sum≠SUM≠Sum≠sUM
 A variable name must not be the same as a reserved
word.
Reserved words / Key Words in C and C++

 Certain words have a special meaning to the


C or C++ compiler.
 They are called reserved words or keywords.
 We should not try to use these words as
names of variables or function names in a
program.
 The keyword list for C contains 32 words .
Some Keywords in C and C++
asm double new switch
auto else operator template
break enum private this
case extern protected throw
catch float public try
char for register typedef
class friend return union
const goto short unsigned
continue if signed virtual
default inline sizeof void
delete int static volatile
do long struct while
Variable Names
 Valid variable names:
totalArea _main
counter1 isEmpty
Count_trees pNuts
temp_in_F m_size
 Invalid variable names:
$product int main not-this
total% 19 3rd Student score
 Legal, badly-chosen variable names:
l11 (is it L11, L1L, LL1, or LLL?)
x (what does it mean?)
maximum_number_of_students_in_my_class
a23456789_123456789_123456789_12345678
Data Type
 Programming languages store and
process data in various ways depending
on the type of the data; consequently, all
data read, processed, or written by a
program must have a type.
 A data type is
 A set of values, and
 A set of operations on those values
Data Type
 A data type is used to:
 determines how much storage space is
allocated to variables.
 Identify the type of a variable when the
variable is declared.
 Identify the type of the return value of a
function
 Identify the type of a parameter expected by a
function.
Classifications of Data Types
 Fundamental or Built-in data types
 int, char, double, float, void
 void – used to denote the type with no values.
 int – used to denote an integer type
 char – used to denote a character type
 float, double – used to denote a floating
point type.
 Derived data types
 array, string, structure, Union, Enumeration .
DATA TYPES
TYPE MEMORY USE RANGE

char 1 BYTE 0 to 255 (ASCII)


- 128 to 127

int 2 BYTES -32768 to 32767

float 4 BYTES 3.4E-32 to 3.4 E+38

double 8 BYTES 1.7E-308 to 1.7 E+308

void 0 valueless
TYPE
DATA
EXAMPLES
TYPES
char ‘A’ ‘b’ ‘$’ ‘9’

int 1 250 4500

float 3.5 42.56 345.6789

double 3.5647290… 486.145875...

void valueless

 Characters are stored internally as integers.


 Characters are interpreted according to the character set.
 The most commonly used character set is ASCII.
 In the ASCII character set, A is represented by the number 65.
// program using variables
void main (void)
{ ‘declare’ each variable;
int rollno; write a statement that
char section; to set its type and name
float gpa = 3.25;
rollno = 100;
section = ‘A’;
printf (“ My name is %s. My Roll no is %d.”, “Ahmed”, rollno );
printf (“ My section is %c and my GPA is %f.”, section, gpa);
}
Output:
My name is Ahmed. My Roll no is 100. My section is A
and my GPA is 3.25.
scanf( ) FUNCTION
 scanf function allows the programmer to accept the
input from a keyboard.
 scanf( ) allows us to enter data (at run time) from keyboard
that will be formatted in a certain way.
 Syntax:
scanf (“format control string”, &variable list);

 For example:
scanf ( “ %s %d %f”, &name, &age, &per );

 Here is a new symbol:


& ( Address Operator )
scanf( ) FUNCTION
 The format control string indicates the type of data that should be
input by the user.

 Format control string Data Type


%c character
%d integer
%f float
%lf double
 The ampersand (&) is called the address operator in C.
 This is placed before the variable name in a scanf( ).
 The address operator tells scanf( ) the location in memory in
which the variable will be stored. The computer then stores the
value of the variable at that location.
scanf ( )
Examples:
int x,y;
float grade;
char letter;

scanf (“%d”, &x);


scanf (“%f”, &grade);
scanf (“%c”, &letter);
scanf (“%d %d”, &x, &y);
// Addition of two numbers using scanf ( )

#include < stdio.h >


#include <conio.h>
main( )
{
int integer1, integer2, sum;
printf ( “Enter first integer : ” );
scanf ( “%d”, &integer1 );
printf ( “Enter second integer: ” );
scanf ( “%d”, &integer2 );
sum = integer1 + integer2;
printf ( “Sum is %d ”, sum );
getch();
}
scanf( ) . . .
 Spaces are not accepted upon inputting.
 The values that are supplied through the keyboard
must be separated by either blank(s), tab(s), or
newline(s).
 Do not include these escape sequences in the format
string (in scanf ( ) ).
 This is an input function in Turbo C, while printf is
an output function.
 All the format specifications that we learnt in
printf( ) function are applicable to scanf( ) function
as well.
getch( ) function
• So far for input we have used the scanf( ).
• However, for some situations the scanf( ) has one
weakness...
– you need to hit the Enter key before the function can digest
what you have typed.
• However, we often want a function that will read a
single character the instant it is typed without waiting
for the Enter key to be hit.
• getch( ) and getche( ) are two functions which serve
this purpose.
• These functions return the character that has been
recently typed.
getch ( ) function
• You do not have to press the [ Return ] Key.
• Unformatted input function.
• It only takes a character.
• If you typed any wrong character, you cannot move
backward to correct it.
– get  get from outside
– ch  character
–e  echo ( display )
• getch ( ) vs scanf ( )
/* programming example to demonstrate the getch( ) and
getche( ) functions. */

void main (void)


{
char ch;
print ( “ Type any Charater:” );
ch = getch ( ); // will not echo the character
printf ( “ \n The character you typed was %c”, ch);
printf (Type another character:”);
ch = getche( ); // will echo the character
printf ( “ \n The character you typed was %c”, ch);
}
Class Activity 1
• Write c program to take name, address, age and height
in feet (a float value should be entered), print all values
in new lines.
Class Activity 2
• Write a program which takes 2 inputs, x and y, and
displays their sum, product, difference and division as
follows:
Class Activity 3
• Write a program to calculate area of circle.
Operators
• Operators are symbols that causes a program to do
something to variables.
• In C Language there are basically 4 types of operators.
1. Arithmetic Operator
2. Relational Operator
3. Arithmetic Assignment Operator
4. Increment / Decrement Operator
5. Logical Operators
6. Special Operators (&, sizeof(), *, ?: )
7. Bit-wise operators
Arithmetic Operator
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder
• Remainder Operator ( % ) is also called Modulo
Operator.
• For Example:
Answer = 13 % 5
Answer = 3
Arithmetic Operator
Operator Precedence- Order of Evaluation
Arithmetic Operators – Order of Evaluation

Another example:

x = 6 / 2 + 1 - 3 + 8 * 4;
x = 33;

x = 6 / (2 + 1) - (3 + 8) * 4;

x = -42;
Arithmetic Assignment Operator
+= Addition Arithmetic Assignment Operator
-= Subtraction Arithmetic Assignment Operator
*= Multiplication Arithmetic Assignment
Operator
/= Division Arithmetic Assignment Operator
%= Remainder Arithmetic Assignment Operator

For Example:
total = total + number;
total + = number;
Arithmetic Assignment Operator

Example of arithmetic assignment operators:

int a = 4, b = 2, c = 36 ;
a += b ; /* This adds b to a, a = ? */

c /= a + b ; /* What is value of c now?


*/
Arithmetic Assignment Operator
Example of arithmetic assignment operators:

int a = 4, b = 2, c = 36 ;
a += b ; /* This adds b to a, a = ? */
[ Answer: a = a + b, so a = 4 + 2 or a = 6 ]
c /= a + b ; /* What is value of c now?
*/
Arithmetic Assignment Operator
Example of arithmetic assignment operators:

int a = 4, b = 2, c = 36 ;
a += b ; /* This adds b to a, a = ? */
[ Answer: a = a + b, so a = 4 + 2 or a = 6 ]
c /= a + b ; /* What is value of c now? */
[ Answer: c = c / (a + b), and a = 6 now,
so c = 36 / (6 + 2), so c = 36 / 8 or c = 4 ]
Relational Operators
Operator: Meaning:

< Less Than


> Greater Than
<= Less Than or Equal To
>= Greater Than or Equal To
== Exactly Equal To
!= Not Equal To
Relational Operators
• Used for asking questions like:
Is x bigger than 10?

• In C, the value of 1 stands for true and 0


stands for false. But C will recognize any
non zero value as true.

• NOTE: "==" is NOT same as "="


Program Using Relational Operator
void main (void)
{
int age ;
age = 15;
printf ( “ Is age less than 20 ? %d \n “, age < 20 );
age = 30;
printf ( “ Is age less than 20 ? %d \n “, age < 20 );
getch ( );
}

Output:
Is age less than 20 ? 1
Is age less than 20 ? 0
Increment/Decrement Operators

Operator: Meaning: When?

count++ ; count = count + 1 ; After use


++count ; count = count + 1 ; Before use
count-- ; count = count - 1 ; After use
--count ; count = count - 1 ; Before use
Increment/Decrement Operators
Examples of increment/decrement operators:

int a = 4, b = 2, c;
c = ++a + b-- ;
/* What are the values of a, b, c now? */

c = b-- - ++a ;
/* What are the values of a, b, c now? */
Increment/Decrement Operators
Examples of increment and decrement operators:

int a = 4, b = 2, c;
c = ++a + b-- ;
/* What are the values of a, b, c now? */
(Answers: a = 5, b = 1, c = 7)
c = b-- - ++a ;
/* What are the values of a, b, c now? */
Increment/Decrement Operators
Examples of increment and decrement operators:
int a = 4, b = 2, c;
c = ++a + b-- ;
/* What are the values of a, b, c now? */
(Answers: a = 5, b = 1, c = 7)
c = b-- - ++a ;
/* What are the values of a, b, c now? */
(Answers: a = 6, b = 0, c = -5)
Logical Operators
Homework
1. Write a program that inputs your age in years and then
calculate the total number of months, weeks and days.
2. Write a program that inputs marks for 5 subjects and then
calculate the total marks obtained and the average
3. Write a program that inputs a number and checks if it is
even or odd (Hint: use remainder operator)
4. Write a program that takes temperature in Fahrenheit as
input and convert it into Celcius
5. Write a program that takes input the coefficients (a,b,c) of a
quadratic equation and calculate its roots x1 and x2 with the
following formulae:

You might also like