0% found this document useful (0 votes)
4 views31 pages

Porcedraul Programming Unit-1B_Intro to C Programming

CS engineering

Uploaded by

parivnems
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
4 views31 pages

Porcedraul Programming Unit-1B_Intro to C Programming

CS engineering

Uploaded by

parivnems
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 31

UNIT-2 INTRODUCTION TO C PROGRAMMING

INTRODUCTION TO C PROGRAMMING

‘C’ is high level language and is the upgraded version of another language (Basic Combined
Program Language). C language was designed at Bell laboratories in the early 1970’s by Dennis Ritchie.
C being popular in the modern computer world can be used in Mathematical Scientific, Engineering
andCommercial applications

The most popular Operating system UNIX is written in C language. This language also has the
features of low level languages and hence called as “SystemProgramming Language”

Features of C language
• Highly Portable: C programs are machine-independent which means that the fraction of a
code created in C program can run on various machines with none or some machine-specific
changes. Hence, it provides the functionality of using a single code on multiple systems
depending on the requirement.
• Robust: C provides a lot of inbuilt functions and operators that can be used to write any
complex program.
• Structured programming language: C is a structured programming language because a
program in c language can be divided into small logical functions, modules or structures. So, it
is easy to understand and modify. Functions also provide code reusability. Proper collection of
these functions or modules would make a complete program. Modular structure makes program
to debug, test and maintain easily.
• Efficient and Fast: C is a compiler-based program that makes the compilation and execution
of codes faster.
• Procedural Language: C is a procedural programming language, which means it follows a
procedure of steps written in it called functions.
• Simple: C is a simple programming language, since it provides structured approach, rich set of
library functions, data types etc.
• Flexibility: C is a versatile language that can be used for a wide range of applications, from
system programming and embedded systems to desktop applications and game development.
• Ability to extend itself: If a program is already written in it then some more features and
operations can be added to it.
• General purpose programming language: C can be used to implement any kind of
applications such as math’s, graphics and business oriented applications.

PROBLEM SOLVING USING C 1


UNIT-2 INTRODUCTION TO C PROGRAMMING

Structure of a ‘C’ Program


The basic structure of a C program is divided into six sections which make it easy to read,
modify, document, and understand in a particular format. C program must follow this structure in
order to successfully compile and execute. Debugging is easier in a well-structured C program.

fig: structure of c program

