0% found this document useful (0 votes)
12 views39 pages

Unit II - Notes

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

Unit II - Notes

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

Unit – II

Introduction to C Programming

Contents :

Features of C, basic concepts, structure of C program, program, declarations, variables,


data types, expressions, operators assignment, arithmetic, relational, logical, increment
and decrement, precedence of operators, type conversions, scanf and printf functions.
Case Study: Exchanging the values of two variables, summation of a set of numbers.

2.1 Features of C
C is a procedural programming language. It was initially developed by Dennis Ritchie in
the year 1972. It was mainly developed as a system programming language to write an
operating system. The main features of C language include low-level access to memory, a
simple set of keywords, and clean style, these features make C language suitable for
system programming like an operating system or compiler development.

Features of C Programming Language:


1. Procedural Language
2. Fast and Efficient
3. Modularity
4. Statically Type
5. General Purpose Language
6. Rich set of built in Operators
7. Libraries with rich Functions
8. Middle Level Language
9. Portability
10. Easy to Extend

Figure 2.1 Features of C Language


1. Procedural Language: In a procedural language like C step by step predefined
instructions are carried out. C program may contain more than one function to
perform a particular task. New people to programming will think that this is the only
way of a particular programming language works. There are other programming
paradigms as well in the programming world. Most of the commonly used paradigm
is an object-oriented programming language.
2. Fast and Efficient: Newer languages like java, python offer more features than c
programming language but due to additional processing in these languages, their
performance rate gets down effectively. C programming language as the been
middle-level language provides programmers access to direct manipulation with the
computer hardware but higher-level languages do not allow this. That’s one of the
reasons C language is considered as the first choice to start learning programming
languages. It’s fast because statically typed languages are faster than dynamically
typed languages.
3. Modularity: The concept of storing of C programming language code in the form of
libraries for further future uses is known as modularity. This programming language
van does a very little on its own most of its power is held by its libraries. C language
has it’s own library to solve common problems like in this we can use a particular
function by using a header file stored in its library.
4. Statically Type: C programming language is a statically typed language. Meaning the
type of variable is checked at the time of compilation but not at run time. Means each
time a programmer type a program they have to mention the type of variables used.
5. General Purpose Language: From system programming to photo editing software,
C programming language is used in various applications. Some of the common
applications where it’s used are as follows:
● Operating systems: Windows, Linux, iOS, Android, OXS

● Databases: PostgreSQL, Oracle, MySQL, MS SQL Server etc.


6. Rich set of built-in Operators: It is a diversified language with a rich set of built-
in operators which are used in writing complex or simplified C programs.
7. Libraries with rich Functions: Robust libraries and functions in C help even a
beginner coder to code with ease.
8. Middle-Level Language: As it is a middle-level language so it has the combined form
of both capabilities of assembly language and features of the high level language.
9. Portability: C language is lavishly portable as programs which are written in C
language can run and compile on any system with either none or small changes.
10. Easy to Extend: Programs written in C language can be extended means when a
program is already written in it then some more features and operations can be
added into it.

2.2 Structure of C Program


The structure of C Program consist of different sections shown in figure.
2.2.1 Preprocessor Directives:

● Before a C program is compiled in a compiler, source code is processed by a


program called preprocessor. This process is called preprocessing.
●Commands used in preprocessor are called preprocessor directives and they begin
with “#” symbol.

Below is the list of preprocessor directives that C programming language offers.

Preprocesso
Syntax/Description
r

Syntax: #define
Macro This macro defines constant value and can be any of the basic
data types.

Syntax: #include <file_name>


Header file
The source code of the file “file_name” is included in the
inclusion
main program at the specified place.

Syntax: #ifdef, #endif, #if, #else, #ifndef


Conditional
Set of commands are included or excluded in source program
compilation
before compilation with respect to the condition.

Syntax: #undef, #pragma


Other #undef is used to undefine a defined macro variable.
directives #Pragma is used to call a function before and after main
function in a C program.
2.2.2 Declarations

Global Variables
Global variables are defined outside a function, usually on top of the program. Global
variables hold their values throughout the lifetime of your program and they can be
accessed inside any of the functions defined for the program.
A global variable can be accessed by any function. That is, a global variable is available
for use throughout your entire program after its declaration. The following program
show how global and local variables are used in a program.
Local Variables
Local Variable is defined as a type of variable declared within programming block or
subroutines. It can only be used inside the subroutine or code block in which it is
declared. The local variable exists until the block of the function is under execution. After
that, it will be destroyed automatically.

