0% found this document useful (0 votes)
94 views

PPS Module-2

The document provides an overview of the fundamentals of the C programming language. It discusses what C language is, highlighting that it was developed by Dennis Ritchie for system applications and is considered the base for other languages. It also covers the history of C language from its development in 1972 at Bell Labs to modern standards. The document outlines key features of C like being simple, portable, structured, and supporting dynamic memory allocation. It also describes the structure of a C program and common elements like comments, header files, characters, tokens, keywords, and identifiers.

Uploaded by

Kapil Bhatt
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)
94 views

PPS Module-2

The document provides an overview of the fundamentals of the C programming language. It discusses what C language is, highlighting that it was developed by Dennis Ritchie for system applications and is considered the base for other languages. It also covers the history of C language from its development in 1972 at Bell Labs to modern standards. The document outlines key features of C like being simple, portable, structured, and supporting dynamic memory allocation. It also describes the structure of a C program and common elements like comments, header files, characters, tokens, keywords, and identifiers.

Uploaded by

Kapil Bhatt
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/ 79

Fundamentals

of
“C” language
What is C Language

The C Language is developed by Dennis Ritchie for creating system applications that directly
interact with the hardware devices such as drivers, kernels, etc.

C programming is considered as the base for other programming languages, that is why it is
known as mother language.

It can be defined by the following ways:

1. Mother language
2. System programming language
3. Procedure-oriented programming language
4. Structured programming language
5. Mid-level programming language
History of C Language

 History of C language is interesting to know. Here we are going to discuss a brief history
of the c language.

 C programming language was developed in 1972 by Dennis Ritchie at bell laboratories


of AT&T (American Telephone & Telegraph), located in the U.S.A.

 Dennis Ritchie is known as the founder of the c language.

 It was developed to overcome the problems of previous languages such as B, BCPL, etc.

 Initially, C language was developed to be used in UNIX operating system.

 It inherits many features of previous languages such as B and BCPL.


History of C Language
Let's see the programming languages that were developed before C language.

Language Year Developed By


Algol 1960 International Group
BCPL 1967 Martin Richard
B 1970 Ken Thompson
Traditional C 1972 Dennis Ritchie
K&RC 1978 Kernighan & Dennis Ritchie

ANSI C 1989 ANSI Committee


ANSI/ISO C 1990 ISO Committee
C99 1999 Standardization Committee
Features of C Language
Features of C Language
Simple
C is a simple language in the sense that it provides a structured approach (to break the
problem into parts), the rich set of library functions, data types, etc

Machine Independent or Portable


Unlike assembly language, c programs can be executed on different machines with some
machine specific changes. Therefore, C is a machine independent language.

Mid-level programming language


Although, C is intended to do low-level programming. It is used to develop system
applications such as kernel, driver, etc. It also supports the features of a high-level language.
That is why it is known as mid-level language.
Features of C Language
Structured programming language
C is a structured programming language in the sense that we can break the program
into parts using functions. So, it is easy to understand and modify. Functions also
provide code reusability.
Rich Library
C provides a lot of inbuilt functions that make the development fast.
Memory Management
It supports the feature of dynamic memory allocation. In C language, we can free the
allocated memory at any time by calling the free() function.
Speed
The compilation and execution time of C language is fast since there are lesser inbuilt
functions and hence the lesser overhead.
Structure of C Program
Program
Documentation section
1 // Program for addition of 2 nos
(Used for comments)
2
Link section 3
4
Definition section 5
6 void fun();
7
Global declaration section 8 int a=10;
(Variables used in more than 9
one functions) 10
void main () 11 void main( )
{ 12 {
Declaration part 13 printf("Value of a inside main function: %d", a);
Executable part 14 fun();
} 15 }
16
Subprogram section 14 void fun()
(User defined functions) 18 {printf("Value of a inside fun function: %d", a);}
Comments
 A comment is an explanation or description of the source code of the program
 It helps a programmer to explain logic of the code and improves program
readability.
 At run-time, a comment is ignored by the compiler.
 There are two types of comments in C:
 Single line comment
 Represented as // double forward slash
 It is used to denote a single line comment only.
 Example: // Single line comment
 Multi-line comment
 Represented as /* any_text */ start with forward slash and asterisk (/*) and end with asterisk and
forward slash (*/).
 It is used to denote single as well as multi-line comment.
 Example: /* multi line comment line -1
 multi line comment line -2 */
