Introduction to C
Programming
By Mohamed Gamal
© Mohamed Gamal 2024
The topics of today’s lecture:
Agenda
Basic Data Types in C
Data Type No. bytes Range
int 4 bytes –231 to (231 – 1)
short 2 bytes –215 to (215 – 1)
long 4 or 8 bytes –263 to (263 – 1)
float 4 bytes A floating-point number (7 precision digits)
double 8 bytes
A floating-point number with more precision
(15 precision digits)
long double 10 bytes
A floating-point number with more precision
(15 precision digits)
char 1 byte
-27 to 27-1
(ASCII)
All
of
these
types
are
signed
Unsigned Data Types
Data Type No. bytes Range
unsigned int 4 bytes 0 to (232 – 1)
unsigned short 2 bytes 0 to (216 – 1)
unsigned long 4 or 8 bytes 0 to (264 – 1)
unsigned char 1 byte
0 to 28-1
(ASCII)
Signed and Unsigned Example
#include <stdio.h>
int main() {
int signedVar = 1500000000; // signed
unsigned int unsignVar = 1500000000; // unsigned
signedVar = (signedVar * 2) / 3; // calculation exceeds range
unsignVar = (unsignVar * 2) / 3; // calculation within range
printf("signedVar = %in", signedVar); // wrong
printf("unsignVar = %i", unsignVar); // OK
return 0;
}
Order of Data Types (Automatic Conversions)
Data Type Order
long double Highest
double
↓
float
long
int
short
char Lowest
– When two operands of different
types are encountered in the
same expression, the lower-
type variable is converted to the
type of the higher-type variable.
Example – Automatic Conversions
#include <stdio.h>
int main() {
int count = 7;
float avgWeight = 155.5;
double totalWeight = count * avgWeight;
printf("totalWeight = %lf", totalWeight);
return 0;
}
– The int value of count is converted to type float and stored in a temporary variable before being multiplied by
the float variable avgWeight. The result (still of type float) is then converted to double
Example
(Cont.)
Type Casting
#include <stdio.h>
int main() {
int intVar = 1500000000; //1,500,000,000
intVar = (intVar * 10) / 10; //result too large
printf("intVar = %in", intVar); //wrong answer
intVar = 1500000000; //reset to 1,500,000,000
intVar = (static_cast<double>(intVar) * 10) / 10; //cast to double
printf("intVar = %i", intVar); //right answer
return 0;
}
– Suppose an intermediate result won’t fit the unsigned type either.
– In such a case we might be able to solve the problem by using a type cast.
printf() and scanf()
o Built-in library functions, defined in stdio.h (header file).
o The printf() function is used for output. It prints the given statement to the
console.
The format string can be %d (integer), %c (character), %s (string), %f (float)
o The scanf() function is used for input. It reads the input data from the console.
scanf("format string", arguments);
printf("format string", arguments);
printf("%d %c %f %s", 2, 'A', 3.14, "eight");
scanf("%d %d", num1, num2);
Constants in C
– A constant is a value or variable that cannot be changed in the program.
Constant Example
Decimal Constant 10, 20, 450, ..., etc.
Real or Floating-point Constant 10.3, 20.2, 450.6, ..., etc.
Character Constant 'a', 'b', 'x', …, etc.
String Constant "c", "c program", …, etc.
Constants in C
– A constant is just an immediate, absolute value found in an expression.
– A constant that contains a decimal point or the letter e (or both) is a
floating-point constant.
3.14, 10., .01, 123e4, 123.456e7
– Floating-point constants are of type double by default.
– A character constant is simply a single character between single quotes.
'A', ' . ', '%'
Constants in C (Cont.)
– A string is represented in C as a sequence or array of characters.
– A string constant is a sequence of zero or more characters enclosed in
double quotes.
"apple", "hello world", "this is a string"
– Within character and string constants, the backslash character  is
special, and is used to represent characters not easily typed on the
keyboard or for various reasons not easily typed in constants.
Constants in C (Cont.)
#define CONSTANT_NAME constant_value
const DATA_TYPE CONSTANT_NAME = constant_value;
Examples:
#define PI 3.14156
#define MYNAME "Mohamed Gamal"
#define LIMIT 10
const int x = 5;
Escape Sequence
Escape Sequence Meaning
a Alarm or Beep
b Backspace
f Form Feed
n New Line
r Carriage Return
t Tab (Horizontal)
v Vertical Tab
 Backslash