#include <stdio.h>
/* global variable declaration */
int g;

int main () {

/* local variable declaration */


int a, b;

/* actual initialization */
a = 10;
b = 20;
g = a + b;

printf ("value of a = %d, b = %d and g = %d\n", a, b, g);

return 0;
}
A program can have same name for local and global variables but the value of local
variable inside a function will take preference. Here is an example –
#include <stdio.h>

/* global variable declaration */


int g = 20;

int main () {

/* local variable declaration */


int g = 10;

printf ("value of g = %d\n", g);

return 0;
}
When the above code is compiled and executed, it produces the following result –

value of g = 10
There are three places where variables you can declare variable programming language:

● Inside a function or a block: Local variables


● Outside of all functions: Global variables
● In the definition of function parameters: Formal parameters
KEY DIFFERENCE

● Local variable is declared inside a function whereas Global variable is declared


outside the function.
● Local variables are created when the function has started execution and is lost
when the function terminates, on the other hand, Global variable is created as
execution starts and is lost when the program ends.
● Local variable doesn’t provide data sharing whereas Global variable provides
data sharing.
● Local variables are stored on the stack whereas the Global variable are stored on
a fixed location decided by the compiler.
● Parameters passing is required for local variables whereas it is not necessary for
a global variable
● fundamental differences between Local and Global variables.

Parameter Local Global


Scope It is declared inside a function. It is declared outside the function.
If it is not initialized, a garbage value is If it is not initialized zero is stored as
Value
stored default.
It is created when the function starts It is created before the program's
Lifetime execution and lost when the functions global execution starts and lost when
terminate. the program terminates.
Data sharing is not possible as data of the Data sharing is possible as multiple
Data
local variable can be accessed by only one functions can access the same global
sharing
function. variable.
Parameters passing is required for local Parameters passing is not necessary
Parameters variables to access the value in other for a global variable as it is visible
function throughout the program
Modificatio
When the value of the local variable is When the value of the global variable
n of
modified in one function, the changes are is modified in one function changes
variable
not visible in another function. are visible in the rest of the program.
value
Local variables can be accessed with the
Accessed You can access global variables by any
help of statements, inside a function in
by statement in the program.
which they are declared.
Memory It is stored on a fixed location decided
It is stored on the stack unless specified.
storage by the compiler.

Advantages of using Global variables

● You can access the global variable from all the functions or modules in a program
● You only require to declare global variable single time outside the modules.
● It is ideally used for storing "constants" as it helps you keep the consistency.
● A Global variable is useful when multiple functions are accessing the same data.
Advantages of using Local Variables

● The use of local variables offer a guarantee that the values of variables will
remain intact while the task is running
● If several tasks change a single variable that is running simultaneously, then the
result may be unpredictable. But declaring it as local variable solves this issue as
each task will create its own instance of the local variable.
● You can give local variables the same name in different functions because they
are only recognized by the function they are declared in.
● Local variables are deleted as soon as any function is over and release the
memory space which it occupies.

Disadvantages of using Global Variables

● Too many variables declared as global, then they remain in the memory till
program execution is completed. This can cause of Out of Memory issue.
● Data can be modified by any function. Any statement written in the program can
change the value of the global variable. This may give unpredictable results in
multi-tasking environments.
● If global variables are discontinued due to code refactoring, you will need to
change all the modules where they are called.

Disadvantages of using Local Variables

● The debugging process of a local variable is quite tricky.


● Common data required to pass repeatedly as data sharing is not possible between
modules.
● They have a very limited scope.

What is more useful?


The local and global variable equally important while writing a program in any language.
However, a large number of the global variable may occupy a huge memory. An
undesirable change to global variables is become tough to identify. Therefore, it is
advisable to avoid declaring unwanted global variables.

Initializing Local and Global Variables


When a local variable is defined, it is not initialized by the system, you must initialize it
yourself. Global variables are initialized automatically by the system when you define
them as follows −

Data Type Initial Default Value

int 0
char '\0'

float 0

double 0

pointer NULL

2.2.3 main() Function


main() function is the entry point of any C program. It is the point at which execution of
program is started. When a C program is executed, the execution control goes directly to
the main() function. Every C program have a main() function.
Syntax of main() Function in C

