Module 2 Notes and Final
Module 2 Notes and Final
Module II
• Basic structure of C program: Character set, Tokens, Identifiers
in C, Variables and Data Types, Constants, Console IO
Operations, printf and Continue statements. (Simple programs
covering control flow) scanf
• Operators and Expressions: Expressions and Arithmetic
Operators, Relational and Logical Operators, Conditional
operator, size of operator, Assignment operators and Bitwise
Operators. Operators Precedence
• Control Flow Statements: If Statement, Switch Statement,
Unconditional Branching using goto statement, While Loop, Do
While Loop, For Loop, Break
C PROGRAM STRUCTURE
• Documentation Section
• Link Section
• Definition Section
• Local Declarations
Eg: Header File or Standard files: These files contains definition of pre-defined
functions like printf(), scanf() etc. These files must be included for working with
these functions.
Syntax: #include<file name>
Eg: #include<stdio.h>
• These instructions are called preprocessor directives which tell the compiler to
preprocess the source code before compiling.
}
C CHARACTER SET
• All valid characters in C program are termed as C character set
Alphabet
All upper case letters and lower case letters
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ASCII CODE of A to Z is from 65 to 90
abcdefghIjklmnopqrstuvwxyz ASCII CODE of a to z is from 97 to 122
Digits
All digits. ASCII CODE of 0 to 9 is from 48 to 57
0 1 2 3 4 5 6 7 8 9
Special Characters
Most of the special characters are supported in C programming.
~ ! # $ % ^ & * _ - + = { } [ ] | \ / < > , . : ; ‘ “ ?
White Spaces
White spaces are any sort of spaces or sequence of characters called escape sequences to generate spaces like tabs or new
lines.
\b blank space
\n new line
\t horizontal tab
\v vertical tab
C TOKENS
smallest individual units
1. Keywords int
Char
Integer data type
Character datatype
float Floating point datatype
•Keywords are predefined, reserved words used in programming double Double datatype
auto Automatic storage class
static Static storage class
•Meaning of the keywords has already been described to the C compiler. extern Extern storage class
register Register storage class
global Global variable declaration
•They cannot be used as variable names. struct Structure datatype
union Union datatype
•Keywords are part of the syntax and they cannot be used as an identifier. if If conditional statement
else Else conditional statement
break Break unconditional statement
while While loop statement
do Do loop statement
void Void datatype
continue Continue statement
volatile Volatile qualifier for a variable
switch Switch conditional statement
case Case in switch statement
default Default case in switch statement
for For loop statement
goto Goto unconditional jump statement
typedef Defining a new name to existing data type
const Constant definition
size of Operator to find size of a datatype
enum Enumeration data type
return Return a value to called function
long Make Long version of any data type
short Make short version of any data type
signed Make Signed version of datatypes
unsigned Make unsigned version of datatypes
2. Identifiers
• These are the names we use for a variable, functions etc in our program.
• Names can begin with a character or an underscore followed by any characters or
numbers.
• Uppercase and lowercase letters are not equivalent in C, so the two identifiers r1 and
R1 do not describe the same object.
4. There is no rule on how long an identifier can be. However, you may run
into problems in some compilers if the identifier is longer than 31
characters.
3. Constants
Integer Constants
• They are integer numbers
• It can have a positive or negative sign. In case it doesn’t have any sign it is taken as a positive
integer.
• No blank spaces or commas are allowed in an integer constant.
• Eg: 257, +563,-3245,-56
Real Constants
• also known as Floating point Constants are numbers that have a whole number followed by a
decimal point followed by the fractional number.
• The real constants can be expressed in two forms: Fractional Form and Exponential Form
• It can have a positive or negative sign. In case it doesn’t have any sign it is taken as positive.
• No blank spaces or commas are allowed.
• Eg: 546.236, +453.89, -22.564
5.6e9, +2.0e-7, -5.6e+8, -7.8e-5.
Character Constants
• It is a single alphabet, digit or special character enclosed within ‘single quotes’.
• Should be enclosed within single quotes.
• It can have only one character, digit or special character.
• Eg: ‘A’, ‘f’, ‘4’
String Constants
• It is a combination of alphabet, digits and special characters enclosed within “double
quotes”.
• Should be enclosed within double quotes.
• It can be of any length.
• It ends with a null character assigned to it by the compiler.
• Eg: “Welcome to Saintgits”, “Good to see you”, “5 modules”, “learning is fun”.
4. Strings
• Strings are sequence of characters enclosed in double quotes for example
• Eg: “Hello”, “abc”, ”hello123”
• Every string is automatically ending with a special character called the null
character (/0).
5. Special Symbols
• These are the punctuators used in C and have a special meaning .
Brackets [ ] Opening and closing brackets are used as array element reference. These
indicate single and multidimensional subscripts.
Parentheses ( ) These special symbols are used to indicate function calls and function
parameters.
Braces { } These opening and ending curly braces mark the start and end of a block of
code containing more than one executable statement.
Semicolon ; It is used to separate more than one statements like in for loop is
separates initialization, condition, and increment.
comma , It is an operator that essentially invokes something called an initialization
list.
an asterisk * it is used for multiplication.
assignment = It is used to assign values.
Preprocessor # The preprocessor is a macro processor that is used automatically by
the compiler to transform your program before actual compilation.
6. Operators in C
• C supports a rich set of operators.
Result of
Operator Operation Example
operation
+ Addition 7+3 10
- Subtraction 7–3 4
* Multiplication 7*3 21
/ Division 7/3 2
% Modulus (Remainder after division) 7% 3 1
Operands must be numbers. It can also be expressions or functions which results in a numeric value.
Result of
Operator Operation Example
operation
Operands can be Boolean values. It can also be expressions or functions which results in a Boolean value.
Result of
Operator Operation Examples
operation
0 && 0 0
0 && 1 0
&& Logical AND
1 && 0 0
1 && 1 1
0 || 0 0
0 || 1 1
|| Logical OR
1 || 0 1
1 || 1 1
!0 1
! Logical NOT
!1 0
Assignment Used to assign values to a variables
Type: Binary (works on two operands)
Operators
Operands must be numbers
Let x= 5 initially for all examples
Result of
Operator Operation Example Meaning operation
(value of x)
= Assign value from right to left x=2 x=2 2
+= Add and assign x += 2 x=x+2=5+2 7
-= Subtract and assign x -= 2 x=x-2=5-2 3
*= Multiply and assign x *= 2 x=x*2=5*2 10
/= Divide and assign x /= 2 x=x/2=5/2 2
%= Modulus operation and assign x %= 2 x=x%2=5%2 1
&= Bitwise AND and assign x &= 2 x=x&2=5&2 0
|= Bitwise OR and assign x |= 2 x=x|2=5|2 7
^= Bitwise XOR and assign x ^= 2 x=x^2=5^2 7
<<= Bitwise shift left and assign x <<= 2 x = x << 2 = 5 << 2 20
>>= Bitwise shift right and assign x >>= 2 x = x >> 2 = 5 >> 2 1
Increment
Used to perform increment / decrement operations
Decrement Operands can be numeric variable constants. It can also be expressions or functions returning a
number.
Result of
Operator Operation Example
operation
Let x = 5 and y = 7.
++ Increment x++ 6
-- Decrement y-- 6
If expression 1 is
true, Expression 2
Method 1 is executed;
Expression 1? Expression 2 : Expression 3 If expression 1 is (x<y) ? printf(“%d”, x) : printf(“%d”, y); 2
false Expression 3
is executed
If expression is
true, value 1 is
assigned to
Method 2 variable;
Variable = Expression ? Value 1: Value 2 If expression is z = (x != y) ? (x+100) : (x-100); 105
false value 2 is
assigned to
variable
Used to perform bitwise operations.
Bitwise
Operators Type: &, |, <<, >> and ^ are Binary (works on two operands)
~ Unary (works on single operand).
Operands must be numbers. It can also be expressions or functions which results in a numeric value.
Result of
Operator Operation Example
operation
& Bitwise AND 4&2 0
| Bitwise OR 4|2 6
~ Bitwise one’s compliment ~4 -5
^ Bitwise XOR 4^2 6
>> Bitwise Right shift 4 >> 2 1
<< Bitwise Left shift 4<<2 16
Operators
Let char c;
int x=4, *p;
Result /
Operator Operation Example Meaning of
operation
Returns the right side operand value. Both
operands can be expressions resulting in a x = ( (4+2) , (++x) )
, 5
value. Both expressions will be executed but
result of first expression is discarded.
sizeof(char) 1
sizeof Size of a data type or memory location sizeof(c) 1
sizeof(x) 4
& Address of a memory location &x Address of x
Value of the
variable, that
* Pointer *p
the pointer p
points to
Expressions
• The combination of operators and operands is said to be an expression.
Arithmetic Expressions
• An arithmetic expression is a combination of variables, constants, and operators
arranged as per the syntax of the language.
• Example: a = x + y;
• Expressions are evaluated using an assignment statement of the form
variable = expression;
Operator Precedence
Operators Associativity
Eg: ‘*’ and ‘/’ have same precedence and their associativity is Left to
Right, so the expression “100 / 10 * 10” is treated as “(100 / 10) * 10”.
Operator Precedence and Associativity
Example 1:-
Example 2:-
• The red colored portion of the expression represents the order of execution based on
operator precedence and associativity.
Y = (3+2*2)*5 == 0 ? 10 : 20 ;
Y = (3+2*2)*5 == 0 ? 10 : 20 ;
Y = (3+2*2)*5 == 0 ? 10 : 20 ;
Y = (3+4)*5 == 0 ? 10 : 20 ;
Y = (7)*5 == 0 ? 10 : 20 ;
Y = 35 == 0 ? 10 : 20 ;
Y = 0 ? 10 : 20 ;
Y = 20 ;
Data Types in C Data Types in C
Void
PRIMARY DATA TYPES
Integer
Integers datatype holds integer numbers
char
Datatype
Keyword to declare an character variable :
Example of declaration : char ch;
here the variable ch is declared as char
type.
Format Specifier : %c
Datatype
here the variable var is declared as
float type.
Format Specifier : %f
Examples of values float type can hold : 3.5, +512.4543, -86.784 Decimal form - using %f
8.964578e+02 Exponential
form – using %e
Variants Format specifier Memory size
float %f 4 bytes
double %lf 8 bytes
Long double %Lf 16 bytes
Boolean This datatype is used to hold boolean values. ie 1 or 0 to represent true or false respectively
bool
Datatype
Keyword to declare an Boolean variable :
Example of declaration : bool B;
here the variable B is declared as bool
type.
Examples of values bool type can hold : 0,1
Void
This datatype represents no value.
It used for declaring functions having no return value.
Void
DERIVED DATA TYPES
Array
Used for storing a set of elements of same datatype (one dimensional / multi dimensional)
Pointer
Used for storing address of a memory location
Functio
A function is a set of code that performs some specific task or a set of tasks.
n Example
returns int data.
: int sum ( int a, int b);
Sum is declared as a function which takes two arguments a and b of int data type and
Void
USER DEFINED DATA TYPES
Structure To make a collection of variables of same or different data types
Keyword : struct
Keyword : union
Example : union Library {
char bookName[25];
int year;
} book;
book is declared as union Library type with two members of char array type and int type
Memory allocation is that of the member with largest size.
Keyword: enum
Syntax : enum enumName { member1, member2,…… member N };
The enumName is the name of enumeration having members member1, member2
etc.
Example : enum Trimester { July, August, September, October};
July, August, September, October are the members of enumerated type Trimester
by default the value of first member is 0, second member 1, third member 2, …
ie in this example by default July = 0, August = 1, September = 2, October = 3
we can also provide alternate values inside the definition like
enum Trimester { July = 1, August = 2, September = 3, October = 4};
Declaration: To declare a variable as enum Trimester type, the following can be written.
enum Trimester t;
t is declared as enum Trimester type.
t can take the values of the enumerated type ie. July, August, September
or October.
Typedef This is used to give a new name to an existing datatype.
Keyword: typedef
formatSpecifiers Specifies the data type of the data to be read from the keyboard
Common format specifiers are
%c character
%d integer
%f float
%lf double
%s string
argumentList: The list of address locations to which the data from input device need to be stored.
Input Output functions in C
printf()
It is used to display formatted data on a standard output device like an LCD screen.
This function is defined in stdio.h library
Syntax:
printf ("formatSpecifiers and/or strings", argumentList);
formatSpecifiers Specifies the data type of the data to be read from the keyboard
Common format specifiers are
%c character
%d integer
%f float
%lf double
%s string
strings: Any combination of strings and escape sequences can be given within double quotes to display on screen.
argumentList: The list of values to display
Output:
Control Flow Statements
• If Statement
• Switch Statement
Decision Making Statements
• Conditional Operator
• While Loop
Looping Statements
• Do While Loop
• For Loop
Syntax
if (test expression) {
// statements to be
// executed if the
}
• If the test expression is evaluated to true, statements inside the body of if are executed.
• If the test expression is evaluated to false, statements inside the body of if are not executed.
If Statement (Flowchart)
If else Statement
Syntax
if (condition) {
// statements to be executed if the test expression is true
}
else {
// statements to be executed if the test expression is false
}
If else Statement (Flowchart)
Nested if Statement
Syntax
if (condition1) {
// Executes when condition1 is true
if (condition2) {
// Executes when condition2 is true.
}
}
Nested if Statement (Flowchart)
if - else if - else ladder Statement
• Another way of putting ifs together when multipath decisions are involved.
Syntax
if (condition 1) {
//statements if condition 1 is true
}
else if (condition 2) {
//statements if condition 2 is true
}
else if (condition 3) {
//statements if condition 3 is true
}
.
.
.
else {
// statements if all the above conditions are false
}
if else ladder Statement (Flow chart)
Switch Statement
• Tests the value of a given variable (expression) against a list of case values and when a match is found, a
block of statements associated with that case is executed.
Syntax
switch (n) {
case 1: // code to be executed if n = 1;
break;
case 2: // code to be executed if n = 2;
break;
case 3: // code to be executed if n = 3;
break;
.
.
.
Syntax
• Here the test condition is evaluated and if the condition is true, then the body
of the loop is executed.
• After the execution of the body, the test condition is once again evaluated and if
true only, the body will be executed once gain.
• This continues until the test expression becomes false and the control is
transferred out of the loop.
Syntax
while (test_expression)
{
// statements
update_expression;
do while Statement (exit controlled loop)
• Here the body of the loop will be executed at least once before the test is
performed.
• On reaching the do statement, the program proceeds to evaluate the body of
the loop first. At the end of the loop, the test condition in the while statement is
evaluated.
• If the condition is true, the program continues to evaluate the body of the loop
once again. This process continues as long as the condition is true.
• When the condition becomes false, the loop will be terminated and the control
goes to the statement that appears immediately after the while statement.
do while Statement (exit controlled loop)
Syntax
do
{
// loop body
update_expression;
}
while (test_expression);
for statement (entry controlled loop)
Syntax
for (initialization expr; test expr; update expr)
{
// statements in the loop
}
for Statement (entry controlled loop)
Execution order
• The initialization expr step is executed first, and only once. This step allows you
to declare and initialize any loop control variables. You are not required to put a
statement here, as long as a semicolon appears.
• Next, the test expr is evaluated. If it is true, the body of the loop is executed. If it
is false, the body of the loop does not execute and the flow of control jumps to the
next statement just after the 'for' loop.
• After the body of the 'for' loop executes, the flow of control jumps back up to the
update expr statement. This statement allows you to update any loop control
variables. This statement can be left blank, as long as a semicolon appears after
the condition.
• The condition is now evaluated again. If it is true, the loop executes and the
process repeats itself (body of loop, then increment step, and then again
condition). After the condition becomes false, the 'for' loop terminates.
continue and break statements in C
#include <stdio.h>
int main()
{
int i, n, sum=0;
return 0;
}
#include <stdio.h> // Include the standard input/output header file.
int main() { int i, n, sum = 0; // Declare variables 'i' for loop counter, 'n' for
user input, and 'sum' to store the sum.
printf("Input number of terms : "); // Print a message to prompt user input.
scanf("%d", &n); // Read the value of 'n' from the user.
printf("\nThe odd numbers are :"); // Print a message indicating that odd numbers
will be displayed.
for (i = 1; i <= n; i++) { // Start a loop to generate odd numbers based on user
input.
printf("%d ", 2 * i - 1); // Print the odd number. sum += 2 * i - 1; // Add the
odd number to the running sum. }
printf("\nThe Sum of odd Natural Number upto %d terms : %d \n", n, sum); // Print
the sum of odd numbers.
return 0; }