Week-2 Types Operators Expressions
Week-2 Types Operators Expressions
M Alqarni INFO-1221
3
• Let us take a look at the various parts of the above program −
• The first line of the program #include <stdio.h> is a preprocessor command, which
tells a C compiler to include stdio.h file before going to actual compilation.
• The next line int main() is the main function where the program execution begins.
• The next line /*...*/ will be ignored by the compiler and it has been put to add
additional comments in the program. So such lines are called comments in the
program.
• The next line printf(...) is another function available in C which causes the
message "Hello, World!" to be displayed on the screen.
• The next line return 0; terminates the main() function and returns the value 0.
M Alqarni INFO-1221
4
Types, Operators and Expressions
M Alqarni INFO-1221
5
Data types and sizes
• The true power of programs you create is their manipulation of data. In order
to truly take advantage of this power, you need to better understand the
different data types you can use, as well as how to create and name variables.
C has a rich variety of math operators that you can use to manipulate your
data. In this chapter we will cover:
M Alqarni INFO-1221
6
Data Types and Sizes
There are only a few basic data types in C:
•Char: a single byte, capable of holding one character in the
local character set.
•Int: an integer, typically reflecting the natural size of
integers on the host machine.
•Float: single-precision floating point.
•Double: double-precision floating point.
M Alqarni INFO-1221
7
Data types (MIDTERM!)
• Data types in c refer to an extensive system used for declaring variables or functions of
different types. The type of a variable determines how much space it occupies in storage
and how the bit pattern stored is interpreted.
• The types in C can be classified as follows −
M Alqarni INFO-1221
8
Integer Types
•The following table provides the details of standard integer
types with their storage sizes and value ranges −
M Alqarni INFO-1221
9
Example
To get the exact size of a type or a variable on a particular platform, you
can use the sizeof operator. The expressions sizeof(type) yields the
storage size of the object or type in bytes. Given below is an example to
get the size of int type on any machine −
When you compile and execute the above program, it produces the
following result
M Alqarni INFO-1221
10
Parts of the C Language
•Keywords
•Functions
•Operators
•Values and Variables
•Structure
M Alqarni INFO-1221
11
Keywords
Keywords: are the language part of the C language. They accomplish very
basic tasks.
M Alqarni INFO-1221
12
Functions
•The true workhorses on the C language
•Held in C language libraries
•Defined by header files
•Thousands of functions
M Alqarni INFO-1221
13
Operators
Operators are symbols used to manipulate data in the
program. These include the traditional math operators as
well as a host of other special symbols.
•Mathematical: + - / * % ++ --
•Comparison: == != > <
•Assignment: = += -= *= /=
•Logical: && || !
•Bitwise: & | ^ << >>
•Unary + - ~ ! *
M Alqarni INFO-1221
14
Values and Variables
Values Variables
•Characters •Characters
•Integer values •Integer values
•Floating-point values •Floating-point values
•Memory locations •Memory locations
• Values include characters and numeric values.
• A variable, on the other hand, is a container for a value. Its contents can
change. The values that go into variables are the same types of values you use
directly in a program.
M Alqarni INFO-1221
15
Structure
• All these pieces of the language must be used in a specific manner or
order. That's the C language structure.
• The C language uses preprossesor directives to help control program
flow.
• The main() function is the first function executed in all C programs. “It's
required, as you saw earlier example”.
• Curly brackets are used to enclose a functions' contents.
• Statements are like sentences in the C language. They can include C
language keywords, functions, math, logical comparisons.
• comments are notes to yourself or other programmers, reminders,
general information, or other items that are part of the source code but
not compiled
M Alqarni INFO-1221
16
Variables
•There are special “containers” for this purpose and these
containers are called variables. The name suggests that
the contents of a container can be varied in (almost) any
way.
M Alqarni INFO-1221
17
Variables
• Let's start our discussion with the issues related to a variable's name.
Variables do not appear in our program in some magical way. We (as
developers) decide how many and which variables we want to exist in
our program. We also give them their names, almost becoming their
godparents. If you want to give a name to a variable you must follow
some strict rules:
• the name of the variable must be composed of upper-case or lower-case
Latin letters, digits and the character _ (underscore);
• the name of the variable must begin with a letter
• the underline character is a letter (strange but true)
• upper- and lower-case letters are treated as different (a little differently
than in the real world – Alice and ALICE are the same given names but
they are two different variable names, consequently, two different
variables)
M Alqarni INFO-1221
18
Variables
• Note that the same restrictions apply to function names.
• The standard of the “C” language does not impose restrictions on
the length of variable names, but a specific compiler may have a
different opinion on this matter. Don't worry; usually the limitation is
set so high that it’s unlikely that you would actually want to use
such long variable names (or functions).
M Alqarni INFO-1221
19
Variables
Here are some correct, but not always convenient variable names:
• variable
•i
• t10
• Exchange_Rate
• counter
• DaysToTheEndOfTheWorld
• TheNameOfAVariableWhichIsSoLongThatYouWillNotBeAbleToWriteItWithoutMistakes
And now some incorrect names:
• 10t (does not being with a letter)
• Adiós_Señora (contains illegal characters)
• Exchange Rate (contains a space)
M Alqarni INFO-1221
20
Variables
•The type is an attribute that uniquely defines which values
can be stored inside the variable. We already know of
integer (int) and floating point (float) types. The value of a
variable is what we have put into it. Of course, you can
only put in a value that is compatible with the variable's
type. Only an integer value can be assigned to an integer
variable (to say the same thing but in a slightly different
way – to a variable of type int). The compiler will not allow
us to put a floating-point number there.
M Alqarni INFO-1221
21
Variables
How the variables are created and how to put a value inside
them (or rather – how to give them a value)?
M Alqarni INFO-1221
22
Variables
•Let's try to declare a variable of type int named Counter.
The relevant portion of the program looks like this:
int Counter;
•What is declared by the following fragment of a program?
int variable1, account_balance, invoices;
•It declares three variables of type int named
variable1, account_balance and invoices.
M Alqarni INFO-1221
23
Variables = “value”
•And how do we give a value to the newly declared
variable? You need to use the assignment operator.
Although this sounds rather mysterious, the operator has a
simple syntax and an unambiguous interpretation. The
assignment operator looks very familiar – here it is:
=
example
Counter = 1;
The above statement reads: assign a value of 1 to a
variable named Counter or a bit shorter assign 1 to Counter.
Some use a different convention and read it as: Counter
becomes 1.
M Alqarni INFO-1221
24
Variables ; Another example:
•In this case, the new value of the variable Result will be the
result of adding 100 to 200, which is probably not a
surprise to you, right?
M Alqarni INFO-1221
25
Variables; difficult example
Slightly more difficult example:
x = x + 1;
• Seeing that, a mathematician would probably protest – no value
may be equal to itself plus one. This is a contradiction.
But in the “C” language the sign "=" does not mean is equal to,
but assign a value.
Take the current value of the variable x, add 1 to it and store the
result in the variable x
M Alqarni INFO-1221
26
Variables
•For example – you can't do this:
int int;
•You mustn't have a variable named int – it’s prohibited. But
you can do this instead:
int Int;
•The compiler will be glad, very glad.
M Alqarni INFO-1221
27
Variables; Program - example
Output
M Alqarni INFO-1221
28
Variables
•The same concept applies on function declaration where
you provide a function name at the time of its declaration
and its actual definition can be given anywhere else. For
example −
M Alqarni INFO-1221
29
Lvalues and Rvalues in C
• There are two kinds of expressions in C −
• lvalue − Expressions that refer to a memory location are called "lvalue"
expressions. An lvalue may appear as either the left-hand or right-hand side of
an assignment.
• rvalue − The term rvalue refers to a data value that is stored at some address
in memory. An rvalue is an expression that cannot have a value assigned to it
which means an rvalue may appear on the right-hand side but not on the left-
hand side of an assignment.
• Variables are lvalues and so they may appear on the left-hand side of an
assignment. Numeric literals are rvalues and so they may not be assigned and
cannot appear on the left-hand side. Take a look at the following valid and
invalid statements −
M Alqarni INFO-1221
30
Note About C Programs
•In C, lowercase and uppercase characters are very
important!
•All commands in C must be lowercase. The C programs
starting point is identified by the word
main()
•This informs the computer as to where the program
actually starts. The brackets that follow the keyword main
indicate that there are no arguments supplied to this
program ( this will be examined later on).
M Alqarni INFO-1221
31
Statement
•The purpose of the statement include
stdio.h is to allow the use of the printf ()
statement to provide program output. Text to be
displayed by printf() must be enclosed in double
quotes.
• The program has only one statement
printf("Programming in C is easy.\n")
•printf() is actually a function (procedure) in C that
is used for printing variables and text. Where
text appears in double quotes "", it is printed
without modification. There are some exceptions
however.
M Alqarni INFO-1221
32
Constants
• Constants refer to fixed values that the program may not
alter during its execution. These fixed values are also
called literals.
• Constants can be of any of the basic data types like an
integer constant, a floating constant, a character constant,
or a string literal. There are enumeration constants as well.
• Constants are treated just like regular variables except
that their values cannot be modified after their definition.
M Alqarni INFO-1221
33
Character Constants
•Character literals are enclosed in single quotes, e.g., 'x'
can be stored in a simple variable of char type.
•A character literal can be a plain character (e.g., 'x'), an
escape sequence (e.g., '\t'), or a universal character (e.g.,
'\u02C0').
•There are certain characters in C that represent special
meaning when preceded by a backslash for example,
newline (\n) or tab (\t).
•Following is the example to show a few escape sequence
characters
M Alqarni INFO-1221
34
String Literals
•String literals or constants are enclosed in double
Quotes “”.
A string contains characters that are similar to character
literals: plain characters, escape sequences, and universal
characters.
•You can break a long line into multiple lines using string
literals and separating them using white spaces.
•Here are some examples of string literals.
•All the three forms are identical strings.
M Alqarni INFO-1221
35
Defining Constants
•There are two simple ways in C to define constants −
Using #define preprocessor.
Using const keyword.
The #define Preprocessor
•Given below is the form to use #define preprocessor to
define a constant −
M Alqarni INFO-1221
36
Example
M Alqarni INFO-1221
37
The const Keyword
•You can use const prefix to declare constants with a
specific type as follows:
const type variable = value;
•Example
M Alqarni INFO-1221
38
Integer Literals
•An integer literal can be a decimal, octal, or hexadecimal
constant. A prefix specifies the base or radix: 0x or 0X for
hexadecimal, 0 for octal, and nothing for decimal.
•An integer literal can also have a suffix that is a
combination of U and L, for unsigned and long,
respectively. The suffix can be uppercase or lowercase and
can be in any order.
M Alqarni INFO-1221
39
Examples
•Here are some examples of integer literals:
M Alqarni INFO-1221
40
Floating-point Literals
•A floating-point literal has an integer part, a decimal point,
a fractional part, and an exponent part. You can represent
floating point literals either in decimal form or exponential
form.
•While representing decimal form, you must include the
decimal point, the exponent, or both; and while
representing exponential form, you must include the
integer part, the fractional part, or both. The signed
exponent is introduced by e or E.
M Alqarni INFO-1221
41
Examples
M Alqarni INFO-1221
42
Input/Output Operations (I/O)
•Input operation
• an instruction that copies data from an input device into memory
•Output operation
• an instruction that displays information stored in memory to the
output devices (such as the monitor screen)
M Alqarni INFO-1221
43
Input/Output Functions
•A C function that performs an input or output operation
•A few functions that are pre-defined in the header file
stdio.h such as :
• puts()
• gets()
• printf()
• scanf()
• getchar() & putchar()
M Alqarni INFO-1221
44
Example
M Alqarni INFO-1221
45
Use of gets() and puts()
•Input comes from the standard input device, which is
normally the keyboard.
•gets() fetches a character from standard input. puts() sends
a character to standard output. Both of these functions
require the inclusion of the standard I/O header file
stdio.h for their prototypes and such.
M Alqarni INFO-1221
46
example
M Alqarni INFO-1221
47
Formatted I/O using printf() & scaf()
• Now we’re going to set aside conditional statements for a while and
spend some time on two important and extremely useful features we
use to provide connectivity between the computer and the outside
world.
• Sending data in the direction from human (user) to the computer
program is called input. The stream of data transferred in the opposite
direction, i.e. from the computer to the human, is called output.
• To accomplish these, and even more complex, tasks, there’s a very
powerful function in the “C” language named printf (print formatted).
This function can easily output several values of different types and mix
them with the text. We can’t show you all of its capabilities now
because, firstly, there are many, and secondly, we still lack some
theoretical foundations to understand many of them.
M Alqarni INFO-1221
48
Formatted I/O using printf()
• The printf function has several unique features: it doesn’t specify how
many arguments must be provided; the only requirement is that there
must be at least one argument; additionally, only the first argument has
a strict type (it must be a string); all subsequent arguments may be of
any type. It isn’t sorcery. The “C” language enables us to write these
functions ourselves.
• The first, mandatory, argument is called the format. It’s a recipe or a
specification according to which the printf function will proceed with its
subsequent arguments.
• Printf reads the instruction carefully and learns from it which data is to
be printed and how it should be presented to the user. Let's look at it in
a few applications
M Alqarni INFO-1221
49
Formatted I/O using printf() & scaf()
• now the printf function is invoked with two arguments. The first is the
format. The second is a variable of type int. Take a look at the format –
there’s a suspicious character there: %.
• What is this mysterious percent intended for?
M Alqarni INFO-1221
50
Formatted I/O using scaf()
• The function is named scanf (scan formatted) and is a close relative
of the printf function. Where did this relationship come from? You'll see
soon.
Imagine that we want to ask the user about the maximum number of
sheep that we want to count before the developer falls asleep. The user
enters the value from the keyboard and the program stores it in a
specified variable (MaxSheep). An appropriate scanf invocation looks as
follows:
Perhaps you see the similarity to the printf. The first parameter is also
a format that tells the function which data will be given to the program,
and in which form. As before, we give arguments for the format in the
amount equal to the number of the given specifiers. At this point, the
similarities end and the differences begin. First, the argument for the
print may not be a variable. It may be an expression as well.
M Alqarni INFO-1221
51
Formatted I/O using scaf()
• Example
• Here we’d like to print the doubled value of MaxSheep– this is feasible.
Using the scanf specifier, we must explicitly specify the variable that
is able to store the data entered by the user. This, however, is not the
end of the differences.
M Alqarni INFO-1221
52
NOTE for scaf()
• To fetch a string from standard input, or to fetch any specific value, use
the scanf() function.
• Required stdio.h header file
• Reads specific values from standed input
• Assigns the value to a variable
• Uses printf() placeholders
• Uses ‘&’ operator (sometimes)
---------------------------------------------------------------------------
• Scanf()
M Alqarni INFO-1221
53
Examples
• Example 1.1
M Alqarni INFO-1221
54
Examples
• Example 1.2
M Alqarni INFO-1221
55
Examples
• Example 1.3
M Alqarni INFO-1221
56
Examples
• The scanf() function stops reading text at the first white space
character. That's a space. Tab our new line, and there's no way you
can force scanf() to read in those characters.
• It's just the way it works. So scanf() is really a string input
function where strings are just one word long. A better function to use
for reading strings is fgets, which is a file input function
M Alqarni INFO-1221
57
Escape Sequence
M Alqarni INFO-1221
58
Placeholder / Conversion Specifier
No Conversion Output Type Output Example
Specifier
1 %d Signed decimal integer 76
2 %i Signed decimal integer 76
3 %o Unsigned octal integer 134
4 %u Unsigned decimal integer 76
5 %x Unsigned hexadecimal (small letter) 9c
6 %X Unsigned hexadecimal (capital letter) 9C
7 %f Integer including decimal point 76.0000
8 %e Signed floating point (using e notation) 7.6000e+01
9 %E Signed floating point (using E notation) 7.6000E+01
10 %g The shorter between %f and %e 76
11 %G The shorter between %f and %E 76
12 %c Character ‘7’
13 %s String ‘76'
M Alqarni INFO-1221
59
Type conversions
•the “C” language may cause some confusion, especially
when different data types appear together inside one
expression.
•Changing the type of the data (perhaps combined with a
change of its value, which may be caused by a loss of
accuracy) is called a conversion.
•Implicit conversions:
•Explicit conversions:
M Alqarni INFO-1221
60
Type conversions
•The “C” language knows two types of conversions:
•implicit conversions, which work according to language
rules and are not specified in the code in any visible way;
their operation is silent and automatic;
•explicit conversions carried out at the developer's
request; the developer should insert them explicitly inside
the code indicating which value should be converted and
into which resulting type.
M Alqarni INFO-1221
61
Implicit conversions
•Implicit conversions are performed at run-time according to
these strict rules. The rules are applied in the order below
until all the data used in the particular expression has the
same type – this condition is very important!
• data of type char or short int will be converted to type int (this is called
an integer promotion);
• if there is any value of type float in the expression, the other data will
be converted to float;
• if there’s any value of type double in the expression, the other data will
be converted to double;
• if there’s any value of type long int in the expression, the other data will
be converted to long int.
M Alqarni INFO-1221
62
Implicit conversions Ex-
M Alqarni INFO-1221
63
Explicit conversions
•Explicit conversions are introduced into the code using
the typecast operator. This is a unary operator with a high
priority, equal to unary minus priority. You can see it here
→ where type is a name or description of the type which
the value will be converted into.
M Alqarni INFO-1221
64
Explicit conversions Ex-
M Alqarni INFO-1221
65
Type conversions
For example, in the following snippet, the variable x of
type float is explicitly converted into the double type.
M Alqarni INFO-1221
66
example
M Alqarni INFO-1221
67