void main()

……

…..

In above syntax;

● void: is a keyword in C language, void means nothing, whenever we use void as a


function return type then that function nothing return. here main() function no
return any value.
● In place of void we can also use int return type of main() function, at that time
main() return integer type value.
● main: is a name of function which is predefined function in C library.

2.2.4 Other functions in C


A function is a block of code that performs a specific task.
C allows you to define functions according to your need. These functions are known as
user-defined functions. For example:

Suppose, you need to create a circle and color it depending upon the radius and color.
You can create two functions to solve this problem:

● createCircle() function

● color() function

Note : You may refer the reference book to read more about the user defined
functions.

2.3 Compilation process in c

A program in C language involves into different processes. Below diagram will help you
to understand all the processes that a C program comes across.

The compilation is a process of converting the source code into object code. It is done
with the help of the compiler. The compiler checks the source code for the syntactical or
structural errors, and if the source code is error-free, then it generates the object code.

Lets understand it with an example

sample.c

1. #include <stdio.h>
2. int main()
3. {
4. printf("Hello javaTpoint");
5. return 0;
6. }
DO YOU KNOW DIFFERENCE BETWEEN STACK & HEAP MEMORY IN C LANGUAGE?

Stack : Stack is a memory region where Heap : Heap is a memory


“local variables”, “return addresses of region which is used by
function calls” and “arguments to functions” dynamic memory allocation
are hold while C program is executed. functions at run time.

Linked list is an example


CPU’s current state is saved in stack memory
which uses heap memory.

DO YOU KNOW DIFFERENCE BETWEEN COMPILERS VS INTERPRETERS IN C


LANGUAGE?

Compiler: reads the entire source Interpreter : reads the program


code of the program and converts it source code one line at a time and
into binary code. This process is executing that line. This process is
called compilation. called interpretation.
Binary code is also referred as Program speed is slow.
machine code, executable, and object Interpretation occurs at every line of
code. the program.
Example: BASIC
Program speed is fast.

One time execution.


Example: C, C++

2.4 Variable declaration in C and Data types

A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable
in C has a specific type, which determines the size and layout of the variable's memory; the range of
values that can be stored within that memory; and the set of operations that can be applied to the
variable.
The name of a variable can be composed of letters, digits, and the underscore character. It must begin
with either a letter or an underscore. Upper and lowercase letters are distinct because C is case-sensitive.
Based on the basic types explained in the previous chapter, there will be the following basic variable data
types −

Sr.No. Type & Description

1
char
Typically a single octet(one byte). It is an integer type.

2
int
The most natural size of integer for the machine.

3
float
A single-precision floating point value.

4
double
A double-precision floating point value.

5
void
Represents the absence of type.

C programming language also allows to define various other types of variables, like Enumeration,
Pointer, Array, Structure, Union.

A variable declaration tells the compiler where and how much storage to create for the
variable. A variable definition specifies a data type and contains a list of one or more
variables of that type as follows –
type variable_list;
Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any user-defined
object; and variable_list may consist of one or more identifier names separated by commas. Some valid
declarations are shown here –
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; declares and defines the variables i, j, and k; which instruct the
compiler to create variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The
initializer consists of an equal sign followed by a constant expression as follows –
type variable_name = value;
Ex .
int d = 3, f = 5; // definition and initializing d
and f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value
'x'.

Difference between variable declaration and definition

Variable declaration refers to the part where a variable is first declared or introduced
before its first use. Variable definition is the part where the variable is assigned a
memory location and a value. Most of the times, variable declaration and definition are
done together.
Rules for defining variables
1. A variable can have alphabets, digits, and underscore.
2. A variable name can start with the alphabet, and underscore only. It can’t start with a
digit.
3. No whitespace is allowed within the variable name.
4. A variable name must not be any reserved word or keyword, e.g. int, goto , etc.
C Keywords and Identifiers

Character set
A 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

C accepts both lowercase and uppercase alphabets as variables and functions.


Digits

0123456789

Special Characters

Special Characters in C Programming

, < > . _

( ) ; $ :

% [ ] # ?

' & { } "

^ ! * / |

- \ ~ +

White space Characters


Blank space, newline, horizontal tab, carriage return and form feed.

C 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. For example:

int money;

Here, int is a keyword that indicates money is a variable of type int (integer).
As C is a case sensitive language, all keywords must be written in lowercase. Here is a list
of all keywords allowed in ANSI C.