DOCUMENTATION SECTION:
Document the use of logic or reasons in your program. It can be used to write the program's
objective, developer and logic details. The documentation is done in C language with comments.
Comments: The lines beginning with /* and ending with */ are known as comment lines.
• Single line comment (//)
• Multi-line comment (/* */)
o Comments are used to enhance readability and understanding of a program.
o Comment lines are not executable statements.
o Comments can be written anywhere beginning, middle or end of a line but never in middle of a
word.
Example:
// description, name of the program, programmer name, date, time etc.
//To find sum of two numbers
or
/*
* Description, name of the program, programmer name, date, time etc.
*/

PROBLEM SOLVING USING C 2


UNIT-2 INTRODUCTION TO C PROGRAMMING
LINKING SECTION
It provides instructions to the compiler to link functions from the system library. It provides
instructions to the compiler to link functions in your program to the header files specified.
Header files: Header file is a text file that contains pieces of code written in the c programming
language. Header files help us to access other’s improved code into our code. A copy of these
multiple files is inserted into our program before the process of compilation.
Header files end with .h extension.
It is inserted in program by coding the #include preprocessor directive.
e.g. #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
DEFINITION SECTION
It is used to declare some constants and assign them some value. Preprocessors are the
programs that process our source code before the process of compilation. There are multiple steps
which are involved in the writing and execution of the program. Preprocessor directives start with
the ‘#’ symbol. The #define preprocessor is used to create a constant throughout the program.
Whenever this name is encountered by the compiler, it is replaced by the actual piece of defined
code.
Ex.: #define MAX 25
Here #define is a compiler directive which tells the compiler whenever MAX is found in the
program replace it with 25.
Ex.: #define PI 3.14
Here #define is a compiler directive which tells the compiler whenever PI is found in the
program replace it with 3.14.
GLOBAL DECLARATION SECTION
The global declaration section contains global variables, function declaration, and static
variables. Variables and functions which are declared in this scope can be used anywhere in the
program.
Here the variables which are used throughout the program (including main and other
functions) are declared so as to make them global (i.e accessible to all parts of program).
e.g. int i; (before main())

PROBLEM SOLVING USING C 3


UNIT-2 INTRODUCTION TO C PROGRAMMING
MAIN FUNCTION SECTION
main() is a special function used by the c system to tell the computer where the program
starts. Every program in C begins executing at the main(). No C program is executed without main()
function. There must be one and only one main() function in every C program. It should be written in
lowercase letters and should not be terminated by a semicolon. It calls other Library functions user defined
functions.
There are many forms of main statements.
• main()
• int main()
• void main()
• main ( void)
• void main(void)
• int main(void)
void main() tells the compiler that the program will not return any value. The int main() tells the
compiler that the program will return an integer value.
main() function section
{
Declaration Part
Executable Part
}
Every C program uses a pair of curly braces ({ , }). The left brace indicates beginning of
main() function. On the other hand, the right brace indicates end of the main() function. Program
execution ends near closed brace.
All statements between these two braces form the function body. The function body
contains a set of instructions to perform the given task. All statements in declaration and executable
parts end with a semicolon (;).

Declaration part: It is part of C program where all the variables, arrays, functions etc., used in the
C program are declared and may be initialized with their basic data types.
Executable Part / Statements: These are instructions to the specific operations. They may be
input-output statements, arithmetic statements, control statements and any other statements.
Comments are also included in statements.
Example:

PROBLEM SOLVING USING C 4


UNIT-2 INTRODUCTION TO C PROGRAMMING

void main() int main( )


User-defined functions
These are subprograms. Generally, a subprogram is a function, and they contain a set of
statements to perform a specific task. These are written by the user. Hence the name is user-defined
functions. They may be written before or after the main() function.
Example for simple structure of c program

Output:

Example for structure of c program

PROBLEM SOLVING USING C 5


UNIT-2 INTRODUCTION TO C PROGRAMMING

Program Development Steps

Creating the program


To create a program use some IDE open source code file under which a new main file is
present.
Open file with name main.c to edit the source code.
Source code is a file with c programming instructions in a high level language.
The file name can be letters, digits or special characters followed by a dot and a letter c.
Ex: first.c
Program.c

PROBLEM SOLVING USING C 6


UNIT-2 INTRODUCTION TO C PROGRAMMING

Creating the program


To create a program use some IDE open source code file under which a new main file is
present.
Open file with name main.c to edit the source code. Source code is a file with c
programming instructions in a high level language. The file name can be letters, digits or special
characters followed by a dot and a letter c.
Ex: first.c
Program.c
Compiling the program
The program created using C programming is written using high level language. But
computer cannot understand high level language. It can understand only low-level language. So
program should be converted into a low- level language. This conversion is performed using either
compiler or interpreter. The compiled code is called object code.

PROBLEM SOLVING USING C 7


UNIT-2 INTRODUCTION TO C PROGRAMMING

All programs written in C uses library functions. These library functions are pre-compiled
pre
and the object code of these library files is stored in .lib extension.
Compiler:: compiler is a program that converts high level language instructions into low level
language instructions on one go.. It performs:
• Verifies the program errors, if errors are found, it re
returns
turns a list of errors otherwise.
• It converts the complete code into the low level language.
Compiled programs run faster as there is no translation during runtime. A compiler displays every
error and warning while compiling. So program cannot run until all errors are fixed.
• Example:: gcc (GNU C Compiler)
Interpreter:
Reads High Level Language programs line by line and executes their equivalent operational
codes. The process of interpretation makes the program execution slower
slower.. It generates errors in
every single line one by one. An interpreter reads every statement, then display the errors if any.
User must resolve these errors in order to interpret the next line.
• Example:
– Java Virtual Machine: Works on object code generated by Java compiler.
compiler
Linking the program
Linking is the process of putting together other program files and functions that are required
by the program. Linking is done by linker. The linker is a proc
process
ess that accepts object files and
library files as input to produce the final executable program.

PROBLEM SOLVING USING C 8


UNIT-2 INTRODUCTION TO C PROGRAMMING
The compiled code is called object code. The compiled and linked code is called executable object
code.

Executing the program: Execution is a simple task.


 Once
nce the executable object code is created then instructions execution takes place.
 During this execution the program may request for some data to be entered through the
keyboard.
 Sometimes the program does not produce the desired result if something is wrong
wro with the
program logic or data.
 Then it would be necessary to correct the source program or the data.
 In case the source program is modified, the entire process of compiling, linking and executing
the program should be repeated.
 After execution the output
ut of program is displayed on the screen.

Errors

 Errors are the problems or the faults that occur in the program.
 Programming errors are also known as the bugs or faults.
 The process of removing these bugs is known as debugging.
 These errors are detected
ed either during the time of compilation or execution.
 Thus, the errors must be removed from the program for the successful execution of the
program.
There are mainly five types of errors exist in C programming:
o Syntax error
o Linker error
o Run-time error
o Logical error
o Semantic error

PROBLEM SOLVING USING C 9


UNIT-2 INTRODUCTION TO C PROGRAMMING
Syntax error
 Syntax errors are also known as the compilation errors as they occurred at the compilation
time
 These errors are mainly occurred due to the mistakes while typing the code's syntax
 Syntax errors occur when a programmer does not follow the set of rules defined for the
syntax of C language.
 These errors can be easily identified and rectified by programmers.
 The most commonly occurring syntax errors in C language are:
 Missing semi-colon (;)
 Missing parenthesis ({})
 Assigning value to a variable without declaring it.
Example

Runtime Error
 Errors that occur during the execution (or running) of a program are called Run time Errors.
 These errors occur after the program has been compiled successfully.
 When a program is running, and it is not able to perform any particular operation, it means
that we have encountered a run time error.
 Runtime errors are difficult to identify because the compiler cannot detect these errors.
 Some of the most common run time errors are:
o All mathematically incorrect operations
 number not divisible by zero
 calculating the square root of -1
o Memory related issues
 Array index out of bounds
 string index out of bounds
o Infinite loop
o Wrong input by the user

PROBLEM SOLVING USING C 10


UNIT-2 INTRODUCTION TO C PROGRAMMING

Logical Error
 The logical error is an error that leads to an undesired output.
 These errors produce the incorrect output, but they are error-free.
 The output generated is different from the expected one after the compilation and execution
of a program.
 Some of the most common Logical errors are:
o Semicolon after a loop.
o Incorrect use of relational and logical operators
o Misunderstanding the order of precedence

Semantic Error
 Errors that occur because the compiler is unable to understand the written code are called
Semantic Errors.
 A semantic error will be generated if the code makes no sense to the compiler, even though
it is syntactically correct.

PROBLEM SOLVING USING C 11


UNIT-2 INTRODUCTION TO C PROGRAMMING
 This is similar to grammatical errors.
 Semantic errors signify the incorrect implementation of a program by considering the
meaning of the program.
 Some of the most common Semantic errors are:
o un-initialized variables,
o Type compatibility
o Errors in expressions

Linker Error
 Linker is a program that takes the object files generated by the compiler and combines them
into a single executable file.
 Linker errors are mainly generated when the executable file of the program is not created
even though the code gets compiled successfully.
 We can run into a linked error if we have
o Imported an incorrect header file in the code.
o Wrong function declaration. Ex: main() is written as Main()

PROBLEM SOLVING USING C 12


UNIT-2 INTRODUCTION TO C PROGRAMMING

Conclusion
 Errors are the problems or the faults that occur in the program.
 There are 5 different types of errors in C programming language: Syntax error, Runtime
error, Logical error, Semantic error, and Linker error.
 Syntax errors, linker errors, and semantic errors can be identified by the compiler during
compilation. Logical errors and run time errors are encountered after the program is
compiled and executed.
 Syntax errors, linker errors, and semantic errors are relatively easy to identify and rectify
compared to the logical and run time errors. This is so because the compiler generates these
3 (syntax, linker, semantic) errors during compilation itself, while the other 2 (Logical and
run time) errors are generated during or after the execution.

Character set
• Alphabets
 Lower case letters – a to z
 Upper case letters – A to Z
• Digits
 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
• Special characters
 ~ % | @ + < _ - > ^ # = & $ / ( * \ ) ′ : [ “ ; ] ! , { ? . }
C Tokens
• C tokens : the smallest individual units

 Keyword – float, while, for, int,….

 Identifier – main( ) , amount, sum, …

 Constants – -13.5, 500, …

 Strings – “ABC”, “MCA”, …

 Operators – + - * % …

 Special Symbols – [ ] { }…

PROBLEM SOLVING USING C 13


UNIT-2 INTRODUCTION TO C PROGRAMMING
Keywords: C word is classified as either a keyword or an identifier.
• Fixed meaning and cannot be changed.
• Reserved words
• Cannot be used as a variable or function name.
• Basic building blocks
• All keywords should be in Lowercase.
Keywords used in C

Identifiers: It refer to the names of variables, functions and arrays


• Name given to a function or variable memory location
• An identifier is a series of characters consisting of letters, digits and underscores “_”
• Should start with a letter or underscore but not with digit.
• Can be any length. Generally Keep identifiers 31 characters or less for portability and fewer
problems.
Identifier CAN:
– contain a number elsewhere h2o
– be of mixed cases Xsquared
– contain or begin with an underscore _height_
Identifier CANNOT :
– start with a number 2i
– contain any arithmetic operators r*s+t
– contain any other punctuation marks #@x%£!!a
– be a C keyword struct
– contain a space my var
Constants:
Constants are fixed values. Does not changes during execution of program.
1. Numeric Constants
a. Integer constant
b. Real constant
2. Character constants

PROBLEM SOLVING USING C 14


UNIT-2 INTRODUCTION TO C PROGRAMMING
a. Single character constant
b. String constant
c. Backslash or Escape character constant

Integer constants
An integer constant refers to a sequence of digits. There are three types of integers
 Decimal Integer: Consists a set of digits 0 to 9
 Octal Integer :Combination of digits 0 to 7
 Hexadecimal Integer: Combination of digits 0 to 15 where A to F represents the numbers 10
to 15 respectively.
Real constant:

The numbers containing fractional part are called real or floating point constants.

Example: To represent quantities that vary continuously such as distance, height, prices etc. like
17.45, -.72, 12.

Comma is not allowed. Whitespace is not permitted. $symbol is not permitted

Single character constant

A single character constant contains a single character enclosed within a pair of single quote
marks. Every character constant has an equivalent integer value know as ASCII Value.

Example: ‘5’, ‘x’, ‘ ‘

The range of ASCII values for uppercase letters A-Z is 65-90

The range of ASCII values for lowercase letters a-z is 97-122

The range of ASCII values for digits [0 – 9] is [48 – 57]

String constant:
A string constant is a sequence of character enclosed in double quotes. The character may
be letters, numbers, special characters and blank space
Example: “Hello”, “1997”, “welcome all’, “5+3”.

Escape character – backslash \

• When encountering a backslash in a string, the compiler looks ahead at the next character
and combines it with \ to form escape sequence

PROBLEM SOLVING USING C 15


UNIT-2 INTRODUCTION TO C PROGRAMMING

Variables
These are the names of the objects, whose values can be changed during the program
execution. Variables are named with description that transmits the value it holds.
 A variable is a data name that may be used to store a data value.
 A variable may take different values at different times during execution.
 The variable name can be chosen by the programmer in a meaningful way.
Rules to name a variable
 Should start with a letter or underscore.
 Can be any length. Standard length is 31 characters.
 Lowercase and uppercase are significant.
 It should not be a C keyword.
 White space is not allowed.
Declaration of variables
Syntax type Variable list
int i, j i, j are declared as integers
float salary salary is declared ad floating point variable
Char sex sex is declared as character variable

PROBLEM SOLVING USING C 16


UNIT-2 INTRODUCTION TO C PROGRAMMING
DATA TYPES
Primary data types: There are five fundamental data types
 Integer(int)
 Character(char)
 Floating point(float)
 Double precision floating point(double)
 Void
Compiler is free to choose a suitable size depending on the hardware.

Range Format
Data Type Size (bits) Size (bytes)
Specifier

short int 8 1 -27 to +27-1 %hd

int 16 2 -215 to +215-1 %d

long int 32 4 -231 to +231-1 %ld

long long int 64 8 -263 to 263-1 %lld

unsigned short 0 to 28
8 1 %hu
int

unsigned int 16 2 0 to 216 %u

PROBLEM SOLVING USING C 17


UNIT-2 INTRODUCTION TO C PROGRAMMING

unsigned long 32 0 to 232 %lu


4
int

unsigned long 64
8 0 to 264 %llu
long int

signed char or 8 -27 to +27-1 %c


1
char

unsigned char 8 1 0 to 28 %c

float 32 3.4E-38 to %f
4
3.4E+38

double 64 1.7E-308 to %lf


8
1.7E+308

long double 80 3.4E-4932 to %Lf


10
1.1E+4932

Character
Any character of the ASCII character set can be considered as a character data types and its
maximum size can be 1 byte or 8 bits long. ‘Char’ is the keyword used to represent character data
type in C. Char - a single byte size, capable of holding one character.
Syntax:
char var_name;
Integer data
The keyword ‘int’ stands for the integer data type in C and its size is either 16 or 32 bits.
The integer data type can again be classified as
o Long int - long integer with more digits
o Int- an Integer with the natural size of the host machine
o Short int - short integer with fewer digits.
o Unsigned int - Unsigned integer
o Unsigned short int – Unsigned short integer
o Unsigned long int – Unsigned long integer
Syntax:
int var_name;

PROBLEM SOLVING USING C 18


UNIT-2 INTRODUCTION TO C PROGRAMMING
Floating point data: - The numbers which are stored in floating point representation with
mantissa and exponent are called floating point (real) numbers. These numbers can be declared as
‘float’ in C.
float – Single – precision floating point number value.
Syntax:
float var_name;

Double data: - Double is a keyword in C to represent double precision floating point numbers. It
can easily accommodate about 16 to 17 digits after or before a decimal point.
double - Double – precision floating point number value.
Syntax:
double var_name;

Void
The void data type always represents an empty set of values. It is used to specify the type of
a function. The type of function is said to be void when it doesn’t return any value to the calling
function.
Syntax:
void main()

Operator
An Operator is a symbol that operates on a certain data type. The data items that operators
act upon are called operands. Some operators require two operands, some operators act upon only
one operand. In C, operators can be classified into various categories based on their utility and
action.
1. Arithmetic Operators
2. Relational Operators
3. Logical Operator
4. Assignment Operator
5. Increment & Decrement Operator
6. Conditional Operator
7. Special Operator
1. Arithmetic Operators
The Arithmetic operators perform arithmetic operations. The Arithmetic operators can operate on
any built in data type. Some of arithmetic operators are

PROBLEM SOLVING USING C 19


UNIT-2 INTRODUCTION TO C PROGRAMMING
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo division
Examples :
A+B
A-B

2. Relational Operators
Relational Operators are used to compare arithmetic, logical and character expressions. The
Relational Operators compare their left hand side expression with their right hand side expression.
That results to an integer value. If the Expression is false it evaluate to “zero”(0) if the expression is
true it evaluate to “one”
Operator Meaning
< Less than
> Greater than
<= Less than or Equal to
>= Greater than or Equal to
== Equal to
!= Not Equal to

PROBLEM SOLVING USING C 20


UNIT-2 INTRODUCTION TO C PROGRAMMING
The Relational Operators are represented in the following manner:
Expression-1 Relational Operator Expression-2
The Expression-1 will be compared with Expression -2 and depending on the relation the result will
be either “TRUE” OR “FALSE”.
Examples:
 (5 <= 10) ———————— 1
 (-35 > 10) ——————— 0
 (X < 10) ———————— 1 ( if value of x is less than 10) Other wise 0
 (a + b) = = ( c + d ) ————1 (if sum of a and b is equal to sum of c, d) Other wise 0

3. Logical Operators
A logical operator is used to evaluate logical and relational expressions. The logical operators act
upon operands that are themselves logical expressions. There are three logical operators.
Operators Expression
&& Logical AND
|| Logical OR
! Logical NOT
Logical And (&&): A compound Expression is true when two expression when two expressions
are true. The && is used in the following manner:
Exp1 && Exp2
The result of a logical AND operation will be true only if both operands are true.
The results of logical operators are:
Exp1 Operator Exp2 Result
True && True True

PROBLEM SOLVING USING C 21


UNIT-2 INTRODUCTION TO C PROGRAMMING
True && False False
False && False False
False && True False
Example: Consider a = 5; b = 10; c = 15;
Exp1 Op. Exp2 Result
1. ( a< b ) && ( b < c ) => True
2. ( a> b ) && ( b < c ) => False
3. ( a< b ) && ( b > c ) => False
4. ( a> b ) && ( b > c ) => False

Logical OR: A compound expression is false when all expressions are false otherwise the
compound expression is true. It evaluates to true if either Exp1 Or Exp2 is true. The operator “||” is
used in following manner:
The truth table of “OR” is Exp1 || Exp2
Exp1 Operator Exp2 Result
True || True True
True || False True
False || True True
False || False False
Example: a = 5; b = 10; c = 15;
Exp1 Op. Exp2 Result
1. ( a< b ) || ( b < c ) => True
2. ( a> b ) || ( b < c ) => True
3. ( a< b ) || ( b > c ) => True
4. ( a> b ) || ( b > c ) => False

Logical NOT: The NOT ( ! ) operator takes single expression and evaluates to true(1) if the
expression is false (0) or it evaluates to false (0) if expression is true (1). The general form of the
expression is: !( Relational Expression )
The truth table of NOT :
Operator. Exp1 Result
! True False
! False True

PROBLEM SOLVING USING C 22


UNIT-2 INTRODUCTION TO C PROGRAMMING
Example: Consider a = 5; b = 10; c = 15
1. !( a< b ) False
2. !( a> b ) True
4. Assignment Operator
An assignment operator is used to assign a value to a variable. The most commonly used
assignment operator is =. The general format for assignment operator is :
<Identifier> = < expression >
Where identifier represents a variable and expression represents a constant, a variable or a Complex
expression.
If the two operands in an assignment expression are of different data types, then the value of the
expression on the right will automatically be converted to the type of the identifier on the left.
Example: Suppose that I is an Integer type Variable then
1. I = 3.3 3 ( Value of I )
2. I = 3.9 3 ( Value of I )
3. I = 5.74 5 ( Value of I )
Multiple assignments
< identifier-1 > = < identifier-2 > = - - - = < identifier-n > = <exp>;
Example: a,b,c are integers; j is float variable
1. a = b = c = 3;
2. a = j = 5.6; then a = 5 and j value will be 5.6
C contains the following five additional assignment operators called shorthand operator.
 +=
 -=
 +=
 *=
 /=
The assignment expression is: - Exp1 < Operator> Exp-2
Ex: Consider I = 10
Expression Equivalent to Final Value of ‘I’
I+=5 I=I+5 15
I-=5 I=I–5 10
I*=5 I=I*5 50
I/=5 I=I/5 10

PROBLEM SOLVING USING C 23


UNIT-2 INTRODUCTION TO C PROGRAMMING

5. Increment & Decrement Operator

The increment/decrement operator act upon a Single operand and produce a new value is
also called as “unary operator”. The increment operator ++ adds 1 to the operand and the
Decrement operator – subtracts 1 from the operand.
Syntax: < operator > < variable name > ;
The ++ or – operator can be used in the two ways.
Example:
Pre-increment ++ A; (or) Post increment A++
Pre-Decrement —A; (or) Post decrement A—
Pre-increment ++ A: Immediately increments the value of A by 1.
Post increment A ++: The value of the A will be increment by 1 after it is utilized.
Example 1: Suppose A = 5 ;
Statements Output
printf ( “A value is %d”, A ); a value is 5
printf ( “A value is %d”, ++ A ); a value is 6
printf ( “A value is %d “, A) ; a value is 6
Example 2: Suppose : A = 5 ;
Statements Output
printf (“A value is %d “, A); A value is 5

PROBLEM SOLVING USING C 24


UNIT-2 INTRODUCTION TO C PROGRAMMING
printf (“A value is %d “, A++); A value is 5
printf (“A value is %d “,A); A value is 6

6. Conditional operator (or) Ternary operator (? :)


It is called ternary because it uses three expressions. The ternary operator acts like If- Else
construction.
Syntax :( <Exp –1 > ? <Exp-2> : <Exp-3> );
Expression-1 is evaluated first. If Exp-1 is true then Exp-2 is evaluated otherwise Exp-3 will be
evaluated.
Example:
i. Consider a = 5 ; b = 3;
( a> b ? printf (“a is larger”) : printf (“b is larger”));
Output is : a is larger
ii. Consider a = 3; b = 3;
(a> b ? printf (“a is larger”) : printf (“b is larger”));
Output is :b is larger

7. Special Operators
i. Comma Operator:
A set of expressions separated by using commas is a valid construction in c language.
Example: Consider int i, j;
i= ( j = 3, j + 2 ) ;
The first expression is j = 3 and second is j + 2. These expressions are evaluated from left
to right. From the above example I = 5.
ii. Size of operator: The operator size operator gives the size of the data type or variable in
terms of bytes occupied in the memory. This operator allows a determination of the no of
bytes allocated to various Data items
Example : int i; float x; double d; char c;
printf (“integer : %d\n”, sizeof(i)); OUTPUT integer : 2
printf (“float : %d\n”, sizeof(i)); OUTPUT float : 4
printf (“double : %d\n”, sizeof(i)); OUTPUT double : 8
printf (“char : %d\n”,sizeof(i)); OUTPUT character : 1

Expressions

PROBLEM SOLVING USING C 25


UNIT-2 INTRODUCTION TO C PROGRAMMING
An expression can be defined as collection of data object and operators that can be
evaluated to lead a single new data object. A data object is a constant, variable or another data
object.
Example :
a+b
x + y + 6.0
3.14 * r * r
( a + b ) * ( a – b)
The above expressions are called as arithmetic expressions because the data objects (constants and
variables) are connected using arithmetic operators.
Evaluation Procedure: The evaluation of arithmetic expressions is as per the hierarchy rules
governed by the C compiler. The precedence or hierarchy rules for arithmetic expressions are
 The expression is scanned from left to right.
 While scanning the expression, the evaluation preference for the operators are
*, /, % - evaluated first
+, - - evaluated next
 To overcome the above precedence rules, user has to make use of parenthesis. If parenthesis
is used, the expression/ expressions with in parenthesis are evaluated first as per the above
hierarchy.
Example:
a % b (a divided by b)
5 % 2 ==1.
Precedence of Operators in C
The below table describes the precedence order and associativity of operators in C. The
precedence of the operator decreases from top to bottom.

Precedence Operator Description Associativity

() Parentheses (function call) left-to-right

[] Brackets (array subscript) left-to-right


1
. Member selection via object name left-to-right

-> Member selection via a pointer left-to-right

PROBLEM SOLVING USING C 26


UNIT-2 INTRODUCTION TO C PROGRAMMING

a++/a– Postfix increment/decrement (a is a variable) left-to-right

++a/–a Prefix increment/decrement (a is a variable) right-to-left

+/- Unary plus/minus right-to-left

!~ Logical negation/bitwise complement right-to-left

2 (type) Cast (convert value to temporary value of type) right-to-left

* Dereference right-to-left

& Address (of operand) right-to-left

sizeof Determine size in bytes on this implementation right-to-left

3 *,/,% Multiplication/division/modulus left-to-right

4 +/- Addition/subtraction left-to-right

5 << , >> Bitwise shift left, Bitwise shift right left-to-right

< , <= Relational less than/less than or equal to left-to-right


6
> , >= Relational greater than/greater than or equal to left-to-right

7 == , != Relational is equal to/is not equal to left-to-right

8 & Bitwise AND left-to-right

9 ^ Bitwise exclusive OR left-to-right

10 | Bitwise inclusive OR left-to-right

11 && Logical AND left-to-right

12 || Logical OR left-to-right

PROBLEM SOLVING USING C 27


UNIT-2 INTRODUCTION TO C PROGRAMMING

13 ?: Ternary conditional right-to-left

= Assignment right-to-left

+= , -= Addition/subtraction assignment right-to-left

*= , /= Multiplication/division assignment right-to-left


14
%= , &= Modulus/bitwise AND assignment right-to-left

^= , |= Bitwise exclusive/inclusive OR assignment right-to-left

<>= Bitwise shift left/right assignment right-to-left

15 , expression separator left-to-right

Type Conversion
Type conversion in C is the process of converting one data type to another. The type
conversion is only performed to those data types where conversion is possible. Type conversion is
performed by a compiler. In type conversion, the destination data type can’t be smaller than the
source data type. Type conversion is done at compile time and it is also called widening conversion
because the destination data type can’t be smaller than the source data type.
There are two types of Conversion
1. Implicit Type Conversion
2. Explicit Type Conversion

1. Implicit Type Conversion: Also known as ‘automatic type conversion’.

 Implicit conversion is done automatically by the compiler, without any external trigger from
the user.
 Generally takes place when in an expression more than one data type is present. In such
conditions type conversion (type promotion) takes place to avoid loss of data.
 All the data types of the variables are upgraded to the data type of the variable with the largest
data type.

PROBLEM SOLVING USING C 28


UNIT-2 INTRODUCTION TO C PROGRAMMING
bool -> char -> short int -> int -> unsigned int -> long -> unsigned -> long long -> float ->
double -> long double

 It is possible for implicit conversions to lose information, signs can be lost (when signed is
implicitly converted to unsigned), and overflow can occur (when long is implicitly converted to
float).
Example: Implicit type conversion

The compiler automatically converts the int value 9 to a float value of 9.000000.

2. Explicit Type Conversion

Explicit Type Conversion is also called type casting and it is user-defined. Explicit
conversion is done manually by placing the type in parentheses () in front of the value.
Consider the following example

The result is 2.00000 but the expected output is 2.5. This is because 5 and 2 are still integers
in the division so result is 2.00000. In this case, integer values need to be manually converted to
floating-point values. This is known as Explicit Type Conversion.

PROBLEM SOLVING USING C 29


UNIT-2 INTRODUCTION TO C PROGRAMMING
Syntax: (type) expression
type indicated the data type to which the final result is converted.

Example 2 Explicit Type Conversion:

Formatted input and output functions


An input/output function can be accessed from anywhere within a program simply by
writing the function name followed by a list of arguments enclosed in parentheses. The arguments
represent data items that are sent to the function.
Formatted Input Statements: scanf( )
Formatted Output Statements: printf( )
scanf():
Scanf() function can be used input the data into the memory from the standard input device.
This function can be used to enter any combination of numerical Values, single characters and
strings. The function returns number of data items.
Syntax:- scanf (“control strings”, &arg1,&arg2,——&argn);
Where control string refers to a string containing certain required formatting information
and arg1, arg2, ——,argn are arguments that represent the individual input data items.
Example: scanf(“%d %f”, &num, &marks);
%d, %f are conversion characters. The conversion characters indicate the type of the corresponding
data. Commonly used conversion characters from data input.
Conversion Characters Characters Meaning
%c data item is a single character.
%d data item is a decimal integer.
%f data item is a floating point value.
%h data item is a short integer.

PROBLEM SOLVING USING C 30


UNIT-2 INTRODUCTION TO C PROGRAMMING
%s data item is a string.
%x data item is a hexadecimal integer.
%o data item is a octal integer.
printf():
The printf() function is used to print the data from the computer’s memory onto a standard
output device. This function can be used to output any combination of numerical values, single
character and strings.
Syntax:
printf(“control string”, arg-1, arg-2,———arg-n );
 Control string is format specifications that define the output format for display of each item.
 Escape sequence characters such as \n, \t are used in control string.
 Argument should match in number, order and type.
 String that contains formatted information or any string and arg-1, arg-2 —— are arguments
that represent the output data items.
Example : printf(“%d ”, num);
Example:

PROBLEM SOLVING USING C 31

You might also like