0% found this document useful (0 votes)
2 views88 pages

Chapter-01(C Programming Fundamentals)

C programming basics slides BSC engineering

Uploaded by

hassan01754
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views88 pages

Chapter-01(C Programming Fundamentals)

C programming basics slides BSC engineering

Uploaded by

hassan01754
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 88

Lec 01

Background

C is a structured programming language language.. It is


considered a high
high--level language because it allows the
programmer to concentrate on the problem at hand
and not worry about the machine that the program will
be using
using.. That is another reason why it is used by
software developers whose applications have to run on
many different hardware platforms
platforms..

Computer Science: A
Structured Programming 1
Approach Using C
C Programs

It's time to write your first C program


program..

Topics discussed in this section:


Structure of a C Program
Your First C Program
Comments
The Greeting Program

Computer Science: A
Structured Programming 2
Approach Using C
FIGURE 2-2 Structure of a C Program
Computer Science: A
Structured Programming 3
Approach Using C
FIGURE 2-3 The Greeting Program
Computer Science: A
Structured Programming 4
Approach Using C
Documentation Section
•The Documentation Section consists of set of comment lines giving the

Name of the program

The author

Other Details which the programmer would like to use later

Syntax

/* Multiple Comment lines *\

// Single Comment line


Example

/* c –program to find gcd and lcm of two numbers using Euclid's Algorithm *\

// Welcome to C
Link Section
•The link section provides instruction to the complier to
link functions from system library

•Syntax
#include<header file name .h>

Header files
stdio– Standard Input /Output
conio– Console input/Output,
math- contains mathematical functions like(cos(),
sin(), sqrt(), abs())

•Example
#include<stdio.h>
#include<conio.h>
Definition Section
•This section is used to define symbolic constants

•Syntax:-

#define symbolic-name constant-value

•Example:-

#define pi 3.142

#define maxmarks 100

#define minmarks 35
Global declaration Section

•In C There are two types of declarations

1.Local variable declaration

2. Global variable Declaration

•Global variables are declared out side the main function

•Local variables are declared inside the main function


Identifiers

One feature present in all computer languages is the


identifier.. Identifiers allow us to name data and other
identifier
objects in the program
program.. Each identified object in the
computer is stored at a unique address
address..

Computer Science: A
Structured Programming 11
Approach Using C
Table 2-1 Rules for Identifiers

Computer Science: A
Structured Programming 12
Approach Using C
Note
An identifier must start with a letter or underscore:
it may not have a space or a hyphen.

Computer Science: A
Structured Programming 13
Approach Using C
Note
C is a case-sensitive language.

Computer Science: A
Structured Programming 14
Approach Using C
Table 2-2 Examples of Valid and Invalid Names

Computer Science: A
Structured Programming 15
Approach Using C
Variable declaration
•Syntax:-

data-type variable-name;

Ex:-
int a,x;
float b,c;
char name;
Data types in C

Fundamental Data Types


Integer types
Floating type
Character type

Derived Data Types


Arrays
Pointers
Structures
Enumeration
Integer data types
Integers are whole numbers that can have both positive and
negative values, but no decimal values.

Example: 0, -5, 10

In C programming, keyword int is used for declaring integer variable.

For example:

int id;
Here, id is a variable of type integer.

You can declare multiple variable at once in C programming.


For example:
int id, age;
The size of int is either 2 bytes(In older PC's) or 4 bytes.
If you consider an integer having size of 4 byte( equal to 32 bits), it
can take 232 distinct states as: -231,-231+1, ...,-2, -1, 0, 1, 2, ...,
231-2, 231-1

Similarly, int of 2 bytes, it can take 216 distinct states from -215 to
215-1. If you try to store larger number than 231-1,
i.e,+2147483647 and smaller number than -231, i.e, -2147483648,
program will not run correctly.
Floating types

Floating type variables can hold real numbers such as: 2.34, -9.382, 5.0
etc.

You can declare a floating point variable in C by using either float


or double keyword.

For example:
float accountBalance; double bookPrice;
Here, both accountBalance and bookPrice are floating type variables.

In C, floating values can be represented in exponential form as well.


For example:
float normalizationFactor = 22.442e2;
Difference between float and double

The size of float (single precision float data type) is 4 bytes. And the
size of double (double precision float data type) is 8 bytes. Floating
point variables has a precision of 6 digits whereas the precision of
double is 14 digits.

Character types

Keyword char is used for declaring character type variables. For


example:
char test = 'h'
Here, test is a character variable. The value of test is 'h'.
The size of character variable is 1 byte.
C Qualifiers

Qualifiers alters the meaning of base data types to yield a new data
type.
Size qualifiers
Size qualifiers alters the size of a basic type. There are two size
qualifiers, long and short. For example:

long double i;

The size of double is 8 bytes. However, when long keyword is used,


that variable becomes 10 bytes.
Sign qualifiers
Integers and floating point variables can hold both negative and
positive values. However, if a variable needs to hold positive value
only, unsigned data types are used.
For example:
// unsigned variables cannot hold negative value

unsigned int positiveInteger;

There is another qualifier signed which can hold both negative and
positive only. However, it is not necessary to define
variable signed since a variable is signed by default.
An integer variable of 4 bytes can hold data from -2 ^31 to 2^31-1.
However, if the variable is defined as unsigned, it can hold data from
0 to 2^32-1.
It is important to note that, sign qualifiers can be applied to int and
char types only.
C Programming

Keywords and Identifiers


Keywords are the reserved words in programming and are part of
the syntax.
Character set

Character set is a set of alphabets, letters and some


special characters that are valid in C language.

Alphabets
Uppercase: A B C ................................... X Y Z
Lowercase: a b c ...................................... x y z

Digits

0123456789
Special Characters
Special Characters in C Programming

, < > . _
, < > . _
( ) ; $ :
( ) ; $ :
% [ ] # ?
' & { } "
%
^ ! * /[ | ] # ?
- \ ~ +

' & { } "

^ ! * / |

- \ ~ +

White space Characters


blank space, new line, horizontal tab, carriage return and form feed
Keywords

Keywords are predefined, reserved words used in programming that


have special meaning.

Keywords are part of the syntax and they cannot be used as an


identifier.

For example:
int money;

Here, int is a keyword that indicates


'money' is a variable of type integer.

C is a case sensitive language, all keywords must be written in


lowercase.
Here is a list of all keywords allowed in ANSI C.

Keywords in C Language

auto double int struct


break else long switch
case enum register typedef
char extern return union
continue for signed void
do if static while
default goto sizeof volatile
const float short unsigned

Along with these keywords, C supports other numerous keywords


depending upon the compiler.
Identifiers

Identifiers are the names you can give to entities such as variables,
functions, structures etc.

Identifier names must be unique. They are created to give unique


name to a C entity to identify it during the execution of a program.

For example:

int money; double accountBalance;

Here, money and accountBalance are identifiers.

Identifier names must be different from keywords.


You cannot use int as an identifier because int is a keyword.
Identifiers

One feature present in all computer languages is the


identifier.. Identifiers allow us to name data and other
identifier
objects in the program
program.. Each identified object in the
computer is stored at a unique address
address..

Computer Science: A
Structured Programming 9
Approach Using C
Here ,you will learn about identifiers and proper way to name
an identifier.

Table 2-1 Rules for Identifiers

Computer Science: A
Structured Programming 10
Approach Using C
Note
An identifier must start with a letter or underscore:
it may not have a space or a hyphen.

Computer Science: A
Structured Programming 11
Approach Using C
Note
C is a case-sensitive language.

Computer Science: A
Structured Programming 12
Approach Using C
Table 2-2 Examples of Valid and Invalid Names

Computer Science: A
Structured Programming 13
Approach Using C
Rules for writing an identifier

A valid identifier can have letters (both uppercase and lowercase letters), digits
and underscore only.

The first letter of an identifier should be either a letter or an underscore.

However, it is discouraged to start an identifier name with an underscore. It is


because identifier that starts with an underscore can conflict with system names.
In such cases, compiler will complain about it. Some system names that start with
underscore are _fileno, _iob, _wfopen etc.

There is no rule on the length of an identifier. However, the first 31 characters of


identifiers are discriminated by the compiler. So, the first 31 letters of two
identifiers in a program should be different.

Good Programming Practice

You can choose any name for an identifier. However, if the programmer choose meaningful name
for an identifier, it will be easy to understand and work on.
Variables
Variable is a name of data to store its value.
In programming, a variable is a container (storage area) to hold data.
Variable declaration

•Syntax:-

data-type variable-name;

Ex:-
int a,x;
float b,c;
char name;
Note
When a variable is defined, it is not initialized.
We must initialize any variable requiring
prescribed data when the function starts.
To indicate the storage area, each variable should be given a unique name
(identifier).
Variable names are just the symbolic representation of a memory location.

Sintax:

Data_type Data_name;

For example:
int playerScore = 95;

Here, playerScore is a variable of integer type. The variable is holding 95 in the


above code.

The value of a variable can be changed, hence the name 'variable'.

In C programming, you have to declare a variable before you can use it.
2.4 Memory Concepts
• Variables
– Variable names correspond to locations in the
computer's memory
– Every variable has a name, a type, a size and a value
– Whenever a new value is placed into a variable
(through scanf, for example), it replaces (and
destroys) the previous value
– Reading variables from memory does not change
them
• A visual representation

integer1 45
5
What is a Variable? symbol table?

A Variable names a place in memory where you Symbol Addr Value


store a Value of a certain Type. 0
1
You first Define a variable by giving it a name 2
and specifying the type, and optionally an 3
initial value declare vs define?
x 4 ?
y 5 ‘e’ (101)
char x; Initial value of x is undefined
char y=‘e’; 6
7
The compiler puts them
Initial value 8
somewhere in memory.
9
Name What names are legal? 10

Type is single character (char) 11

extern? static? const?


12
6
Rules for writing variable name in C

A variable name can have letters (both uppercase and lowercase letters), digits
and underscore only.

The first letter of a variable should be either a letter or an underscore. However, it


is discouraged to start variable name with an underscore. It is because variable
name that starts with an underscore can conflict with system name and may cause
error.

There is no rule on how long a variable can be. However, the first 31 characters of
a variable are discriminated by the compiler. So, the first 31 letters of two variables
in a program should be different.
Constants

Constants are data values that cannot be changed during


the execution of a program
program.. Like variables, constants
have a type
type..

Topics discussed in this section:


Constant Representation
Coding Constants
Constants/Literals

A constant is a value or an identifier whose value cannot be altered in


a program.

For example: 1, 2.5, "C programming is easy" etc.

As mentioned, an identifier also can be defined as a constant.

const double PI = 3.14

Here, PI is a constant. Basically what it means is that, PI and 3.14 is


same for this program.
Integer constants

A integer constant is a numeric constant (associated with number)


without any fractional or exponential part.

There are three types of integer constants in C programming:


decimal constant(base 10)
octal constant(base 8)
hexadecimal constant(base 16)
For example:
Decimal constants: 0, -9, 22 etc
Octal constants: 021, 077, 033 etc
Hexadecimal constants: 0x7f, 0x2a, 0x521 etc

In C programming, octal constant starts with a 0 and hexadecimal


constant starts with a 0x.
Floating-point constants

A floating point constant is a numeric constant that has either a


fractional form or an exponent form.

For example:
-2.0 0.0000234 -0.22E-5
Note: E-5 = 10-5

Character constants
A character constant is a constant which uses single quotation around
characters.

For example: 'a', 'l', 'm', 'F'


Escape Sequences

Sometimes, it is necessary to use characters which cannot be typed


or has special meaning in C programming.

For example: newline(enter), tab, question mark etc. In order to use


these characters, escape sequence is used.

For example: \n is used for newline. The backslash ( \ ) causes


"escape" from the normal way the characters are interpreted by the
compiler.
Escape Sequences

Escape Sequences Character


\b Backspace
\f Form feed
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\' Single quotation mark
\" Double quotation mark
\? Question mark
\0 Null character
String constants

String constants are the constants which are enclosed in a pair of double-quote
marks.
For example:
"good" //string constant
"" //null string constant
" " //string constant of six white space
"x" //string constant having single character.
"Earth is round\n“ //prints string with newline

Enumeration constants

Keyword enum is used to define enumeration types.

For example:

enum color {yellow, green, black, white};

Here, color is a variable and yellow, green, black and white are the enumeration
constants having value 0, 1, 2 and 3 respectively. For more information, visit
page: C Enumeration.
C Programming Input Output (I/O): printf() and scanf()

This focuses on two in-build functions printf() and scanf() to perform


I/O task in C programming. Also, you will learn how you write a valid
program in C.

C programming has several in-build library functions to perform input


and output tasks.

Two commonly used functions for I/O (Input/Output) are printf() and
scanf().

The scanf() function reads formatted input from standard input


(keyboard) whereas the printf() function sends formatted output to
the standard output (screen).
Example #1: C Output

#include <stdio.h> //This is needed to run printf() function.


int main()
{
printf("C Programming"); //displays the content inside quotation return 0;
}

Output

C Programming
How this program works?
All valid C program must contain the main() function.
The code execution begins from the start of main() function.
The printf() is a library function to send formatted output to the
screen.
The printf() function is declared in "stdio.h" header file.

stdio.h is a header file (standard input output header file) and


#include is a preprocessor directive to paste the code from the
header file when necessary.
When the compiler encounters printf() function and doesn't
find stdio.h header file, compiler shows error.

The return 0; statement is the "Exit status" of the program. In simple


terms, program ends.
2.2 A Simple C Program:Printing a Line of Text
1 /* Fig. 2.1: fig02_01.c
2 A first program in C */
3 #include <stdio.h>
4
5 int main()
6 {
7 printf( "Welcome to C!\n" );
8
9 return 0;
10}