C Keywords
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

C Identifiers
Identifier refers to names 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

Here, money and accountBalance are identifiers.


Also remember, identifier names must be different from keywords. You cannot use int as
an identifier because int is a keyword.
Rules for naming identifiers
1. A valid identifier can have letters (both uppercase and lowercase letters), digits and
underscores.
2. The first letter of an identifier should be either a letter or an underscore.
3. You cannot use keywords like int, while etc. as identifiers.
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.
You can choose any name as an identifier if you follow the above rule, however, give
meaningful names to identifiers that make sense.

2.5 C Operator and Expression


An expression is a formula in which operands are linked to each other by the use of
operators to compute a value. An operand can be a function reference, a variable, an
array element or a constant.
For example
c= a-b;
in above example minus character (-) and = are the operator, and a, and b are the two
operands.

There are following types of expressions exist in C:

1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators

1. Arithmetic Operators:

C Arithmetic operators are used to perform mathematical calculations like addition,


subtraction, multiplication, division and modulus in C programs.

Arithmetic
Operators/Operation Example

+ (Addition) A+B

– (Subtraction) A-B

* (multiplication) A*B

/ (Division) A/B

% (Modulus) A%B

2. Assignment operators :

In C programs, values for the variables are assigned using assignment operators.
For example, if the value “10” is to be assigned for the variable “sum”, it can be assigned
as “sum = 10;”

a) There are 2 categories of assignment operators in C language. They are,


Simple assignment operator ( Example: = )
b) Compound assignment operators/ shorthand operators ( Example: +=, -=, *=, /=,
%=, &=, ^= )

Operators Example/Description

sum = 10;
= 10 is assigned to variable sum

sum += 10;
+= This is same as sum = sum + 10

sum -= 10;
-= This is same as sum = sum – 10

sum *= 10;
*= This is same as sum = sum * 10

sum /= 10;
/= This is same as sum = sum / 10

sum %= 10;
%= This is same as sum = sum % 10

sum&=10;
&= This is same as sum = sum & 10

sum ^= 10;
^= This is same as sum = sum ^ 10

3. Relational operators
Relational operators are used to find the relation between two variables. i.e. to
compare the values of two variables in a C program.

Operators Example/Description

> 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)

== x == y (x is equal to y)
!= x != y (x is not equal to y)

EXAMPLE PROGRAM FOR RELATIONAL OPERATORS IN C:


● In this program, relational operator (==) is used to compare 2 values whether they
are equal are not.
● If both values are equal, output is displayed as ” values are equal”. Else, output is
displayed as “values are not equal”.
● Note : double equal sign (==) should be used to compare 2 values. We should not
single equal sign (=).

#include<stdio.h>
int main()
{
m = 40, n =20;
if (m==n)
{
printf(“\n m and n are equal”);

}
else
{
printf(“m and n are not equal”);
}
}

Output:
m and n are not equal

4. Logical operators
These operators are used to perform logical operations on the given expressions.

● There are 3 logical operators in C language. They are, logical AND (&&), logical OR
(||) and logical NOT (!).

Operators Example/Description

&& (logical (x>5)&&(y<5)


AND) It returns true when both conditions are true

(x>=10)||(y>=10)
|| (logical OR) It returns true when at-least one of the condition is true

! (logical !((x>5)&&(y<5))
NOT) It reverses the state of the operand “((x>5) && (y<5))”
If “((x>5) && (y<5))” is true, logical NOT operator makes it
false

Example

#include <stdio.h>

int main()
{
int m=40,n=20;
int o=20,p=30;
if (m>n && m !=0)
{
printf("&& Operator : Both conditions are true\n");
}
if (o>p || p!=20)
{
printf("|| Operator : Only one condition is true\n");
}
if (!(m>n && m !=0))
{
printf("! Operator : Both conditions are true\n");
}
else
{
printf("! Operator : Both conditions are true.
But, status is inverted as false\n");
}
}

Output :

&& Operator : Both conditions are true


|| Operator : Only one condition is true
! Operator : Both conditions are true. But, status is inverted as false

5. Bit wise operators


These operators are used to perform bit operations. Decimal values are converted into
binary values which are the sequence of bits and bit wise operators work on these bits.

● Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise
NOT), ^ (XOR), << (left shift) and >> (right shift).
TRUTH TABLE FOR BIT WISE OPERATION & BIT WISE OPERATORS:
BELOW ARE THE BIT-WISE OPERATORS AND THEIR NAME IN C LANGUAGE.
1. & – Bitwise AND
2. | – Bitwise OR
3. ~ – Bitwise NOT
4. ^ – XOR
5. << – Left Shift
6. >> – Right Shift
Consider x=40 and y=80. Binary form of these values are given below.