' Single Quote
" Double Quote
? Question Mark
Comments
#include <stdio.h>
int main() {
// Single Line Comment
/*
Multi-Line
Comment
*/
return 0;
}
• Single Line Comments
• Multi-Line Comments
– Comments in C language are used to provide information about lines of code.
Declarations
– Think of a variable as writing the value on a paper and placing it in a box.
– A declaration tells the compiler the name and type of a variable you’ll be
using in your program.
char c;
int i;
float f;
int i = 1;
int i1, i2;
int i1 = 10, i2 = 20;
– You can give your variables any names you want, the formal term of
these names is “identifiers”.
Declarations
– The rules for forming a variable name also apply to function names.
• The first character must be a letter, either lowercase or uppercase or
underscore;.
• The capitalization of names in C is significant (case-sensitive).
• Defined constants are traditionally made up of all uppercase characters.
• The variable must be unique in the first eight characters in order to be safe
across compilers and names should be descriptive;
• Do not make a variable name the same as a reserved word (the words such
as int and for which are part of the syntax of the language).
Operators in C
– Both C and C++ have many operators defined.
– The operators fall into several categories:
arithmetic relational
(Comparison)
bitwise
assignment logical miscellaneous
1) Arithmetic Operators
– The basic operators for performing arithmetic operations are the same in
many computer languages
1) Arithmetic Operators (Cont.)
– The – operator can be used in two ways: to subtract two numbers (Binary)
(as in a - b), or to negate one number (Unary) (as in -a + b or a + -b).
– The division operator / when applied to integers, it discards any remainder
1 / 2 → 0
5 / 2 → 2
– But when the operand is a floating-point quantity (i.e., float or double), the
division operator yields a floating-point result,
1 / 2.0 → 0.5
5.0 / 2.0 → 2.5
1) Arithmetic Operators (Cont.)
– The modulus operator % gives you the remainder when two integers are
divided (The modulus operator can only be applied to integers)
1 % 2 → 1
5 % 2 → 1
– An additional arithmetic operation you might be wondering about is
exponentiation.
– Some languages have an exponentiation operator (typically ^ or **), but C
doesn’t.
– To square or cube a number, just multiply it by itself.
Example
#include <stdio.h>
int main() {
printf("6 %% 8 = %in", 6 % 8); // 6
printf("7 %% 8 = %in", 7 % 8); // 7
printf("8 %% 8 = %in", 8 % 8); // 0
printf("9 %% 8 = %in", 9 % 8); // 1
printf("10 %% 8 = %i", 10 % 8); // 2
printf("5.3 %% 1.7 = %f", 5.3 % 1.7); // Error!
integers only
return 0;
}
1) Arithmetic Operators (Cont.)
– For binary operators, multiplication, division, and modulus, all have higher
precedence than addition and subtraction.
1 + 2 * 3 →
1 – 2 – 3 →
1) Arithmetic Operators (Cont.)
– For binary operators, multiplication, division, and modulus, all have higher
precedence than addition and subtraction.
1 + 2 * 3 → 7, not 9
1 + 2 * 3 is equivalent to 1 + (2 * 3)
1 – 2 – 3 → –4
from left to right
1) Arithmetic Operators (Cont.)
– Whenever the default precedence doesn't give you the grouping you want,
you can always use explicit parentheses.
(1 + 2) * 3 → 9
Higher Precedence
SQRT( ) – cmath library
#include <stdio.h> //for printf, scanf, etc.
#include <cmath> //for sqrt()
int main()
{
double number, answer; //sqrt() requires type double
printf("Enter a number : ");
scanf("%lf", &number); //get the number
answer = sqrt(number); //find square root
printf("Square root is %lf", answer); //display it
return 0;
}
2) Assignment Operators
– The assignment operator ‘ = ’ assigns a value to a variable.
– The assignment operator works from right to left.
b = 1
a = b
c = a = b is equivalent to c = (a = b)
2) Assignment Operators (Cont.)
– The standard programming for increasing a variable's value by a specific
quantity:
i = i + 10
i = i + 170
– The standard programming idiom for increasing a variable's value by 1:
i = i + 1
i += 1
2) Assignment Operators (Cont.)
– There's no particular difference between
int a = 10;
and
int a;
/* later... */
a = 10;
3) Relational Operators
– Types of Relational Operators in C
▪ Equal to ( == )
▪ Not equal to ( != )
▪ Less than ( < )
▪ Greater than ( > )
▪ Less than or equal to ( <= )
▪ Greater than or equal to (>=)
Evaluated from
left to right
3) Relational Operators – Equal to (==)
– The function of the ‘equal to’ operator ( == ) is to check if two of the
available operands are equal to each other or not.
– If it is so, then it returns to be true, or else it returns false.
– Examples:
3 == 3 will return true
2 == 3 will return false
3) Relational Operators – Not Equal (!=)
– The function of the ‘not equal’ operator ( != ) is to check if two of the
available operands are not equal to each other.
– If they’re, then it returns true, otherwise false.
– Examples:
2 != 3 will return true
3 != 3 will return false
3) Relational Operators – Less Than (<)
– The function of the ‘less than’ operator ( < ) is to check if the first
available operand is less than the second one.
– If so, then it returns true, otherwise false.
– Examples:
3 < 3 will return false
2 < 3 will return true
3) Relational Operators – Less or Equal (<=)
– The function of the ‘less than or equal’ operator ( <= ) is to check if the
first available operand is less than or equal to the second one.
– If so, then it returns true, otherwise false.
– Examples:
3 <= 3 will return true
2 <= 3 will return true
8 < 5 < 2 will return false
(8 < 5) → False or 0
0 < 2 → True
3) Relational Operators – Greater Than (>)
– The function of the ‘greater than’ operator ( > ) is to check if the first
available operand is greater than the second one.
– If so, then it returns true, otherwise false.
– Examples:
4 > 3 will return true
2 > 3 will return false
8 > 5 > 2 will return false (8 > 5) → True or 1
1 > 2 → False
3) Relational Operators – Greater or Equal (>=)
– The function of the ‘greater than or equal’ operator ( >= ) is to check if
the first available operand is greater than or equal to the second one.
– If so, then it returns true, otherwise false.
– Examples:
4 >= 3 will return true
2 >= 3 will return false
3) Relational Operators – Summary
4) Logical Operators
– We have three major logical operators in the C language:
Important: Short-Circuiting in Logical Operators in C.
Logical NOT (!)
Logical OR ( || )
Logical AND ( && )
Name AND OR NOT XOR
Algebraic
Expression
𝐴𝐵 𝐴 + 𝐵 ҧ
𝐴 𝐴 ⊕ 𝐵
Symbol
Truth
Table
A
B
C
A
B
C A C
A C
0 1
1 0
A B C
0 0 0
0 1 0
1 0 0
1 1 1
A B C
0 0 0
0 1 1
1 0 1
1 1 1
Logic Gates
A B C
0 0 0
0 1 1
1 0 1
1 1 0
A
B
C
4) Bitwise Operators
– Types of bitwise operators found in C programming language
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise complement
<< Shift left
>> Shift right
4) Bitwise Operators - AND
Example:
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bitwise AND operation of 12 and 25
00001100
& 00011001
________
00001000 = 8 (In decimal)
4) Bitwise Operators - OR
Example:
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bitwise OR operation of 12 and 25
00001100
| 00011001
________
00011101 = 29 (In decimal)
4) Bitwise Operators - XOR
Example:
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bitwise XOR operation of 12 and 25
00001100
^ 00011001
________
00010101 = 21 (In decimal)
4) Bitwise Operators – Complement (Not)
Example:
35 = 00100011 (In Binary)
Bitwise complement operation of 35
~ 00100011
________
11011100 = 220 (In decimal)
– Also called as one’s complement operator.
Note: Takes 4-bit blocks.
4) Bitwise Operators – Right shift
4) Bitwise Operators – Right shift
Example:
212 = 11010100 (In binary)
212 >> 2 = 00110101 (In binary) [Right shift by two bits]
212 >> 7 = 00000001 (In binary)
212 >> 8 = 00000000
212 >> 0 = 11010100 (No Shift)
– Right shift operator shifts all bits towards right by certain number of
specified bits.
4) Bitwise Operators – Left shift
4) Bitwise Operators – Left shift
Example:
212 = 11010100 (In binary)
212 << 1 = 110101000 (In binary) [Left shift by one bit]
212 << 0 = 11010100
212 << 4 = 110101000000 (In binary) = 3392 (In decimal)
– Left shift operator shifts all bits towards left by certain number of
specified bits.
5) Miscellaneous Operators
– Besides the operators discussed above, there are a few other
important operators
Operator Description Example
sizeof() Returns the size of a variable. sizeof(a), where a is integer, will return 4.
& Returns the address of a variable. &a; returns the actual address of the variable.
∗ Pointer to a variable. *a;
? : Conditional Expression. If Condition is true ? then value X : otherwise value Y
Operators Precedence
Category Operator Associativity
Postfix () [] -> . ++ -- Left to right
Unary + - ! ~ ++ -+ (type)* & sizeof Right to left
Multiplicative * / % Left to right
Additive + - Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND &+ Left to right
Logical OR |+ Left to right
Conditional ?: Right to left
Assignment = += -= *= /= % = > >= < <= & = ^= |
= Right to left
Comma , Left to right
Expression
Statement 1
Statement 2
Statement n
⋮
Statement 1
Statement 2
Statement n
⋮
True False
Flowchart of if-else decision making statements
Syntax
if (expression) {
statement;
}
if (expression) {
statement;
} else {
statement;
}
int x = 7;
if (x == 5) {
printf("Yes");
}
int x = 7;
if (x == 5) {
printf("Yes");
} else {
printf("No");
}
if else-if ladder
if (expression) {
statement;
} else if {
statement;
} else {
statement;
}
int x = 5;
if (x == 5) {
printf("x = 5");
} else if (x > 5) {
printf("x > 5");
} else {
printf("x < 5");
}
Nearest if
#include <stdio.h>
int main() {
int a, b, c;
printf("Enter three numbers, a, b, and c: ");
scanf("%i %i %i", &a, &b, &c);
if (a == b)
if (b == c)
printf("a, b, and c are the samen");
else
printf("a, b, and c are differentn");
return 0;
}
Correct indentation
#include <stdio.h>
int main() {
int a, b, c;
printf("Enter three numbers, a, b, and c: ");
scanf("%i %i %i", &a, &b, &c);
if (a == b)
if (b == c)
printf("a, b, and c are the samen");
else
printf("a, b, and c are differentn");
return 0;
}
Correct Program
#include <stdio.h>
int main() {
int a, b, c;
printf("Enter three numbers, a, b, and c: ");
scanf("%i %i %i", &a, &b, &c);
if (a == b) {
if (b == c)
printf("a, b, and c are the samen");
}
else
printf("a, b, and c are differentn");
return 0;
}
Conditional if-else ( ? : )
#include <stdio.h>
int main() {
int num1 = 10, num2;
num2 = num1 == 10 ? num1 : 20;
printf("num1 = %i, num2 = %i", num1, num2);
return 0;
}
Another possibility – with only one statement
int x = 2;
if (x == 5)
printf("x = 5");
else if (x > 5)
printf("x > 5");
else
printf("x < 5");
Another possibility – with only one statement
int x = 7;
if (x == 5)
printf("x = 5");
else if (x > 5 && x < 10)
printf("5 < x < 10");
else
printf("x < 5 or x > 10");
What will be the output?
int a = 2;
if (a = 0)
printf("a = 5");
int a = 2;
if (0 = a)
printf("a = 5");
Example 1:
Example 2:
int a = 2;
if (1 < a < 10)
printf("True");
Example 3:
int a = 2;
if (a)
printf("a is non-zero");
Example 4: Although C generates a 1 to indicate true, it
assumes that any value other than 0
(such as –7 or 44) is true; only 0 is false.
Switch Statement
switch (expression) {
case value1:
// code to be executed;
break; // optional
case value2:
// code to be executed;
break; // optional
...
default:
// code to be executed if all cases are not matched
}
Rules for Switch Statement
1. The switch expression must be of an integer or
character type.
2. The case value must be an integer or character
constant.
3. The case value can be used only inside the switch
statement.
4. The break statement in switch case is optional. (Switch
statements is fall through)
C Switch statement is fall-through
In C language, the switch statement is fall through; it means if
you don't use a break statement in the switch case, all the cases
after the matching case will be executed.
Switch Statement (Cont.)
int x, y;
char a, b;
float f;
Switch Valid / Invalid
switch (x) ✓
switch (x + 2.5) ✘
switch (a + b - 2) ✓
switch (f) ✘
switch (x > y) ✓
// Determine Valid and Invalid Variables
Case Valid / Invalid
case 3; ✓
case 'a'; ✓
case x + 2; ✘
case 'x' > 'y'; ✓
case 2.5; ✘
case 1, 2, 3; ✘
Switch Statement – Example
#include <stdio.h>
int main() {
char grade = ’A’;
switch (grade) {
case ’A’:
printf(”Excellent!");
break; // optional
case ’B’:
printf(”Good!");
break; // optional
default:
printf(”Failed!");
}
return 0;
}
Switch Statement – Example
#include <stdio.h>
int main() {
char grade = ’A’;
switch (grade) {
case ’A’:
case ’B’:
case ’C’:
printf(”Good!");
break; // optional
default:
printf(”Failed!");
}
return 0;
}
// You can combine multiple cases
Vending Machine
End of lecture 2
ThankYou!

Introduction to C Programming -Lecture 2

  • 1.
    Introduction to C Programming ByMohamed Gamal © Mohamed Gamal 2024
  • 2.
    The topics oftoday’s lecture: Agenda
  • 4.
    Basic Data Typesin C Data Type No. bytes Range int 4 bytes –231 to (231 – 1) short 2 bytes –215 to (215 – 1) long 4 or 8 bytes –263 to (263 – 1) float 4 bytes A floating-point number (7 precision digits) double 8 bytes A floating-point number with more precision (15 precision digits) long double 10 bytes A floating-point number with more precision (15 precision digits) char 1 byte -27 to 27-1 (ASCII) All of these types are signed
  • 5.
    Unsigned Data Types DataType No. bytes Range unsigned int 4 bytes 0 to (232 – 1) unsigned short 2 bytes 0 to (216 – 1) unsigned long 4 or 8 bytes 0 to (264 – 1) unsigned char 1 byte 0 to 28-1 (ASCII)
  • 6.
    Signed and UnsignedExample #include <stdio.h> int main() { int signedVar = 1500000000; // signed unsigned int unsignVar = 1500000000; // unsigned signedVar = (signedVar * 2) / 3; // calculation exceeds range unsignVar = (unsignVar * 2) / 3; // calculation within range printf("signedVar = %in", signedVar); // wrong printf("unsignVar = %i", unsignVar); // OK return 0; }
  • 7.
    Order of DataTypes (Automatic Conversions) Data Type Order long double Highest double ↓ float long int short char Lowest – When two operands of different types are encountered in the same expression, the lower- type variable is converted to the type of the higher-type variable.
  • 8.
    Example – AutomaticConversions #include <stdio.h> int main() { int count = 7; float avgWeight = 155.5; double totalWeight = count * avgWeight; printf("totalWeight = %lf", totalWeight); return 0; } – The int value of count is converted to type float and stored in a temporary variable before being multiplied by the float variable avgWeight. The result (still of type float) is then converted to double
  • 9.
  • 10.
    Type Casting #include <stdio.h> intmain() { int intVar = 1500000000; //1,500,000,000 intVar = (intVar * 10) / 10; //result too large printf("intVar = %in", intVar); //wrong answer intVar = 1500000000; //reset to 1,500,000,000 intVar = (static_cast<double>(intVar) * 10) / 10; //cast to double printf("intVar = %i", intVar); //right answer return 0; } – Suppose an intermediate result won’t fit the unsigned type either. – In such a case we might be able to solve the problem by using a type cast.
  • 11.
    printf() and scanf() oBuilt-in library functions, defined in stdio.h (header file). o The printf() function is used for output. It prints the given statement to the console. The format string can be %d (integer), %c (character), %s (string), %f (float) o The scanf() function is used for input. It reads the input data from the console. scanf("format string", arguments); printf("format string", arguments); printf("%d %c %f %s", 2, 'A', 3.14, "eight"); scanf("%d %d", num1, num2);
  • 13.
    Constants in C –A constant is a value or variable that cannot be changed in the program. Constant Example Decimal Constant 10, 20, 450, ..., etc. Real or Floating-point Constant 10.3, 20.2, 450.6, ..., etc. Character Constant 'a', 'b', 'x', …, etc. String Constant "c", "c program", …, etc.
  • 14.
    Constants in C –A constant is just an immediate, absolute value found in an expression. – A constant that contains a decimal point or the letter e (or both) is a floating-point constant. 3.14, 10., .01, 123e4, 123.456e7 – Floating-point constants are of type double by default. – A character constant is simply a single character between single quotes. 'A', ' . ', '%'
  • 15.
    Constants in C(Cont.) – A string is represented in C as a sequence or array of characters. – A string constant is a sequence of zero or more characters enclosed in double quotes. "apple", "hello world", "this is a string" – Within character and string constants, the backslash character is special, and is used to represent characters not easily typed on the keyboard or for various reasons not easily typed in constants.
  • 16.
    Constants in C(Cont.) #define CONSTANT_NAME constant_value const DATA_TYPE CONSTANT_NAME = constant_value; Examples: #define PI 3.14156 #define MYNAME "Mohamed Gamal" #define LIMIT 10 const int x = 5;
  • 17.
    Escape Sequence Escape SequenceMeaning a Alarm or Beep b Backspace f Form Feed n New Line r Carriage Return t Tab (Horizontal) v Vertical Tab Backslash ' Single Quote " Double Quote ? Question Mark
  • 18.
    Comments #include <stdio.h> int main(){ // Single Line Comment /* Multi-Line Comment */ return 0; } • Single Line Comments • Multi-Line Comments – Comments in C language are used to provide information about lines of code.
  • 20.
    Declarations – Think ofa variable as writing the value on a paper and placing it in a box. – A declaration tells the compiler the name and type of a variable you’ll be using in your program. char c; int i; float f; int i = 1; int i1, i2; int i1 = 10, i2 = 20; – You can give your variables any names you want, the formal term of these names is “identifiers”.
  • 21.
    Declarations – The rulesfor forming a variable name also apply to function names. • The first character must be a letter, either lowercase or uppercase or underscore;. • The capitalization of names in C is significant (case-sensitive). • Defined constants are traditionally made up of all uppercase characters. • The variable must be unique in the first eight characters in order to be safe across compilers and names should be descriptive; • Do not make a variable name the same as a reserved word (the words such as int and for which are part of the syntax of the language).
  • 23.
    Operators in C –Both C and C++ have many operators defined. – The operators fall into several categories: arithmetic relational (Comparison) bitwise assignment logical miscellaneous
  • 24.
    1) Arithmetic Operators –The basic operators for performing arithmetic operations are the same in many computer languages
  • 25.
    1) Arithmetic Operators(Cont.) – The – operator can be used in two ways: to subtract two numbers (Binary) (as in a - b), or to negate one number (Unary) (as in -a + b or a + -b). – The division operator / when applied to integers, it discards any remainder 1 / 2 → 0 5 / 2 → 2 – But when the operand is a floating-point quantity (i.e., float or double), the division operator yields a floating-point result, 1 / 2.0 → 0.5 5.0 / 2.0 → 2.5
  • 26.
    1) Arithmetic Operators(Cont.) – The modulus operator % gives you the remainder when two integers are divided (The modulus operator can only be applied to integers) 1 % 2 → 1 5 % 2 → 1 – An additional arithmetic operation you might be wondering about is exponentiation. – Some languages have an exponentiation operator (typically ^ or **), but C doesn’t. – To square or cube a number, just multiply it by itself.
  • 27.
    Example #include <stdio.h> int main(){ printf("6 %% 8 = %in", 6 % 8); // 6 printf("7 %% 8 = %in", 7 % 8); // 7 printf("8 %% 8 = %in", 8 % 8); // 0 printf("9 %% 8 = %in", 9 % 8); // 1 printf("10 %% 8 = %i", 10 % 8); // 2 printf("5.3 %% 1.7 = %f", 5.3 % 1.7); // Error! integers only return 0; }
  • 28.
    1) Arithmetic Operators(Cont.) – For binary operators, multiplication, division, and modulus, all have higher precedence than addition and subtraction. 1 + 2 * 3 → 1 – 2 – 3 →
  • 29.
    1) Arithmetic Operators(Cont.) – For binary operators, multiplication, division, and modulus, all have higher precedence than addition and subtraction. 1 + 2 * 3 → 7, not 9 1 + 2 * 3 is equivalent to 1 + (2 * 3) 1 – 2 – 3 → –4 from left to right
  • 30.
    1) Arithmetic Operators(Cont.) – Whenever the default precedence doesn't give you the grouping you want, you can always use explicit parentheses. (1 + 2) * 3 → 9 Higher Precedence
  • 31.
    SQRT( ) –cmath library #include <stdio.h> //for printf, scanf, etc. #include <cmath> //for sqrt() int main() { double number, answer; //sqrt() requires type double printf("Enter a number : "); scanf("%lf", &number); //get the number answer = sqrt(number); //find square root printf("Square root is %lf", answer); //display it return 0; }
  • 32.
    2) Assignment Operators –The assignment operator ‘ = ’ assigns a value to a variable. – The assignment operator works from right to left. b = 1 a = b c = a = b is equivalent to c = (a = b)
  • 33.
    2) Assignment Operators(Cont.) – The standard programming for increasing a variable's value by a specific quantity: i = i + 10 i = i + 170 – The standard programming idiom for increasing a variable's value by 1: i = i + 1 i += 1
  • 34.
    2) Assignment Operators(Cont.) – There's no particular difference between int a = 10; and int a; /* later... */ a = 10;
  • 35.
    3) Relational Operators –Types of Relational Operators in C ▪ Equal to ( == ) ▪ Not equal to ( != ) ▪ Less than ( < ) ▪ Greater than ( > ) ▪ Less than or equal to ( <= ) ▪ Greater than or equal to (>=) Evaluated from left to right
  • 36.
    3) Relational Operators– Equal to (==) – The function of the ‘equal to’ operator ( == ) is to check if two of the available operands are equal to each other or not. – If it is so, then it returns to be true, or else it returns false. – Examples: 3 == 3 will return true 2 == 3 will return false
  • 37.
    3) Relational Operators– Not Equal (!=) – The function of the ‘not equal’ operator ( != ) is to check if two of the available operands are not equal to each other. – If they’re, then it returns true, otherwise false. – Examples: 2 != 3 will return true 3 != 3 will return false
  • 38.
    3) Relational Operators– Less Than (<) – The function of the ‘less than’ operator ( < ) is to check if the first available operand is less than the second one. – If so, then it returns true, otherwise false. – Examples: 3 < 3 will return false 2 < 3 will return true
  • 39.
    3) Relational Operators– Less or Equal (<=) – The function of the ‘less than or equal’ operator ( <= ) is to check if the first available operand is less than or equal to the second one. – If so, then it returns true, otherwise false. – Examples: 3 <= 3 will return true 2 <= 3 will return true 8 < 5 < 2 will return false (8 < 5) → False or 0 0 < 2 → True
  • 40.
    3) Relational Operators– Greater Than (>) – The function of the ‘greater than’ operator ( > ) is to check if the first available operand is greater than the second one. – If so, then it returns true, otherwise false. – Examples: 4 > 3 will return true 2 > 3 will return false 8 > 5 > 2 will return false (8 > 5) → True or 1 1 > 2 → False
  • 41.
    3) Relational Operators– Greater or Equal (>=) – The function of the ‘greater than or equal’ operator ( >= ) is to check if the first available operand is greater than or equal to the second one. – If so, then it returns true, otherwise false. – Examples: 4 >= 3 will return true 2 >= 3 will return false
  • 42.
  • 43.
    4) Logical Operators –We have three major logical operators in the C language: Important: Short-Circuiting in Logical Operators in C. Logical NOT (!) Logical OR ( || ) Logical AND ( && )
  • 44.
    Name AND ORNOT XOR Algebraic Expression 𝐴𝐵 𝐴 + 𝐵 ҧ 𝐴 𝐴 ⊕ 𝐵 Symbol Truth Table A B C A B C A C A C 0 1 1 0 A B C 0 0 0 0 1 0 1 0 0 1 1 1 A B C 0 0 0 0 1 1 1 0 1 1 1 1 Logic Gates A B C 0 0 0 0 1 1 1 0 1 1 1 0 A B C
  • 45.
    4) Bitwise Operators –Types of bitwise operators found in C programming language Operator Meaning & Bitwise AND | Bitwise OR ^ Bitwise XOR ~ Bitwise complement << Shift left >> Shift right
  • 46.
    4) Bitwise Operators- AND Example: 12 = 00001100 (In Binary) 25 = 00011001 (In Binary) Bitwise AND operation of 12 and 25 00001100 & 00011001 ________ 00001000 = 8 (In decimal)
  • 47.
    4) Bitwise Operators- OR Example: 12 = 00001100 (In Binary) 25 = 00011001 (In Binary) Bitwise OR operation of 12 and 25 00001100 | 00011001 ________ 00011101 = 29 (In decimal)
  • 48.
    4) Bitwise Operators- XOR Example: 12 = 00001100 (In Binary) 25 = 00011001 (In Binary) Bitwise XOR operation of 12 and 25 00001100 ^ 00011001 ________ 00010101 = 21 (In decimal)
  • 49.
    4) Bitwise Operators– Complement (Not) Example: 35 = 00100011 (In Binary) Bitwise complement operation of 35 ~ 00100011 ________ 11011100 = 220 (In decimal) – Also called as one’s complement operator. Note: Takes 4-bit blocks.
  • 50.
    4) Bitwise Operators– Right shift
  • 51.
    4) Bitwise Operators– Right shift Example: 212 = 11010100 (In binary) 212 >> 2 = 00110101 (In binary) [Right shift by two bits] 212 >> 7 = 00000001 (In binary) 212 >> 8 = 00000000 212 >> 0 = 11010100 (No Shift) – Right shift operator shifts all bits towards right by certain number of specified bits.
  • 52.
    4) Bitwise Operators– Left shift
  • 53.
    4) Bitwise Operators– Left shift Example: 212 = 11010100 (In binary) 212 << 1 = 110101000 (In binary) [Left shift by one bit] 212 << 0 = 11010100 212 << 4 = 110101000000 (In binary) = 3392 (In decimal) – Left shift operator shifts all bits towards left by certain number of specified bits.
  • 54.
    5) Miscellaneous Operators –Besides the operators discussed above, there are a few other important operators Operator Description Example sizeof() Returns the size of a variable. sizeof(a), where a is integer, will return 4. & Returns the address of a variable. &a; returns the actual address of the variable. ∗ Pointer to a variable. *a; ? : Conditional Expression. If Condition is true ? then value X : otherwise value Y
  • 55.
    Operators Precedence Category OperatorAssociativity Postfix () [] -> . ++ -- Left to right Unary + - ! ~ ++ -+ (type)* & sizeof Right to left Multiplicative * / % Left to right Additive + - Left to right Relational < <= > >= Left to right Equality == != Left to right Bitwise AND & Left to right Bitwise XOR ^ Left to right Bitwise OR | Left to right Logical AND &+ Left to right Logical OR |+ Left to right Conditional ?: Right to left Assignment = += -= *= /= % = > >= < <= & = ^= | = Right to left Comma , Left to right
  • 57.
    Expression Statement 1 Statement 2 Statementn ⋮ Statement 1 Statement 2 Statement n ⋮ True False Flowchart of if-else decision making statements
  • 58.
    Syntax if (expression) { statement; } if(expression) { statement; } else { statement; } int x = 7; if (x == 5) { printf("Yes"); } int x = 7; if (x == 5) { printf("Yes"); } else { printf("No"); }
  • 59.
    if else-if ladder if(expression) { statement; } else if { statement; } else { statement; } int x = 5; if (x == 5) { printf("x = 5"); } else if (x > 5) { printf("x > 5"); } else { printf("x < 5"); }
  • 60.
    Nearest if #include <stdio.h> intmain() { int a, b, c; printf("Enter three numbers, a, b, and c: "); scanf("%i %i %i", &a, &b, &c); if (a == b) if (b == c) printf("a, b, and c are the samen"); else printf("a, b, and c are differentn"); return 0; }
  • 61.
    Correct indentation #include <stdio.h> intmain() { int a, b, c; printf("Enter three numbers, a, b, and c: "); scanf("%i %i %i", &a, &b, &c); if (a == b) if (b == c) printf("a, b, and c are the samen"); else printf("a, b, and c are differentn"); return 0; }
  • 62.
    Correct Program #include <stdio.h> intmain() { int a, b, c; printf("Enter three numbers, a, b, and c: "); scanf("%i %i %i", &a, &b, &c); if (a == b) { if (b == c) printf("a, b, and c are the samen"); } else printf("a, b, and c are differentn"); return 0; }
  • 63.
    Conditional if-else (? : ) #include <stdio.h> int main() { int num1 = 10, num2; num2 = num1 == 10 ? num1 : 20; printf("num1 = %i, num2 = %i", num1, num2); return 0; }
  • 64.
    Another possibility –with only one statement int x = 2; if (x == 5) printf("x = 5"); else if (x > 5) printf("x > 5"); else printf("x < 5");
  • 65.
    Another possibility –with only one statement int x = 7; if (x == 5) printf("x = 5"); else if (x > 5 && x < 10) printf("5 < x < 10"); else printf("x < 5 or x > 10");
  • 66.
    What will bethe output? int a = 2; if (a = 0) printf("a = 5"); int a = 2; if (0 = a) printf("a = 5"); Example 1: Example 2:
  • 67.
    int a =2; if (1 < a < 10) printf("True"); Example 3: int a = 2; if (a) printf("a is non-zero"); Example 4: Although C generates a 1 to indicate true, it assumes that any value other than 0 (such as –7 or 44) is true; only 0 is false.
  • 68.
    Switch Statement switch (expression){ case value1: // code to be executed; break; // optional case value2: // code to be executed; break; // optional ... default: // code to be executed if all cases are not matched } Rules for Switch Statement 1. The switch expression must be of an integer or character type. 2. The case value must be an integer or character constant. 3. The case value can be used only inside the switch statement. 4. The break statement in switch case is optional. (Switch statements is fall through) C Switch statement is fall-through In C language, the switch statement is fall through; it means if you don't use a break statement in the switch case, all the cases after the matching case will be executed.
  • 69.
    Switch Statement (Cont.) intx, y; char a, b; float f; Switch Valid / Invalid switch (x) ✓ switch (x + 2.5) ✘ switch (a + b - 2) ✓ switch (f) ✘ switch (x > y) ✓ // Determine Valid and Invalid Variables Case Valid / Invalid case 3; ✓ case 'a'; ✓ case x + 2; ✘ case 'x' > 'y'; ✓ case 2.5; ✘ case 1, 2, 3; ✘
  • 70.
    Switch Statement –Example #include <stdio.h> int main() { char grade = ’A’; switch (grade) { case ’A’: printf(”Excellent!"); break; // optional case ’B’: printf(”Good!"); break; // optional default: printf(”Failed!"); } return 0; }
  • 71.
    Switch Statement –Example #include <stdio.h> int main() { char grade = ’A’; switch (grade) { case ’A’: case ’B’: case ’C’: printf(”Good!"); break; // optional default: printf(”Failed!"); } return 0; } // You can combine multiple cases
  • 72.
  • 73.
    End of lecture2 ThankYou!