Welcome to C!
• Comments
– Text surrounded by /* and */ is ignored by computer
– Used to describe program
• #include <stdio.h>
– Preprocessor directive
• Tells computer to load contents of a certain file
5 – <stdio.h> allows standard input/output operations
Example #2: C Integer Output

#include <stdio.h>
int main()
{
int testInteger = 5;
printf("Number = %d", testInteger);
return 0;
}

Output
Number = 5

Inside the quotation of printf() function, there is a format


string "%d"(for integer). If the format string matches the argument
(testInteger in this case), it is displayed on the screen.
Example #3: C Integer Input/Output
#include <stdio.h>
int main()
{
int testInteger;
printf("Enter an integer: ");
scanf("%d",&testInteger);
printf("Number = %d",testInteger);
return 0;
}

Output
Enter an integer: 4 Number = 4

The scanf() function reads formatted input from the keyboard. When
user enters an integer, it is stored in variable testInteger. Note
the '&'sign before testInteger; &testInteger gets the address
of testInteger and the value is stored in that address.
Example #3: C Floats Input/Output

#include <stdio.h>
int main()
{
float f;
printf("Enter a number: ");
// %f format string is used in case of floats
scanf("%f",&f);
printf("Value = %f", f);
return 0;
}

Output
Enter a number: 23.45 Value = 23.450000