x=00101000
y= 01010000

All bit wise operations for x and y are given below.


1. x&y = 00000000 (binary) = 0 (decimal)
2. x|y = 01111000 (binary) = 120 (decimal)
3. ~x = 11111111111111111111111111
11111111111111111111111111111111010111 = -41 (decimal)
4. x^y = 01111000 (binary) = 120 (decimal)
5. x << 1 = 01010000 (binary) = 80 (decimal)
6. x >> 1 = 00010100 (binary) = 20 (decimal)
NOTE:
● Bit wise NOT : Value of 40 in binary is 00000000000000000000000000000000
00000000000000000010100000000000. So, all 0’s are converted into 1’s in bit
wise NOT operation.
● Bit wise left shift and right shift : In left shift operation “x << 1 “, 1 means that the
bits will be left shifted by one place. If we use it as “x << 2 “, then, it means that the
bits will be left shifted by 2 places.
EXAMPLE PROGRAM FOR BIT WISE OPERATORS IN C:
In this example program, bit wise operations are performed as shown above and output
is displayed in decimal format.

#include <stdio.h>

int main()
{
int m = 40,n = 80,AND_opr,OR_opr,XOR_opr,NOT_opr ;
AND_opr = (m&n);
OR_opr = (m|n);
NOT_opr = (~m);
XOR_opr = (m^n);
printf("AND_opr value = %d\n",AND_opr );
printf("OR_opr value = %d\n",OR_opr );
printf("NOT_opr value = %d\n",NOT_opr );
printf("XOR_opr value = %d\n",XOR_opr );
printf("left_shift value = %d\n", m << 1);
printf("right_shift value = %d\n", m >> 1);
}

Output:

AND_opr value = 0
OR_opr value = 120
NOT_opr value = -41
XOR_opr value = 120
left_shift value = 80
right_shift value = 20

6. Conditional operators (ternary operators)


● Conditional operators return one value if condition is true and returns another
value is condition is false.
● This operator is also called as ternary operator.
Syntax : (Condition)? true_value: false_value;
Example : (A > 100) ? 0 : 1;
● In above example, if A is greater than 100, 0 is returned else 1 is returned. This is
equal to if else conditional statements.
EXAMPLE PROGRAM FOR CONDITIONAL/TERNARY OPERATORS IN C:
#include <stdio.h>

int main()
{
int x=1, y ;
y = ( x ==1 ? 2 : 0 ) ;
printf("x value is %d\n", x);
printf("y value is %d", y);
}

OUTPUT:
x value is 1
y value is 2

7. Increment/decrement operators
● Increment operators are used to increase the value of the variable by one and
decrement operators are used to decrease the value of the variable by one in C
programs.
● Syntax:
Increment operator: ++var_name; (or) var_name++;
Decrement operator: – -var_name; (or) var_name – -;
● Example:
Increment operator : ++ i ; i ++ ;
Decrement operator : – – i ; i – – ;
EXAMPLE PROGRAM FOR INCREMENT OPERATORS IN C:
In this program, value of “i” is incremented one by one from 1 up to 9 using “i++”
operator and output is displayed as “1 2 3 4 5 6 7 8 9”.
//Example for increment operators

#include <stdio.h>
int main()
{
int i=1;
while(i<10)
{
printf("%d ",i);
i++;
}
}

OUTPUT:
123456789
EXAMPLE PROGRAM FOR DECREMENT OPERATORS IN C:
In this program, value of “i” is decremented one by one from 20 up to 11 using “i–”
operator and output is displayed as “20 19 18 17 16 15 14 13 12 11”.
//Example for decrement operators

#include <stdio.h>
int main()
{
int i=20;
while(i>10)
{
printf("%d ",i);
i--;
}
}
OUTPUT:
20 19 18 17 16 15 14 13 12 11

DIFFERENCE BETWEEN PRE/POST INCREMENT & DECREMENT OPERATORS IN C:


Below table will explain the difference between pre/post increment and decrement
operators in C programming language.
Operator Operator/Description