Header files
 A header file is a file with extension .h which contains the set of predefined
standard library functions.
 The “#include” preprocessing directive is used to include the header files with
extension in the program.
Header file Description
stdio.h Input/Output functions (printf and scanf)
conio.h Console Input/Output functions (getch and clrscr)
math.h Mathematics functions (pow, exp, sqrt etc…)
string.h String functions (strlen, strcmp, strcat etc…)
Character Set of “C” Language
 Every language contains a set of characters used to construct words, statements,
etc..
 C language also has a set of characters which include alphabets, digits,
and special symbols.
 C language supports a total of 256 characters.

• Every C program contains statements.


• These statements are constructed using words and these words are constructed
using characters from C character set.
Character Set of “C” Language
C language character set contains the following set of characters...

1. Alphabets
2. Digits
3. Special Characters
4. White Spaces
Character Set of “C” Language
Here is a table that represents all the types of character sets that we can use in the C language

Type of Character Description Characters


Lowercase Alphabets a to z a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v,
w, x, y, z

Uppercase Alphabets A to Z A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T,
U, V, W, X, Y, Z

Digits 0 to 9 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

Special Characters – `~@!$#^*%&()[]{}<>+=_–|/\;:„“


,.?

White Spaces – Blank Spaces, Carriage Return, Tab, New Line


Trigraph Characters in C
 There are many non-English keyboards.
 Many of these kinds of keyboards do not support some characters.
 ANSI C introduces the concept of the „trigraph‟ sequence to provide a way to enter
unavailable characters on some keywords.
 Suppose you have a no-English low-quality keyboard.
 You need to use the tilde symbol in your program but your keyboard doesn‟t contain it.
 So, what you can do?
 You can copy the tilde symbol from the internet or any kind of document or you can use
trigraph character.
 To write tilde we have to type ??-

Some ANSI C Trigraph Sequences are shown the table next slide
ANSI C Trigraph Sequences

Trigraph Sequence Translation

??( [ Left bracket


??) ] Right bracket
??< { Left brace
??> } Right brace
??= # Number sign
??! | Vertical bar
??/ \ Backslash
??’ ^ Caret
??- ~ Tiled
C Tokens
 In C programs, each word and punctuation is referred to as a token.
 C Tokens are the smallest building block or smallest unit of a C program.
C Tokens
 In C programs, each word and punctuation is referred to as a token.
 C Tokens are the smallest building block or smallest unit of a C program.

 C has the following tokens:

 Keywords
 C reserves a set of 32 words for its own use.
 These words are called keywords (or reserved words), and each of these keywords has a special
meaning within the C language.

 Identifiers
 Identifiers are names that are given to various user defined program elements, such as variable,
function and arrays.

 Constants
 Constants refer to fixed values that do not change during execution of program.
C Tokens
 The smallest individual unit of a program is known as token.
 C has the following tokens:

 Strings

 A string is a sequence of characters terminated with a null character \0.

 Special Symbols

 Symbols such as #, &, =, * are used in C for some specific function are called as special symbols.

 Operators

 An operator is a symbol that tells the compiler to perform certain mathematical or logical operation.
Keywords
Keywords are predefined, reserved words used in programming that have special
meanings to the compiler. Keywords are part of the syntax and they cannot be used
as an identifier
Identifiers
 Identifier refers to name given to entities such as variables, functions, structures
etc.

 Identifiers must be unique.



 They are created to give a unique name to an entity to identify it during the
execution of the program.

For example:

int money;
double accountBalance;
Rules for Naming Identifiers
 The first character of an identifier should be either an alphabet or an underscore,
and then it can be followed by any of the character, digit, or underscore.
 It should not begin with any numerical digit.
 In identifiers, both uppercase and lowercase letters are distinct. Therefore, we
can say that identifiers are case sensitive.
 Commas or blank spaces cannot be specified within an identifier.
 Keywords cannot be represented as an identifier.
 The length of the identifiers should not be more than 31 characters.
 Identifiers should be written in such a way that it is meaningful, short, and easy
to read.
Example of identifiers

Example of valid identifiers

total, sum, average, _m _, sum_1, etc.

Example of invalid identifiers

1.2sum (starts with a numerical digit)


2.int (reserved word)
3.char (reserved word)
4.m+n (special character, i.e., '+')
Types of identifiers

1. Internal identifiers
2. External identifiers
 Internal Identifier

If the identifier is not used in the external linkage, then it is known as an internal
identifier. The internal identifiers can be local variables.

 External Identifier

If the identifier is used in the external linkage, then it is known as an external


identifier. The external identifiers can be function names, global variables.
Differences between a Keyword and an Identifier

Keyword Identifier

Keyword is a pre-defined word. The identifier is a user-defined word

It must be written in a lowercase It can be written in both lowercase


letter. and uppercase letters.

Its meaning is pre-defined in the c Its meaning is not defined in the c


compiler. compiler.

It is a combination of alphabetical It is a combination of alphanumeric


characters. characters.

It does not contain the underscore It can contain the underscore


character. character.
Variables in C
 A variable is a name of the memory location.
 It is used to store data. Its value can be changed, and it can be reused many times.
 It is a way to represent memory location through symbol so that it can be easily identified.
Syntax to declare a variable:

type variable_list;
The example of declaring the variable is given below:

int a;
float b;
char c;

Here, a, b, c are variables. The int, float, char are the data types.

We can also provide values while declaring the variables as given below:

int a=10,b=20;//declaring 2 variable of integer type


float f=20.8;
char c='A';
Rules for Naming Variables in C

1. A variable name can consist of Capital letters A-Z,


lowercase letters a-z, digits 0-9, and the underscore character.
Valid Variable Names:
1. The first character must be a letter or underscore.
Int a;
2. Blank spaces cannot be used in variable names. Int _ab;
Int a30;
3. Special characters like #, $ are not allowed.
4. C keywords cannot be used as variable names. Invalid Variable Names:

5. Variable names are case sensitive. Int 2;


Int a b;
6. Values of the variables can be numeric or alphabetic. Int long;

7. Variable type can be char, int, float, double, or void.


Static Variables in C
#include<stdio.h>
 A variable that is declared with the static keyword
void fun();
is called static variable.
 It retains its value between multiple function calls. int main()
{
fun();
fun();
OUTPUT fun();
return 0;
a=1 }
b = 10 void fun()
{
a=1 int a = 1;
b = 11 static int b = 10;
printf("a = %d\n", a);
a =1 printf("b = %d\n", b);
b = 12 a++;
b++;
}
Automatic Variables in C
 All variables in C that are declared inside the block, are automatic variables by
default.
 We can explicitly declare an automatic variable using auto keyword.

void main()
{
int x=10; //local variable (also automatic)
auto int y=20; //automatic variable
}
External Variables in C

 We can share a variable in multiple C source files by using an external variable.


 To declare an external variable, you need to use extern keyword.

extern int x=10;//external variable (also global)

#include "myfile.h"
#include <stdio.h>

void printValue()
{
printf("Global variable: %d", global_variable);
}
Data Types
 Data types are defined as the data storage format that a variable can store a data.
 It determines the type and size of data associated with variables.

Data types in C

Primary Data type


Secondary Data type
(int, float, char)

Derived Data type defined Data type


(array, pointer) (structure, union, enum)
Primary Data Type
 Primary data types are built in data types which are directly supported by machine.
 They are also known as fundamental data types.
 int:
 int datatype can store integer number which is whole number without fraction part such as 10, 105
etc.
 C language has 3 classes of integer storage namely short int, int and long int. All of these data
types have signed and unsigned forms.
 Example: int a=10;
 float:
 float data type can store floating point number which represents a real number with decimal point
and fractional part such as 10.50, 155.25 etc.
 When the accuracy of the floating point number is insufficient, we can use the double to define the
number. The double is same as float but with longer precision.
 To extend the precision further we can use long double which consumes 80 bits of memory space.
 Example: float a=10.50;
Primary Data Type (cont…)
 char:
 Char data type can store single character of alphabet or digit or special symbol such as „a‟, „5‟ etc.
 Each character is assigned some integer value which is known as ASCII values.
 Example: char a=„a‟;

 void:
 The void type has no value therefore we cannot declare it as variable as we did in case of int or
float or char.
 The void data type is used to indicate that function is not returning anything.
Secondary Data Type
 Secondary data types are not directly supported by the machine.
 It is combination of primary data types to handle real life data in more convenient
way.
 It can be further divided in two categories,
 Derived data types: Derived data type is extension of primary data type. It is built-in system
and its structure cannot be changed. Examples: Array and Pointer.
 Array: An array is a fixed-size sequenced collection of elements of the same data type.
 Pointer: Pointer is a special variable which contains memory address of another variable.
 User defined data types: User defined data type can be created by programmer using
combination of primary data type and/or derived data type. Examples: Structure, Union,
Enum.
 Structure: Structure is a collection of logically related data items of different data types grouped
together under a single name.
 Union: Union is like a structure, except that each element shares the common memory.
 Enum: Enum is used to assign names to integral constants, the names make a program easy to read
and maintain.
There are the following data types in C language.

Types Data Types


int
char
Basic Data Type float
double
array
Derived Data Type pointer
structure
union
Enumeration Data Type enum
Void Data Type void
Next Slide
Data Types Memory Size Range

char 1 byte −128 to 127


signed char 1 byte −128 to 127
unsigned char 1 byte 0 to 255
short 2 byte −32,768 to 32,767
signed short 2 byte −32,768 to 32,767
unsigned short 2 byte 0 to 65,535
Data Types Memory Size Range
int 2 byte −32,768 to 32,767
signed int 2 byte −32,768 to 32,767
unsigned int 2 byte 0 to 65,535
short int 2 byte −32,768 to 32,767
signed short int 2 byte −32,768 to 32,767
unsigned short int 2 byte 0 to 65,535
long int 4 byte -2,147,483,648 to 2,147,483,647
signed long int 4 byte -2,147,483,648 to 2,147,483,647
unsigned long int 4 byte 0 to 4,294,967,295
float 4 byte
double 8 byte
long double 10 byte
Format Specifiers in C
 The Format specifier is a string used in the formatted input and output functions.
 The format string determines the format of the input and output. T
 he format string always starts with a '%' character.
The commonly used format specifiers in printf() function are:

Format Specifiers Description


%d or %i It is used to print the signed integer value where signed integer means that the variable can
hold both positive and negative values.
%u It is used to print the unsigned integer value where the unsigned integer means that the
variable can hold only positive value.
%o It is used to print the octal unsigned integer where octal integer value always starts with a 0
value.
%x It is used to print the hexadecimal unsigned integer where the hexadecimal integer value
always starts with a 0x value. In this, alphabetical characters are printed in small letters
such as a, b, c, etc.

%X It is used to print the hexadecimal unsigned integer, but %X prints the alphabetical
characters in uppercase such as A, B, C, etc.
Format Specifiers in C
 The Format specifier is a string used in the formatted input and output functions.
 The format string determines the format of the input and output. T
 he format string always starts with a '%' character.

The commonly used format specifiers in printf() function are:

Format Specifiers Description


%f It is used for printing the decimal floating-point values. By default, it prints the 6 values after
'.'.
%e/%E It is used for scientific notation. It is also known as Mantissa or Exponent.

%g It is used to print the decimal floating-point values, and it uses the fixed precision, i.e., the
value after the decimal in input would be exactly the same as the value in the output.

%p It is used to print the address in a hexadecimal form.


%c It is used to print the unsigned character.
%s It is used to print the strings.
%ld It is used to print the long-signed integer value.
Escape Sequences in C
 An escape sequence in C language is a sequence of characters that doesn't represent itself when
used inside string literal or character.
 It is composed of two or more characters starting with backslash \.
For example: \n represents new line.

Escape Sequence Meaning

Escape Sequence Meaning \v Vertical Tab

\a Alarm or Beep \\ Backslash

\b Backspace \' Single Quote

\f Form Feed \" Double Quote

\n New Line \? Question Mark

\r Carriage Return \nnn octal number

\t Tab (Horizontal) \xhh hexadecimal


number
\0 Null
ASCII value in C
What is ASCII code?

The full form of ASCII is the American Standard Code for information interchange.
It is a character encoding scheme used for electronics communication.
Each character or a special character is represented by some ASCII code, and each ascii
code occupies 7 bits in memory.
In C programming language, a character variable does not contain a character value itself
rather the ascii value of the character variable.
The ascii value represents the character variable in numbers, and each character variable
is assigned with some number range from 0 to 127.
For example, the ascii value of 'A' is 65.
In the above example, we assign 'A' to the character variable whose ascii value is 65, so 65
will be stored in the character variable rather than 'A'.
ASCII value in C
What is ASCII code?

The full form of ASCII is the American Standard Code for information interchange.
It is a character encoding scheme used for electronics communication.
Each character or a special character is represented by some ASCII code, and each ascii
code occupies 7 bits in memory.
In C programming language, a character variable does not contain a character value itself
rather the ascii value of the character variable.
The ascii value represents the character variable in numbers, and each character variable
is assigned with some number range from 0 to 127.
For example, the ascii value of 'A' is 65.
In the above example, we assign 'A' to the character variable whose ascii value is 65, so 65
will be stored in the character variable rather than 'A'.
Let's understand through an example.  In the above code, the first user will
We will create a program which will display the ascii value of give the character input, and the
the character variable. input will get stored in the 'ch'
variable.
#include <stdio.h>
int main()  If we print the value of the 'ch'
{ variable by using %c format specifier,
char ch; // variable declaration then it will display 'A' because we
printf("Enter a character"); have given the character input as 'A‘.
scanf("%c",&ch); // user input
printf("\n The ascii value of the ch variable is : %d", ch);  If we use the %d format specifier
return 0; then its ascii value will be displayed,
} i.e., 65.

 The output shows that the user gave


the input as 'A', and after giving input,
the ascii value of 'A' will get printed,
i.e., 65.
Commonly used
Special Symbols
with ASCII Values
Constants in C
 A constant is a value or variable that can't be changed in the program, for example: 10,
20, 'a', 3.4, "c programming" etc.
 There are different types of constants in C programming.

Constant Example

Decimal Constant 10, 20, 450 etc.


Real or Floating-point Constant 10.3, 20.2, 450.6 etc.
Octal Constant 021, 033, 046 etc.
Hexadecimal Constant 0x2a, 0x7b, 0xaa etc.
Character Constant 'a', 'b', 'x' etc.
String Constant "c", "c program", "c in javatpoint" etc.
Defining Constants in C

There are two ways to define constant in C programming.


1. const keyword
2. #define preprocessor

1) const keyword

The const keyword is used to define constant in C programming.


const float PI=3.14;

Now, the value of PI variable can't be changed.


Defining Constants in C
#define preprocessor
The #define preprocessor directive is used to define constant .
It can use any basic data type.

Syntax:
#define token value

Let's see an example of #define to define a constant.


#include <stdio.h>
#define PI 3.14
main()
{
printf("%f",PI);
}
Output:0
3.140000
Variables and Constants

 Variable is a symbolic name given to some value which can be changed.

 𝑥, 𝑦, 𝑎, 𝑐𝑜𝑢𝑛𝑡, 𝑒𝑡𝑐. can be variable names.

 𝑥=5 𝑎=𝑏+𝑐

 Constant is a fixed value which cannot be changed.

 5, −7.5, 1452, 0, 3.14, 𝑒𝑡𝑐.


Operators

 Arithmetic operators (+, - , *, /, %)

 Relational operators (<, <=, >, >=, ==, !=)

 Logical operators (&&, ||, !)

 Assignment operators (+=, -=, *=, /=)

 Increment and decrement operators (++, --)

 Ternary (Conditional) operators (? :)

 Bitwise operators (&, |, ^, <<, >>)

 Special operators ()
Arithmetic Operators
 Arithmetic operators are used for mathematical calculation.

Operator Meaning Example Description

+ Addition a+b Addition of a and b

- Subtraction a–b Subtraction of b from a

* Multiplication a*b Multiplication of a and b

/ Division a/b Division of a by b

% Modulo division- remainder a%b Modulo of a by b


Relational Operators
 Relational operators are used to compare two numbers and taking decisions based
on their relation.
 Relational expressions are used in decision statements such as if, for, while, etc…

Operator Meaning Example Description


< Is less than a<b a is less than b
<= Is less than or equal to a <= b a is less than or equal to b
> Is greater than a>b a is greater than b
>= Is greater than or equal to a >= b a is greater than or equal to b
== Is equal to a=b a is equal to b
!= Is not equal to a != b a is not equal to b
Logical Operators
 Logical operators are used to test more than one condition and make decisions.

Operator Meaning

&& logical AND (Both non zero then true, either is zero then false)

|| logical OR (Both zero then false, either is non zero then true)

! Is greater than

a b a&&b a||b
0 0 0 0
0 1 0 1
1 0 0 1
1 1 1 1
Assignment Operators
 Assignment operators (=) is used to assign the result of an expression to a variable.
 Assignment operator stores a value in memory.
 C also supports shorthand assignment operators which simplify operation with
assignment.
Operator Meaning
= Assigns value of right side to left side

+= a += 1 is same as a = a + 1
-= a -= 1 is same as a = a - 1
*= a *= 1 is same as a = a * 1
/= a /= 1 is same as a = a / 1
%= a %= 1 is same as a = a % 1
Increment and Decrement Operators

 Increment (++) operator used to increase the value of the variable by one.

 Decrement (--) operator used to decrease the value of the variable by one.

Example Explanation
x=100; After the execution the
x++; value of x will be 101.

Example Explanation
x=100; After the execution the
x--; value of x will be 99.
Increment and Decrement Operators (cont…)
Operator Description
Pre increment operator (++x) value of x is incremented before assigning it to the variable
on the left

Example Explanation Output


x=10; First increment value of x will be 11
p=++x; x by one then assign. p will be 11

Operator Description
Post increment operator (x++) value of x is incremented after assigning it to the variable on
the left

Example Explanation Output


x=10; First assign value of x x will be 11
p=x++; then increment value. p will be 10
Conditional Operators
 A ternary operator (? :) is known as conditional operator.
 Syntax: exp1 ? exp2 : exp3

Working of the ? : Operator


exp1 is evaluated first

if exp1 is true(nonzero) then


- exp2 is evaluated and its value becomes the value of the expression

If exp1 is false(zero) then


- exp3 is evaluated and its value becomes the value of the expression

Example
Example
m=2, n=3;
m=2, n=3; r=(m<n) ? m : n;
r=(m>n) ? m : n;
Explanation
Explanation
Value of r will be 2
Value of r will be 3
Bitwise Operators

 Bitwise operators are used to perform operation bit by bit.

 Bitwise operators may not be applied to float or double.

Operator Meaning
& bitwise AND
| bitwise OR
^ bitwise exclusive OR
<< shift left (shift left means multiply by 2)
>> shift right (shift right means divide by 2)
Bitwise Operators
8 = 1000 (In Binary) and 6 = 0110 (In Binary)

Example: Bitwise & (AND) Example: Bitwise | (OR)


int a=8, b=6, c; int a=8, b=6, c;
c = a & b; c = a | b;
printf("Output = %d", c); printf("Output = %d", c);
Output Output
0 14

Example: Bitwise << (Shift Left) Example: Bitwise >> (Shift Right)
int a=8, b; int a=8, b;
b = a << 1; b = a >> 1;
printf("Output = %d", b); printf("Output = %d", b);
Output Output
16 (multiplying a by a power of two) 4 (dividing a by a power of two)
Special Operators

Operator Meaning

& Address operator, it is used to determine address of the variable.

* Pointer operator, it is used to declare pointer variable and to get value from it.

, Comma operator. It is used to link the related expressions together.

sizeof It returns the number of bytes the operand occupies.

. member selection operator, used in structure.

-> member selection operator, used in pointer to structure.


Expressions
 An expression is a combination of operators, constants and variables.
 An expression may consist of one or more operands, and zero or more operators to
produce a value.

Operand 1 Operand 2 Operand 3

answer = a + b * c;

Variable to store Operator 1 Operand 2


the expression value
Evaluation of Expressions
 An expression is evaluated based on the operator precedence and associativity.

 When there are multiple operators in an expression, they are evaluated according
to their precedence and associativity.
Operator precedence
 Precedence of an operator is its priority in an expression for evaluation.

 The operator with higher precedence is evaluated first and the operator with the
least precedence is evaluated last.

 Operator precedence is why the expression 5 + 3 * 2 is calculated as 5 + (3 * 2),


giving 11, and not as (5 + 3) * 2, giving 16.

 We say that the multiplication operator (*) has higher "precedence" or "priority"
than the addition operator (+), so the multiplication must be performed first.
Operator associativity
 Associativity is the left-to-right or right-to-left order for grouping operands to
operators that have the same precedence.

 Operator associativity is why the expression 8 - 3 - 2 is calculated as (8 - 3) - 2,


giving 3, and not as 8 - (3 - 2), giving 7.

 We say that the subtraction operator (-) is "left associative", so the left subtraction
must be performed first.

 When we can't decide by operator precedence alone in which order to calculate an


expression, we must use associativity.
Type conversion (Casting)
 Type conversion is basically a conversion of one type of data to another type.

 It is also known as Type Casting.

 There are two types of type conversion:

 Implicit Type Conversion


 Explicit Type Conversion
.
Implicit Type conversion (Casting)
 This type of conversion is usually performed by the compiler when necessary
without any commands by the user.
 It is also called Automatic Type Conversion.

Example: Implicit Type Conversion

int a = 20;
double b = 20.5;
printf("%lf", a + b);

Output

40.500000
Explicit Type conversion
 These conversions are done explicitly by users using the pre-defined functions.

Example: Explicit Type Conversion

Output double a = 4.5, b = 4.6, c = 4.9;


int result = (int)a + (int)b +
12 (int)c;
printf("result = %d", result);
printf() Function
 printf() is a function defined in stdio.h file

 In C programming language, printf() function is used to print the (“character, string,


float, integer, octal and hexadecimal values”) onto the output screen.
 Message and value of variable can also be printed with Printf() function
 Let‟s see few examples of printf()

 printf(“ ”);

 printf(“Hello World”); // Hello World

 printf(“%d”, c); // 15

 printf(“Sum = %d”, c); // Sum = 15

 printf(“%d+%d=%d”, a, b, c); // 10+5=15


scanf() Function
 scanf() is a function defined in stdio.h file

 scanf() function is used to read character, string, numeric data from keyboard

 Syntax of scanf

 scanf("%X", &variable);

 where %X is the format specifier which tells the compiler what type of data is in a
variable.
 & refers to address of “variable” which is directing the input value to a address
returned by &variable.
scanf() Function

Format Supported Example Description


specifier data types
%d Integer scanf(“%d”, &a) Accept integer value such as 1, 5, 25,
105 etc
%f Float scanf(“%f”, &b) Accept floating value such as 1.5,
15.20 etc
%c Character scanf(“%c”, &c) Accept character value such as a, f, j,
W, Z etc
%s String scanf(“%s”, &d) Accept string value such as diet,
india etc
getchar and putchar Function
Program
 getchar function reads a single
character from terminal. 1
2
#include <stdio.h>
void main( )
3 {
4 int c;
 putchar function displays the 5 printf("Enter a character: ");
character passed to it on the screen. 6 /* Take a character as input */
7 c = getchar();
8 /* Display the character */
9 printf("Entered character is: ");
10 putchar(c);
11 }

Output
Enter a character: a
Entered character is: a
gets and puts
Program
 gets function reads a line from stdin
into the buffer pointed to by s until 1
2
#include <stdio.h>
void main( )
either a terminating newline or EOF 3 {
(End of File) occurs. 4 /*Character array of length 100*/
5 char str[100];
6 printf("Enter a string: ");
 puts function writes the string 's' 7 /* Take a string as input */
and 'a' trailing newline to stdout. 8 gets( str );
9 /* Display the string */
10 printf("Entered string is: ");
11 puts( str );
12 }

Output
Enter a string: india
Entered string is: india
Preprocessor
 Preprocessors are programs that process our source code before compilation.
 There are a number of steps involved between writing a program and executing a
program in C.
 Let us have a look at these steps before we actually start learning about
Preprocessors.
C Program

Object Executable
Are there No Code Code
preprocessor Compiler Linker
directive

Yes

Preprocessor perform action


Types of Preprocessor
 There are 4 main types of preprocessor directives:

 Macros

 File inclusion

 Conditional compilation

 Other directives
Macro
 A macro is a fragment of code which has been given a name. Whenever the name
is used in program, it is replaced by the contents of the macro.

 Macro definitions are not variables and cannot be changed by your program code
like variables.

 The „#define‟ directive is used to define a macro.

 Do not put a semicolon ( ; ) at the end of #define statements.

 There are two types of macros:


 Object-like Macros

 Function-like Macros
Macro
Description Object-like Macros Function-like Macros
Definition The object-like macro is an identifier that The function-like macro looks like
is replaced by value. function call.
Use It is used to represent numeric constants. It is used to represent function.
Syntax #define CNAME value #define CNAME (expression)
Example #define PI 3.14 #define MIN(a,b) ((a)<(b)?(a):(b))
Program 1 #include <stdio.h> 1 #include <stdio.h>
2 #define PI 3.14 2 #define MIN(a,b) ((a)<(b)?(a):(b))
3 void main() 3 void main()
4 { int r=2; 4 {
5 float a; 5 printf("%d", MIN(2, 5));
6 a=PI*r*r; 6 }
7 printf("%f", a);
8 }

You might also like