The format string "%f" is used to read and display formatted in case of
floats.
Example #4: C Character I/O

#include <stdio.h>
int main()
{
char var1;
printf("Enter a character: ");
scanf("%c",&var1);
printf("You entered %c.",var1);
return 0;
}

Output
Enter a character: g You entered g.

Format string %c is used in case of character types.


1 /* Fig. 2.5: fig02_05.c
2 Addition program */ Outline
3 #include <stdio.h>
4 1. Initialize variables
5 int main()
6 { 2. Input
7 int integer1, integer2, sum; /*
declaration
8 */ 2.1 Sum
9 printf( "Enter first integer\n" ); /*
prompt
10 */
scanf( "%d", &integer1 ); /* read 3. Print
an integer
11 */ "Enter second integer\n" );
printf( /*
prompt
12 */
scanf( "%d", &integer2 ); /* read
an integer
13 sum = */
integer1 + integer2; /*
assignment
14 of "Sum
printf( sum */
is %d\n", sum ); /*
print sum */
15
16 return 0; /* indicate that program ended
successfully */
17}

Enter first integer Program Output


45
Enter second integer
72
Sum is 117
10
 2000 Prentice Hall, Inc. All rights reserved.
Another Simple C Program: Adding Two Integers

• = (assignment operator)
– Assigns a value to a variable
– Is a binary operator (has two operands)
sum = variable1 + variable2;
sum gets variable1 + variable2;
– Variable receiving value on left
• printf( "Sum is %d\n", sum );
– Similar to scanf
• %d means decimal integer will be printed
• sum specifies what integer will be printed
– Calculations can be performed inside printf
statements
printf( "Sum is %d\n", integer1 +
integer2 );
11
Little bit on ASCII code
When a character is entered in the above program, the character itself is not
stored. Instead a numeric value(ASCII value) is stored. And when we displayed that
value using "%c" text format, the entered character is displayed.