Pre increment operator (+ value of i is incremented before assigning it to


+i) the variable i

Post increment operator (i+ value of i is incremented after assigning it to the


+) variable i

Pre decrement operator (-- value of i is decremented before assigning it to


i) the variable i

Post decrement operator value of i is decremented after assigning it to


(i--) variable i

Note : You may skip the examples if you are not aware of looping construct.
EXAMPLE PROGRAM FOR PRE – INCREMENT OPERATORS IN C:
//Example for increment operators

#include <stdio.h>
int main()
{
int i=0;
while(++i < 5 )
{
printf("%d ",i);
}
return 0;
}
OUTPUT:
1234
● Step 1 : In above program, value of “i” is incremented from 0 to 1 using pre-
increment operator.
● Step 2 : This incremented value “1” is compared with 5 in while expression.

● Step 3 : Then, this incremented value “1” is assigned to the variable “i”.
● Above 3 steps are continued until while expression becomes false and output is
displayed as “1 2 3 4”.

EXAMPLE PROGRAM FOR POST – INCREMENT OPERATORS IN C:


#include <stdio.h>
int main()
{
int i=0;
while(i++ < 5 )
{
printf("%d ",i);
}
return 0;
}
OUTPUT:
12345
● Step 1 : In this program, value of i “0” is compared with 5 in while expression.
● Step 2 : Then, value of “i” is incremented from 0 to 1 using post-increment operator.
● Step 3 : Then, this incremented value “1” is assigned to the variable “i”.
● Above 3 steps are continued until while expression becomes false and output is
displayed as “1 2 3 4 5”.

8. Special operators

Below are some of the special operators that the C programming language offers.

Operators Description

& This is used to get the address of the variable.


Example : &a will give address of a.
Note: & is also used for bitwise ‘AND’ operation

* This is used as pointer to a variable.


Example : * a where, * is pointer to the variable a.

Sizeof () This gives the size of the variable.


Example : size of (char) will give us 1.

2.5 Precedence of operators

Operator precedence determines the grouping of terms in an expression. This


affects how an expression is evaluated. Certain operators have higher
precedence than others; for example, the multiplication operator has higher
precedence than the addition operator.

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has


higher precedence than +, so it first gets multiplied with 3*2 and then adds into
7.

Here, operators with the highest precedence appear at the top of the table, those
with the lowest appear at the bottom. Within an expression, higher precedence
operators will be evaluated first.

Category Operator Associativity


Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & Right to left
sizeof
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> 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
Try the following example to understand the operator precedence available in C programming
language:

#include <stdio.h>

main()

int a =
// ( 30 * 15 ) /
printf("Value of (a + b) * c / d is : %d\n", e );

e = ((a + b) * c) / d; // (30 * 15 ) /
printf("Value of ((a + b) * c) / d is : %d\n" , e );

e = a + (b * c) / // 20 +
printf("Value of a + (b * c) / d is : %d\n" , e
);
}

When you compile and execute the above program, it produces the following result:

Value of (a + b) * c / d is : 90

Value of ((a + b) * c) / d is : 90

Value of (a + b) * (c / d) is : 90
2.6 type conversions/ Casting

Type casting is a way to convert a variable from one data type to another data type. For
example, if you want to store a long value into a simple integer then you can type cast long
to int. You can convert values from one type to another explicitly using the cast operator
as follows:

(type_name) expression

Consider the following example where the cast operator causes the division of one integer
variable by another to be performed as a floating-point operation:

#include <stdio.h>

main()

int sum = 17, count = 5; double mean;

mean = (double) sum / count; printf("Value of mean : %f\


n", mean );

When the above code is compiled and executed, it produces the following result:

Value of mean : 3.400000

It should be noted here that the cast operator has precedence over division, so the value of
sum is first converted to type double and finally it gets divided by count yielding a double
value.

Type conversions can be implicit which is performed by the compiler automatically, or it


can be specified explicitly through the use of the cast operator. It is considered good
programming practice to use the cast operator whenever type conversions are necessary.
Integer Promotion

The Integer promotion is the process by which values of integer type "smaller" than int or
unsigned int are converted either to int or unsigned int. Consider an example of adding a character
in an int:

#include <stdio.h>

main()

int i = 17;

char c = 'c'; /* ascii value is 99 */ int sum;

When the above code is compiled and executed, it produces the following result:

Value of sum : 116

Here, value of sum is coming as 116 because compiler is doing integer promotion and converting the
value of 'c' to ascii before performing actual addition operation.

Usual Arithmetic Conversion

The usual arithmetic conversions are implicitly performed to cast their values in a common type.
Compiler first performs integer promotion, if operands still have different types then they are
converted to the type that appears highest in the following hierarchy:
The usual arithmetic conversions
are not performed for the
assignment operators, nor for the
logical operators && and ||. Let us
take following example to
understand the concept:

#include <stdio.h>

main()

int i = 17;

char c = 'c'; /* ascii value is 99 */ float sum;

sum = i + c;

printf("Value of sum : %f\n", sum );

When the above code is compiled and


executed, it produces the following result:

Value of sum : 116.000000

Here, it is simple to understand that first c


gets converted to integer but because final
value is double, so usual arithmetic
conversion applies and compiler convert i
and c into float and add them yielding a
float result.
2.6 scanf and printf functions. (Input and Output)

When we are saying Input that means to feed some data into program. This can be
given in the form of file or from command line. C programming language provides a
set of built-in functions to read given input and feed it to the program as per
requirement.

When we are saying Output that means to display some data on screen, printer or in
any file. C programming language provides a set of built-in functions to output the
data on the computer screen as well as you can save that data in text or binary files.

The Standard Files

C programming language treats all the devices as files. So devices such as the display
are addressed in the same way as files and following three file are automatically
opened when a program executes to provide access to the keyboard and screen.

Standard File Pointer Device


File

Standard stdin Keyboard


input

Standard stdout Screen


output

Standard stderr Your screen


error

The file points are the means to access the file for reading and writing purpose. This
section will explain you how to read values from the screen and how to print the
result on the screen.

The getchar() & putchar() functions

The int getchar(void) function reads the next available character from the screen and
returns it as an integer. This function reads only single character at a time. You can
use this method in the loop in case you want to read more than one characters from
the screen.
The int putchar(int c) function puts the passed character on the screen and returns the
same character. This function puts only single character at a time. You can use this
method

in the loop in case you want to display more than one character on the screen. Check
the following example:

#include <stdio.h>

int main( )

int c;

printf( "Enter a value :"); c =


getchar( );

printf( "\nYou entered: ");

putchar(c);

return 0;

When the above code is compiled and executed, it waits for you to input some text when you
enter a text and press enter then program proceeds and reads only a single character and displays
it as follows:

$./a.out

Enter a value : this is test

The gets() & puts() functions


The char *gets(char *s) function reads a line from stdin into the buffer pointed to by s
until either a terminating newline or EOF.

#include <stdio.h>

int main( )

char str[100];

printf( "Enter a value :"); str = gets( str );

printf( "\nYou entered: "); puts( str );

return 0;
The int puts(const char *s) function writes the string s and a trailing newline to stdout.

When the above code is compiled and executed, it waits for you to input some text
when you enter a text and press enter then program proceeds and reads the complete
line till end and displays it as follows:

$./a.out

Enter a value : this is test

You entered: This is test

The scanf() and printf() functions

The int scanf(const char *format, ...) function reads input from the standard input
stream stdin and scans that input according to format provided.
The int printf(const char *format, ...) function writes output to the standard output
stream stdout and produces output according to a format provided.
The format can be a simple constant string, but you can specify %s, %d, %c, %f, etc.,
to print or read strings, integer, character or float respectively. There are many other
formatting options available which can be used based on requirements. For a
complete detail you can refer to a man page for these function. For now let us proceed
with a simple example which makes things clear:

#include <stdio.h>

int main( )

char str[100]; int


i;

printf( "Enter a value :");

scanf("%s %d", str, &i);

printf( "\nYou entered: %s, %d ", str, i);

return 0;
When the above code is compiled and executed, it waits for you to input some text
when you enter a text and press enter then program proceeds and reads the input and
displays it as follows:

$./a.out

Enter a value : seven 7

Here, it should be noted that scanf() expect input in the same format as you provided
%s and %d, which means you have to provide valid input like "string integer", if you
provide "string string" or "integer integer" then it will be assumed as wrong input.
Second, while reading a string scanf() stops reading as soon as it encounters a space
so "this is test" are three strings for scanf().

Case Study: Exchanging the values of two variables, summation of a set of numbers.

You might also like