Example #6: C ASCII Code

#include <stdio.h>
int main()
{ int var1 = 69;
printf("Character having ASCII value 69 is %c.",var1);
return 0;
}

Output
Character having ASCII value 69 is E.
Example #5: C ASCII Code
#include <stdio.h>
int main()
{ char var1;
printf("Enter a character: ");
scanf("%c",&var1); // When %c text format is used, character is
displayed in case of character types
printf("You entered %c.\n",var1); // When %d text format is used,
integer is displayed in case of character types
printf("ASCII value of %c is %d.", var1, var1);
return 0;
}

Output
Enter a character: g You entered g. ASCII value of g is 103. The ASCII
value of character 'g' is 103. When, 'g' is entered, 103
Example #7: I/O of Floats and Integers

#include <stdio.h>
int main()
{ int integer = 9876;
float decimal = 987.6543; // Prints the number right justified within 6 columns
printf("4 digit integer right justified to 6 column: %6d\n", integer);
// Tries to print number right justified to 3 digits but the number is not right adjusted
because there are only 4 numbers
printf("4 digit integer right justified to 3 column: %3d\n", integer);
// Rounds to two digit places
printf("Floating point number rounded to 2 digits: %.2f\n",decimal);
// Rounds to 0 digit places
printf("Floating point number rounded to 0 digits: %.f\n",987.6543);
// Prints the number in exponential notation(scientific notation)
printf("Floating point number in exponential form: %e\n",987.6543);
return 0;
}
Output

4 digit integer right justified to 6 column: 9876


4 digit integer right justified to 3 column: 9876
Floating point number rounded to 2 digits: 987.65
Floating point number rounded to 0 digits: 988
Floating point number in exponential form: 9.876543e+02
C Programming Operators

C programming has various operators to perform tasks including


arithmetic, conditional and bitwise operations. You will learn about
various C operators and how to use them in this tutorial.
An operator is a symbol which operates on a value or a variable.

For example: + is an operator to perform addition.

C programming has wide range of operators to perform various


operations. For better understanding of operators, these operators can
be classified as:
Operators in C programming
Arithmetic Operators
Increment and Decrement Operators
Assignment Operators
Relational Operators
Logical Operators
Conditional Operators
Bitwise Operators
Special Operators
C Arithmetic Operators
An arithmetic operator performs mathematical operations such as
addition, subtraction and multiplication on numerical values
(constants and variables).

Operator Meaning of Operator

+ addition or unary plus

- subtraction or unary minus

* multiplication

/ division

% remainder after division( modulo division)


Example #1: Arithmetic Operators
// C Program to demonstrate the working of arithmetic operators #include
<stdio.h>
int main()
{
int a = 9,b = 4, c; Output
c = a+b;
printf("a+b = %d \n",c); a+b = 13
c = a-b; a-b = 5
printf("a-b = %d \n",c); a*b = 36
c = a*b; a/b = 2
printf("a*b = %d \n",c); Remainder when a divided by b=1
c=a/b;
printf("a/b = %d \n",c);
c=a%b;
printf("Remainder when a divided by b = %d \n",c);
return 0;
}
The operators +, - and * computes addition, subtraction and
multiplication respectively as you might have expected.

In normal calculation, 9/4 = 2.25. However, the output is 2 in the


program. It is because both variables a and b are integers. Hence,
the output is also an integer. The compiler neglects the term after
decimal point and shows answer 2 instead of 2.25.

The modulo operator % computes the remainder. When a = 9 is


divided by b = 4, the remainder is 1. The % operator can only be
used with integers.
Suppose a = 5.0, b = 2.0, c = 5 and d = 2.
Then in C programming,

a/b = 2.5 // Because both operands are floating-point variables


a/d = 2.5 // Because one operand is floating-point variable
c/b = 2.5 // Because one operand is floating-point variable
c/d = 2 // Because both operands are integers

Increment and decrement operators

C programming has two operators increment ++ and decrement -- to


change the value of an operand (constant or variable) by 1.
Increment ++ increases the value by 1 whereas decrement --
decreases the value by 1.
These two operators are unary operators, meaning they only
operate on a single operand.
Example #2: Increment and Decrement Operators

// C Program to demonstrate the working of increment and decrement operators


#include <stdio.h>
int main()
Output
{
int a = 10, b = 100; ++a = 11
float c = 10.5, - -b = 99
d = 100.5; ++c = 11.500000
printf("++a = %d \n", ++a); ++d = 99.500000
printf("--b = %d \n", --b);
printf("++c = %f \n", ++c);
printf("--d = %f \n", --d);
return 0; Here, the operators ++ and -- are used
as prefix. These two operators can also
} be used as postfix like a++ and a--.
C Assignment Operators

An assignment operator is used for assigning a value to a variable.


The most common assignment operator is =

Operator Example Same as

= a=b a=b

+= a += b a = a+b

-= a -= b a = a-b

*= a *= b a = a*b

/= a /= b a = a/b

%= a %= b a = a%b
Example #3: Assignment Operators
// C Program to demonstrate the working of assignment operators
#include <stdio.h>
int main()
{
int a = 5, c; Output
c = a;
printf("c = %d \n", c);
c=5
c += a; // c = c+a
printf("c = %d \n", c); c = 10
c -= a; // c = c-a c=5
printf("c = %d \n", c); c = 25
c *= a; // c = c*a c=5
printf("c = %d \n", c);
c=0
c /= a; // c = c/a
printf("c = %d \n", c);
c %= a; // c = c%a
printf("c = %d \n", c);
return 0;
}
C Relational Operators

A relational operator checks the relationship between two


operands. If the relation is true, it returns 1; if the relation is
false, it returns value 0.
Relational operators are used in decision making and loops.
Meaning of Operator Example
Operator

== Equal to 5 == 3 returns 0

> Greater than 5 > 3 returns 1

< Less than 5 < 3 returns 0

!= Not equal to 5 != 3 returns 1

>= Greater than or equal to 5 >= 3 returns 1

<= Less than or equal to 5 <= 3 return 0


Decision Making: Equality and
Relational Operators
Standard algebraic C equality or Example of C Meaning of C
equality operator or relational condition condition
relational operator operator
Equality Operators
= == x == y x is equal to y
not = != x != y x is not equal to y
Relational Operators
> > 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

12
// C Program to demonstrate the working of arithmetic operators
#include <stdio.h>
int main() Output
{
int a = 5, b = 5, c = 10; 5 == 5 = 1
printf("%d == %d = %d \n", a, b, a == b); // true 5 == 10 = 0
printf("%d == %d = %d \n", a, c, a == c); // false 5>5=0
printf("%d > %d = %d \n", a, b, a > b); //false 5 > 10 = 0
printf("%d > %d = %d \n", a, c, a > c); //false 5<5=0
printf("%d < %d = %d \n", a, b, a < b); //false 5 < 10 = 1
printf("%d < %d = %d \n", a, c, a < c); //true 5 != 5 = 0
printf("%d != %d = %d \n", a, b, a != b); //false 5 != 10 = 1
printf("%d != %d = %d \n", a, c, a != c); //true 5 >= 5 = 1
printf("%d >= %d = %d \n", a, b, a >= b); //true 5 >= 10 = 0
printf("%d >= %d = %d \n", a, c, a >= c); //false 5 <= 5 = 1
printf("%d <= %d = %d \n", a, b, a <= b); //true 5 <= 10 = 1
printf("%d <= %d = %d \n", a, c, a <= c); //true
return 0;
}
Oper
Meaning of Operator Example
ator
Logial AND. True only if all If c = 5 and d = 2 then, expression ((c == 5)
&&
operands are true && (d > 5))equals to 0.
Logical OR. True only if either If c = 5 and d = 2 then, expression ((c == 5)
||
one operand is true || (d > 5))equals to 1.
Logical NOT. True only if the If c = 5 then, expression ! (c == 5) equals to
!
operand is 0 0.
Arithmetic
• Arithmetic calculations
– Use * for multiplication and / for division
– Integer division truncates remainder
• 7 / 5 evaluates to 1
– Modulus operator(%) returns the remainder
• 7 % 5 evaluates to 2
• Operator precedence
– Some arithmetic operators act before others (i.e.,
multiplication before addition)
• Use parenthesis when needed
– Example: Find the average of three variables a, b and c
• Do not use: a + b + c / 3
• Use: (a + b + c ) / 3

15
Arithmetic
• Arithmetic operators:
C o p era tio n Arithm etic Alg eb ra ic C exp ressio n
o p era to r exp ressio n
Addition + f+7 f + 7
Subtraction - p–c p - c
Multiplication * bm b * m
Division / x/y x / y
Modulus % r mod s r % s

• Rules Operation(s)
Operator(s)of operator precedence:
Order of evaluation (precedence)
() Parentheses Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs of parentheses “on the same level” (i.e.,
not nested), they are evaluated left to right.
*, /, or % Multiplication,Divi Evaluated second. If there are several, they are
sion, Modulus evaluated left to right.
+ or - Addition Evaluated last. If there are several, they are
Subtraction evaluated left to right.
16
Expressions and Evaluation
Expressions combine Values using Operators, according to precedence.

1 + 2 * 2  1 + 4  5
(1 + 2) * 2  3 * 2  6

Symbols are evaluated to their Values before being combined.


int x=1;
int y=2;
x + y * y  x + 2 * 2  x + 4  1 + 4  5

Comparison operators are used to compare values.


In C, 0 means “false”, and any other value means “true”.
int x=4;
(x < 5)  (4 < 5)  <true>
(x < 4)  (4 < 4)  0
((x < 5) || (x < 4))  (<true> || (x < 4))  <true>

Not evaluated because


17 first clause was true
Comparison and Mathematical
Operators
The rules of precedence are clearly
== equal to
< less than defined but often difficult to remember or
<= less than or equal
> greater than non-intuitive. When in doubt, add
>= greater than or equal parentheses to make it explicit. For oft-
!=
&&
not equal
logical and
confused cases, the compiler will give you
|| logical or a warning “Suggest parens around …” – do
! logical not it!
+ plus & bitwise and
- minus | bitwise or Beware division:
* mult ^ bitwise xor • If second argument is integer, the
/ divide ~ bitwise not
% modulo << shift left result will be integer (rounded):
>> shift right 5 / 10  0 whereas 5 / 10.0  0.5
• Division by 0 will cause a FPE

Don’t confuse & and &&..


1 & 2  0 whereas 1 && 2  <true>
18
Assignment Operators
x = y assign y to x x += y assign (x+y) to x
x++ post-increment x x -= y assign (x-y) to x
++x pre-increment x x *= y assign (x*y) to x
x-- post-decrement x x /= y assign (x/y) to x
--x pre-decrement x x %= y assign (x%y) to x

Note the difference between ++x and x++:

int x=5; int x=5;


int y; int y;
y = ++x; y = x++;
/* x == 6, y == 6 */ /* x == 6, y == 5 */

Don’t confuse = and ==! The compiler will warn “suggest parens”.

int x=5; int x=5;


if (x==6) /* false */ if (x=6) /* always true */
{ {
/* ... */ /* x is now 6 */
recommendation
} }
/* x is still 5 */ /* ... */

19

You might also like