Food Rec

Download as pdf or txt
Download as pdf or txt
You are on page 1of 97

UNIT I

C PROGRAMMING FUNDAMENTALS
 History of c language

 Features of c language

 Programming languages (3 levels)

 Applications of ‘c’ language

 Structure of c program

 Flow of c program

 Types of errors

 Step to create source code

 Difference between compiler and interpreter

 C language character set

 C programming: data types

 Basic data types

 Data types and modifiers in c for a 16-bit computer

 C tokens (or) lexical units

 Constant (or) literals

 Keywords in c

 Operators

 Precedence and associativit of operators in c

 Expressions

 Input / output statements

 Assignment statement

 Decision making statements

 Switch statement - looping statements

 Unconditional statements or (jump statements)

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 1


C programming language was developed in 1972 by Dennis Ritchie at bell
laboratories of AT&T (American Telephone & Telegraph), located in U.S.A.

Dennis Ritchie is known as the founder of 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.

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

Year Language Developed by

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 2


1) Simple

C is a simple language in the sense that it provides structured approach (to break the
problem into parts), rich set of library functions, data types etc.

2) Machine Independent or Portable

Unlike assembly language, c programs can be executed in many machines with little
bit or no change. But it is not platform-independent.

3) Mid-level programming language

C is also used to do low level programming. It is used to develop system


applications such as kernel, driver etc. It also supports the feature of high level
language. That is why it is known as mid-level language.

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

5) Rich Library

C provides a lot of inbuilt functions that makes the development fast.

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

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 3


7) Speed

The compilation and execution time of C language is fast.

8) Pointer

C provides the feature of pointers. We can directly interact with the memory by using
the pointers. We can use pointers for memory, structures, functions, array etc.

9) Recursion

In c, we can call the function within the function. It provides code reusability for
every function.

10) Extensible

C language is extensible because it can easily adopt new features.

USES OF C PROGRAMMING LANGUAGE:

The C programming language is used for developing system applications that


forms a major portion of operating systems such as Windows, UNIX and Linux.

 Database systems  Operating system development


 Graphics packages  Compilers and Assemblers
 Word processors  Network drivers
 Spreadsheets  Interpreters

STRUCTURE ORIENTED LANGUAGE: (OR)

PROCEDURE ORIENTED PROGRAM (POP)

 In this type of language, large programs are divided into small programs
called functions
 Prime focus is on functions and procedures that operate on the data
 Data moves freely around the systems from one function to another
 Program structure follows ―Top Down Approach‖
 Examples: C, Pascal, ALGOL and Modula-2

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 4


1. High Level languages:

High level languages provide almost everything that the programmer might
need to do as already built into the language. Example: Java, Python

2. Middle Level languages:

Middle level languages don‘t provide all the built-in functions found in high level
languages, but provides all building blocks that we need to produce the result
we want. Examples: C, C++

3. Low Level languages:

Low level languages provide nothing other than access to the machines basic
instruction set. Example: Assembler

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 5


C is a middle-level language but it has benefits of low-level languages as
well as high-level languages. C is mainly used to develop applications and for
system development work. Use of the C programming language is not limited to
the development of operating systems and applications. It is also used in GUI
development, IDE development, etc.

Some uses of C programming language:

1. Operating Systems

With the help of the C programming language, you can write your own
operating system. Windows Kernel, Linux Kernel and Apple‘s OS X kernel are
mostly written in C.

2. GUI

It stands for Graphical User Interface. The C programming language also


helps in developing popular adobe softwares like Photoshop, Premier Pro, and
Illustrator etc.

3. Embedded Systems

In daily life, we use different embedded systems like coffee machines,


microwaves, climate control systems etc. These all are mostly programmed in C.

4. Database

The C programming language helps in developing the popular database


management system, MySQL.

5. Ease of Computation

C provides faster computation in programs. The implementation of


algorithms and data structures is swift in C. With the help of C, you can perform
high degree calculations such as MATLAB, Mathematica etc.

6. Gaming

C programming is relatively faster than Java or Python. It has been used


in various gaming applications and graphics. C programming language also helps
in creating many popular games like Tic-Tac-Toe, The Snake game etc.

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 6


7. Development of New languages

Due to the fast execution and simplicity, many languages like Java, C++,
Python, PHP, PERL, JavaScript, etc were influenced by the development of C. In
Python, C is used for building standard libraries. The syntax and control
structures of PERL, PHP and C++ are based upon the C programming language.

8. Google

In the Google open source community, the projects are being handled by
C/C++. And C/C++ also helped in developing Google file system and chromium
browser.

9. Assemblers

Mainly used to translate Assembly language to Machine language. C also


helped in developing GNU assembler.

10. Text Editors

C also helped in creating various text editors like Vim, Gedit etc.

11. Drivers

Another application of C is to write driver softwares like Keyboard driver,


Network driver, mouse driver etc.

12. Interpreters

With the help of C programming language, you can create language


interpreters. C helped in developing different programming language interpreters
like Python and MATLAB interpreters etc.

13. Network Devices

Another application of C is to design network devices.

14. Compiler Design

C also helped in designing several popular compilers like Clang C, MINGW,


Apple C etc. This is one of the most popular uses of C language.

C is one of the fastest and most simple programming languages. C is fast,


portable and has a rich library. Being one of the oldest, it is still preferred by
many companies and backend developers. C programming language is being
used in every domain such as hardware and software development, embedded
systems, databases etc

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 7


Structure of C program is defined by set of rules called protocol, to be followed
by programmer while writing C program.

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 8


Sections Description

We can give comments about the program, creation or modified


date, author name etc in this section.

The characters or words or anything which are given between


Documentation

―/*‖ and ―*/‖, won‘t be considered by C compiler for compilation


process.
section

These will be ignored by C compiler during compilation.


Example :

Single line comment - //comment line1

Multiline Comment - /* comment line1 comment line2 comment


line3 */

Link Header files that are required to execute a C program are


Section included in this section

Definition In this section, variables are defined and values are set to these
Section variables.

Global
Global variables are defined in this section. When a variable is to
declaration
be used throughout the program, can be defined in this section.
section

Function
prototype Function prototype gives many information about a function like
declaration return type, parameter names used inside the function.
section

Every C program is started from main function and this function


Main
contains two major sections called declaration section and
function
executable section.

User
defined User can define their own functions in this section which perform
function particular task as per the user requirement.
section

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 9


The C program follows many steps in execution.

To understand the flow of C program well, let us see a simple program first.

File: sample.c

#include <stdio.h>
main()
{
printf("Hello KK");
}

Execution Flow

1) C program sample.c (source code) is sent to preprocessor first. The


preprocessor is responsible to convert preprocessor directives into their
respective values. The preprocessor generates an expanded source code.

2) Expanded source code is sent to compiler which compiles the code and
converts it into assembly code.

3) The assembly code is sent to assembler which assembles the code and
converts it into object code. Now a sample.obj file is generated.

4) The object code is sent to linker which links it to the library such as header
files. Then it is converted into executable code. A sample.exe file is generated.

5) The executable code is sent to loader which loads it into memory and then it
is executed. After execution, output is sent to console.

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 10


C Development Environment

There are lot of IDE programs available for C and C++. IDE makes it easy
to create, compile and execute a C or C++ program. Most of the IDEs are open
source applications (ie.) they are available free of cost.

Familiar C & C++ Compilers with IDE

Compiler (Open source)


1 Turbo C++ 3.7.8.9. 6 CodeLite
2 Quincy 7 K Develop
3 Eclipse 8 Notepad++
4 Net Beans 8 9 Sky IDE
5 Code::blocks 10 Dev C++, Clang……etc

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 11


Compile errors

These are given by the compiler and prevent the program from not running.

Linking errors

This is given by the linker or at runtime and ends the program. The linker can
also detect and report errors, for example, if part of the program is missing or a
non-existent library component is referenced.

Syntax Errors

Syntax is a set of grammatical rules to construct a program. Every programming


language has unique rules for constructing the source code.

Syntax errors occur when grammatical rules of C are violated.

Example: if you type as follows, C will throw an error.

printf(“Hello World”)

As per grammatical rules of C, every executable statement should terminate


with a semicolon. But, this statement does not end with a semicolon.

Semantic Errors

A Program has not produced expected result even though the program is
grammatically correct. It may be happened by wrong use of variable / operator /
order of execution etc. This means, program is grammatically correct, but it
contains some logical error. So, Semantic error is also called as ―Logic Error‖.

Run-time errors

A run time error occurs during the execution of a program. It occurs because of
some illegal operation that takes place.

For example, if a program tries to open a file which does not exist, it results in a
run-time error.

Debugging

Removing errors from a program is called debugging. Any type of error in your
program is known as bug. During debugging an attempt is made to remove all
the known problems or bugs from the program.
Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 12
Source Code is the file which contains programming code in high level
language. To create source code, we need a text editor to write the program.
In C programming language every source code file must be saved with “.c”
extension.

Basic Steps for creating, compiling & executing (run)

Open a text editor &


Step 1
Create New File Alt + f +n

Type the program instructions / Codes


Step 2

Creating Source Code (program) and Save

F2 or Alt + f + s
Step 3

Save the filename with “.c” extension

Compile Source Code


Step 4
Alt + F9 or Alt + c 

Run Executable Code


Step 5
Ctrl + F9 or Alt + r 

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 13


What is the purpose of a compiler?

A compiler is a software tool that translates code written in a high-level programming


language (like C, C++, or Java) into machine code (binary code 0s and 1s known as
object code) that a computer's processor can execute directly.

What is linker?

Linker (link editor binder)

It is a program that combines object modules to form an executable program.

Generally, in case of a large program, the programmers prefer to break a code


into smaller modules as this simplifies the programming task.

Eventually, when the source code of all the modules has been converted into
object code, we need to put all the modules together. This is the job of the
linker.

Usually, the compiler automatically invokes the linker as the last step in
compiling a program.

What is loader?

A loader is a special type of program that copies programs from a storage device
to main memory, where they can be executed.

What is object code in C?

Object code is the output of a compiler after it processes source code. Source
code is the version of a computer program as it is originally written by a human
in a programming language. A compiler is a specialized program that converts
source code into object code.

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 14


Aspect COMPILER INTERPRETER

Translates the entire source code Translates and executes the source

Execution into machine code before code line-by-line or statement-by-


execution. statement.

Generally, it is faster execution


Slower execution compared to
after compilation because the code
Speed compiled code, as translation occurs
is directly translated to machine
during execution.
code.

Errors are detected and must be Errors are detected and must be
Error corrected after the entire program corrected line-by-line during
Detection
is compiled. execution.

Uses less memory as it directly


It requires more memory initially to
Memory executes the instructions without
Consumption store the executable code.
creating an executable file.

Examples C, C++, and Swift Python, JavaScript, and Ruby

Programming Rules in C

Rule 1: All statement should be written in lowercase letters.

Rule 2: Uppercase letter can be used only for symbolic constants.

Rule 3: Blank spaces may be inserted between the words. This improves the
readability of statements.

Rule 4: Blank spaces should not be allowed while declaring variables, constants,
keyword, and function.

Rule 5: Programmer can write the statement anywhere between the "2 braces".

Rule 6: Programmer can write one or more statement in one line, separating
that by semicolon (;).

Rule 7: Opening and closing "braces" must be balanced.

Rule 8: Program must contain a main function.

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 15


Character set is a set of characters which are used to write a C program.
A character represents any alphabet, number or any other symbol (special
characters) mostly available in the keyboard. C accepts the following characters.

Special Symbols

The following table shows some special characters used extensively in C.

White space Characters

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

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 16


Classification of data types in C

A data type specifies the type of data that a variable can store such as integer,
floating, character etc.

There are 4 types of data types in C language.

#include <stdio.h>

void main()

// Create variables

int myNum = 8100; // Integer (whole number)

float myFloatNum = 8.100; // Floating point number

char myLetter = 'K'; // Character

// Print variables

printf("%d\n", myNum);

printf("%f\n", myFloatNum);

printf("%c\n", myLetter);

}
Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 17
C has five basic data types and they are as follows:

Ex.
Specifier

byte(s)
Format
word

Size

Data Type Description


Key

Name

Character %c 1 Stores a single 'A'


char

character/letter/number, or ASCII
values

Integer %d 2 Stores whole numbers, without 1


int

decimals

Floating %f 4 Stores fractional numbers, 1.99


float

containing one or more decimals.


point Sufficient for storing 6 decimal digits

Double
8 Stores fractional numbers, 1.99
double

precision
containing one or more decimals.
floating %lf Sufficient for storing 15 decimal
digits
point

Valueless 2 An empty data type that indicates


void

- the absence of a value it doesn't


hold any value.

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 18


Integer Data type

Integer datatype is a set of whole numbers. Every integer value does not
have the decimal value. We use the keyword "int" to represent integer datatype
in c. A 16-bit signed integer ranges from -32768 to 32767. The integer datatype
is used with different type modifiers like short, long, signed and unsigned.

Syntax:

int var1; //creating an integer type variable named 'var1'

Floating Point Data types

Floating point data types are set of numbers with decimal value (like
3.141592). The floating point data type has two variants float and double.

The keyword "float" to represent floating point data type and "double" to
represent double data type in c.

Type Storage size Value range Precision

float 4 byte 3.4E–38 to 3.4E+38 6 decimal places

double 8 byte 1.7E–308 to 1.7E+308 15 decimal places

Syntax:

float var2;

Character Data type

The character data type is represented by the char keyword and is used to
store a variable with only a single character. The size of the char data type is 1
byte (i.e., 8 bits). It has two subtypes- signed char and unsigned char. The
range for these is -127 to 128 and 0 to 255, respectively. Character data type
is an enclosed in single quotations.

Syntax

char var_name;

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 19


void Datatype

void is an incomplete type. It means "nothing" or "no type". Generally, void is


used to specify a function which does not return any value.

For example, if a function is not returning anything, its return type should be
void. Note that, you cannot create variables of void type.

Data type modifiers:


There are modifiers in the C language, to make the primary data types
more specific.
In the C language, there are 4 datatype modifiers:

1. signed
2. unsigned
3. long
4. short

As the name suggests, signed and unsigned are used to represent


the signed(+ and -) and unsigned(only +) values for any data type.
And long and short affects the range of the values for any datatype.

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 20


Typical Size in Format
Type Range
Byte Specifier

char 1 –128 to 127 %c

unsigned char 1 0 to 255 %c

signed char 1 –128 to 127 %c

int 2 –32768 to 32767 %d, %i

unsigned int 2 0 to 65535 %u

signed int 2 –32768 to 32767 %d, %i

short int 2 –32768 to 32767 %hd

unsigned short int 2 0 to 65535 %hu

signed short int 2 –32768 to 32767 %hd

long int 4 –2147483648 to 2147483647 %ld, %li

-(263 – 1) to 263 – 1
long long int 8 %lld, %lli
(C99 standard)

signed long int 4 –2147483648 to 2147483647 %ld, %li

unsigned long int 4 0 to 4294967295 %lu

264 – 1
unsigned long long int 8 %llu
(C99 standard)

float 4 3.4E–38 to 3.4E+38 %f

double 8 1.7E–308 to 1.7E+308 %lf

long double 10 3.4E–4932 to 1.1E+4932 %Lf

long long num = 123456789987654321; // cannot store a value this big


value using int data type.

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 21


What does signed and unsigned means?

In simple words, the unsigned modifier means all positive values, while
the signed modifier means both positive and negative values.

When the compiler gets a numeric value, it converts that value into a
binary number, which means a combination of 0 and 1. For example,
32767 in binary is 01111111 11111111

In the case of a signed integer, the highest order bit or the first digit
from left (in binary) is used as the sign flag. If the sign flag is 0, the
number is positive, and if it is 1, the number is negative.

For signed int, 11111111 11111111 means -32,767 and because the
first bit is a sign flag to mark it as a negative number, and rest represent
the number. Whereas in the case of unsigned int,
11111111 11111111 means 65,535.

What happens if the value is out of Range?

To assign a value to any data type which is more than the allowed range
of value, then the C language compiler will give an error.
Example:

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 22


Enumerated Datatype

An enumerated datatype is a user-defined data type that consists of integer


constants and each integer constant is given a name. The keyword "enum" is
used to define enumerated datatype.

Derived Data types

Derived datatypes are user-defined data types. The derived datatypes are also
called as user defined datatypes or secondary datatypes. In c programming
language, the derived datatypes are created using the following concepts...
Function, Arrays, Pointer.

Type Casting in C

C compilers allowed programmers to convert from one data type to


another data type by using type cast method. Type casting is also known as type
conversion.

Type Casting Rules

Type casting can be used to convert lower datatypes to higher datatypes


and viceversa (e.g.) int (2 bytes) to float (4 bytes).

The type name to which conversion is to be done is placed in a closed


parenthesis just before the variable. (e.g.) if a float variable 'f' has a value 7.5,
it can be converted into an integer type using (int)f.

Type Casting Lower to Higher Datatype Conversion

Let us write a C program to typecasting int datatype to float datatype

#include <stdio.h>
main()
{
int a = 3;
int b = 2;
int c;
printf("The value of c = %f ",(float)a/b);
}
Output: The value of c = 1.500000

Variables a, b, c belongs to integer data type, where actual result will be in float.
Thus, we are in need to typecast the data type of variable 'c' from an int to float.
Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 23
Type Casting Higher to Lower Datatype Conversion

Let us write a c program to typecasting float datatype to int datatype

#include <stdio.h>
main()
{
float a = 3.56;
printf("The value of a = %d ",(int)a);
}
Output: The value of a = 3

Variables a belongs to float datatype, which is typecasted to int datatype in the


printf statement. Thus integer output is displayed.

Specifiers and qualifiers for the data types:

It can be broadly classified into three types:

Size specifiers— short and long

Sign specifiers— signed and unsigned

Type qualifiers— const, volatile and restrict.

The size qualifiers alter the size of the basic data types. There are two such
qualifiers that can be used with the data type int; these are short and long.

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 24


C program statements are constructed by many different small elements
such as identifiers, constants, keywords and many more symbols called as
operators and punctuators. These individual elements are collectively called as
Lexical units or Lexical elements or Tokens.

C tokens are of six types. They are,

1. Identifiers

2. Constants

3. Keywords

4. Strings

5. Operators

6. Special Symbols

1. Identifiers

Identifiers are the user-defined names given to different parts of the C


program viz. variables, functions, arrays, classes etc., These are the
fundamental building blocks of a program. Every language has specific rules for
naming the identifiers.

Example

int amount;
double totalbalance;

In the above example, amount and totalbalance are identifiers and

int and double are keywords.

Rules for naming identifiers

The first character of an identifier must be an alphabet or an underscore.


Only (alphanumeric characters) alphabets (a-z, A-Z), digits (0-9) and
underscore are permitted (_). Other special characters are not allowed as
part of an identifier.
C is case sensitive as it treats upper and lower-case characters differently.
Reserved words\ or keywords cannot be used as an identifier name.
Identifier names must be unique
Only first thirty-one (31) characters are significant.

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 25


Must not contain white spaces.

Valid identifiers example Invalid identifiers example

1x begins with a digit


Reg_name
char reserved word or (keyword)
sum
x+y special character not allowed
average
Sum-1 hyphen not allowed
_x
123 identifier must start with an
y_ alphabet or underscore

mark_1

x2

Variables in C

A variable is a name of memory location. It is used to store data. It is an


identifier whose value can be changed at the execution time of program. It is a
way to represent memory location through symbol so that it can be easily
identified.

syntax:

datatype variable_name;

The example of declaring variable is given below:

int a;
float b;
char c;

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

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 defining variables

A variable name can have letters (both uppercase and lowercase letters), digits
and underscore only.
Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 26
The first letter of a variable should be either a letter or an underscore. However,
it is discouraged to start variable name with an underscore.

It is because variable name that starts with an underscore can conflict with
system name and may cause error.

There is no rule on how long a variable can be. However, only the first 31
characters of a variable are checked by the compiler.

So, the first 31 letters of two variables in a program should be different.

Valid variable names declaration and initialization:

Variable declaration Syntax: Variable initialization Syntax:

data_type variable_name = value;


data_type variable_name;

int a; float num1; int a = 30; float num1 = 10.10;

int _ab; char ch; int _ab = 50 ; char ch = ‗a‘;

int a30; char name[30]; int num2 = 10 ; char name[100] = ―Abc‖;

Inalid variable names:

int 2;
int a b;
int long;

Types of Variables in C

There are many types of variables in c:

local variable, global variable, static Variable and external Variable

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 27


Local Variable

 The scope of local variables will be within the function only.


 These variables are declared within the function and can‘t be accessed outside
the function.
 In the below example, m and n variables are having scope within the main
function only. These are not visible to test function.
 Likewise, a and b variables are having scope within the test function only.
These are not visible to main function.

Example

#include<stdio.h>

void test(); /* Function declaration */

main()
{
int m = 22, n = 44; /* Local variable declaration and initialization */
printf("\n main function values : m = %d and n = %d", m, n);
test();
}

void test()
{
int a = 50, b = 80; /* Local variable declaration and initialization */
printf("\n sub function values : a = %d and b = %d", a, b);
}

Output:
main function values : m = 22 and n = 44
sub function values : a = 50 and b = 80

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 28


Global Variable

 The scope of global variables will be throughout the program. These variables
can be accessed from anywhere in the program.

 This variable is defined outside the main function. So that, this variable is
visible to main function and all other sub functions.

Example
#include<stdio.h>

void test(); /* Function declaration */

int m = 22, n = 44; /* Global variable declaration and initialization */

int a = 50, b = 80; /* Global variable declaration and initialization */

main()
{
printf("All variables are accessed from main function");
printf("\nvalues: m=%d:n=%d:a=%d:b=%d", m,n,a,b);
test();
}

void test()
{
printf("\n\nAll variables are accessed from" \" test function");
printf("\nvalues: m=%d:n=%d:a=%d:b=%d", m,n,a,b);
}

Output:
All global variables are accessed from main function
values : m = 22 : n = 44 : a = 50 : b = 80
All global variables are accessed from test function
values : m = 22 : n = 44 : a = 50 : b = 80

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 29


static Variable (Keyword static)

Static variables are initialized only once. Compiler persist the variable till the

end of the program. Static variable can be defined inside or outside the function.

Scope − they are local to the block.

Default value − Default initialized value is Zero.

Lifetime − Till the end of the execution of the program.

Example

#include <stdio.h>

/* Function declaration */
void display();

main()
{
display();
display();
display();
}

/* Function definition */
void display()
{
int n1 = 10;
static int n2 = 10;

printf("Local n1 = %d, Static n2 = %d\n", n1, n2);

n1++; // Increment local variable


n2++; // Increment static variable
}

Output:
Local n1 = 10, Static n2 = 10
Local n1 = 10, Static n2 = 11
Local n1 = 10, Static n2 = 12

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 30


External Variable (Keyword extern)

External variables are also known as global variables. These variables are
defined outside the function. These variables are available globally throughout
the function execution. The value of global variables can be modified by the
functions.

Scope − they are not bound by any function. They are


everywhere in the program i.e. global.
Default value − Default initialized value of global variables are Zero.
Lifetime − Till the end of the execution of the program.

First create a file named value.h where you put all your variables with extern
keyword which can be used by any program by simply including the file name in it.
//external variable (also global)

First File name: value.h

Note: The program illustrates that an external variables are declared in separate file with
an extension .h which is then including in demanded file.

Second File name: extest.c

Compile and Run Second file extest.c only.

Output:

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 31


2. Constants in C

• C Constants are also like normal variables. But, only difference is, their
values cannot be modified by the program once they are defined.

• Constants refer to fixed values. They are also called as literals.

• Constants may be belonging to any of the data type.

• Literals are data items whose values do not change during the execution
of a program. Therefore Literals are called as Constants. C has several
kinds of literals:

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 32


Escape sequences (or) Non-graphic characters

C allows certain non-printable characters represented as character


constants. Non-printable characters are also called as non-graphic characters.
Non-printable characters are those characters that cannot be typed directly from
a keyboard during the execution of a program in C, for example: backspace,
tabs etc.
These non-printable characters can be represented by using escape sequences.
An escape sequence is represented by a backslash followed by one or two
characters.

It is composed of two or more characters starting with backslash \.

For example: \n represents new line.

Note:
newline (\n), backspace (\b), Carriage return (\r), tab (\t), space () are
known as whitespace characters.

Example

#include<stdio.h>
main()
{
printf("You\nare\nlearning\n\'c\' language\n\"Do you know C language\"");

Output:

You

are

learning

'c' language

"Do you know C language"

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 33


Keywords in C

A keyword is reserved words which convey specific meaning to the C. They


are the essential elements to construct C programs. You cannot use it as a
variable name, constant name etc. C is a case sensitive programming language
so, all the keywords must be in lowercase.

A list of 32 keywords in c language is given below:

auto break case char const continue default do

double else enum extern float for goto if

int long register return short signed sizeof static

struct switch typedef union unsigned void volatile while

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 34


An operator is simply a symbol that is used to perform operations.

There are following types of operators to perform different types of operations in


C language.

What is a C Operator?

An operator in C can be defined as the symbol that helps us to perform some


specific mathematical, relational, bitwise, conditional, or logical computations on
values and variables. The values and variables used with operators are called
operands. So we can say that the operators are the symbols that perform
operations on operands.

1. Arithmetic Operators

2. Relational Operators

3. Shift Operators

4. Logical Operators

5. Bitwise Operators

6. Ternary or Conditional Operators

7. Assignment Operator

8. Misc Operator

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 35


Arithmetic Operators

The arithmetic operators are used to perform arithmetic/mathematical


operations on operands.

The following table shows all the arithmetic operators supported by the C
language.

Assume variable A holds 10 and variable B holds 20 then

Operator Description Example

+ Adds two operands. A + B = 30

− Subtracts second operand from the first. A − B = -10

* Multiplies both operands. A * B = 200

/ Divides numerator by de-numerator. B/A=2

% Modulus Operator and remainder of after an integer B%A=0


division.

Equality Operators
Assume variable A holds 10 and variable B holds 20 then

Operator Description Example

Checks if the values of two operands are equal or not. If yes, (A == B)


==
then the condition becomes true otherwise false. False

Checks if the values of two operands are equal or not. If the (A != B)


!= values are not equal, then the condition becomes true True
otherwise false.

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 36


Relational Operators

The relational operators in C are used for the comparison of the two operands.
All these operators are binary operators that return true or false values as the
result of comparison.

The following table shows all the relational operators supported by C.

Assume variable A holds 10 and variable B holds 20 then

Operator Description Example

Checks if the value of left operand is greater than the value (A > B)
> of right operand. If yes, then the condition becomes true False
otherwise false.

Checks if the value of left operand is less than the value of (A < B)
right operand. If yes, then the condition becomes true True
< otherwise false.

Checks if the value of left operand is greater than or equal to (A >= B)


the value of right operand. If yes, then the condition False
>= becomes true otherwise false.

Checks if the value of left operand is less than or equal to (A <= B)


the value of right operand. If yes, then the condition True
<= becomes true otherwise false.

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 37


Shift Operators

Binary Left Shift Operator

 A Left Shift of one position moves each bit to the left by one. The vacant
least significant bit (LSB) is filled with zero and the most significant bit
(MSB) is discarded.

Binary Right Shift Operator

 A Right Shift of one position moves each bit to the right by one. The least
significant bit is discarded and the vacant MSB is filled with zero.

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 38


Example:

6010 << 2 = 111100002 = 24010


6010 Decimal value

27 26 25 24 23 22 21 20 Decimal to Binary
128 64 32 16 8 4 2 1 conversion
technology
0 0 1 1 1 1 0 0 Binary value
0 1 1 1 1 0 0 0 Binary Left Shift by 1
1 1 1 1 0 0 0 0 Binary Left Shift by 2

6010 >> 2 = 000011112 = 1510


6010 Decimal value

27 26 25 24 23 22 21 20 Decimal to Binary
128 64 32 16 8 4 2 1 conversion technology

0 0 1 1 1 1 0 0 Binary value
0 0 0 1 1 1 1 0 Binary Right Shift by 1
0 0 0 0 1 1 1 1 Binary Right Shift by 2

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 39


Logical Operators

Logical Operators are used to combine two or more conditions/constraints the


evaluation of the original condition in consideration. The result of the operation
of a logical operator is a Boolean value either true or false.

Operator Description Example

If both left and right operands and (5 > 10) && (5 < 4)
&& expressions are true, it will return true. False
Otherwise, it will return false. Both expressions are false. so,
logical AND output will be 0

If one of the operands or expressions is (10 > 20) || (10 < 20)
true, it will return 1. True
|| If all of them are false, it will return 0. First expression is false and
second one is true. so,
logical OR output will be 1

Logical NOT operator is used to inverse !(100 < 10) 100 is greater
the current decision. Say, if current than 10. So, it will return
! state is true, Logical NOT (!) operator false.
will make it false. !(false) ==> true

Bitwise Operators

1. Bitwise AND (&) operator

Bitwise AND (&) operator will take two equal length binary sequence and perform the
bitwise AND operation on each pair of bit sequence.

AND operator will return 1, if both bits are 1.

Otherwise it will return 0.

Example
Let’s take two integers,
A = 5 and B = 9.
What will be the result of A & B?
Solution
Let’s represent each number in binary format.
A = (0101) 2
Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 40
B= (1001) 2

2. Bitwise OR (|) operator

Bitwise OR (|) operator will take two equal length binary sequence and perform bitwise OR
operation on each pair of bit sequence.

Bitwise OR will return 1, if any of the bit in the pair is 1.

If both bits are 0, then the outcome will be 0.

Example
Let’s take two integers say A = 10 and B = 12,

What will be the result of A | B?

Solution
Then A | B will be,

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 41


3. Bitwise XOR (^) operator

Bitwise XOR (^) operator will take two equal length binary sequence and perform bitwise
XOR operation on each pair of bit sequence.

XOR operator will return 1, if both bits are different.

If bits are same, it will return 0.

Example
Let’s take two integers say A = 5 and B = 9.

Then what will be the result of A ^ B?

Let’s represent each number in binary format.

A = (0101) 2

B= (1001) 2

A B A&B A|B A ^B

0 0 0 0 0

0 1 0 1 1

1 0 0 1 1

1 1 1 1 0

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 42


Bitwise one's compliment operator will invert the binary bits.

If a bit is 1, it will change it to 0.

If the bit is 0, it will change it to 1.

Example
Let’s take a number 4.

Then ~4 will be,

4 = (00000100)2

~4 = (11111011)2. It will convert all 1 to 0 and 0 to 1.

If we print the value of ~4 using printf, it will print -5. How?

Negative numbers are represented using 2’s complement form.

5 = (00000101) 2
1’s complement of 5 = (11111010) 2
Add 1 to get the 2’s complement,
-5 = (11111011) 2
Result of ~4 is equal to the representation of -5 in binary, hence ~4 is -5.

Example
Let’s take number 2,
2 = (00000010) 2
1’s complement of 2 = (11111101) 2
Add 1 to get the 2’s complement,
~2 = (11111101) 2
Result of ~2 is equal to the representation of -3 in binary, hence ~2 is -3.

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 43


Assignment Operators
The following table lists the assignment operators supported by the C language

Operator Description Example

= Simple assignment operator. Assigns values from


C = A + B will
right side operands to left side operand
assign the value of
A + B to C

+= Add AND assignment operator. It adds the right C += A is


operand to the left operand and assign the result to equivalent to
the left operand. C=C+A

-= Subtract AND assignment operator. It subtracts the C -= A is


right operand from the left operand and assigns the equivalent to
result to the left operand. C=C-A

*= Multiply AND assignment operator. It multiplies the C *= A is


right operand with the left operand and assigns the equivalent to
result to the left operand. C=C*A

/= Divide AND assignment operator. It divides the left C /= A is


operand with the right operand and assigns the equivalent to
result to the left operand. C=C/A

%= Modulus AND assignment operator. It takes modulus C %= A is


using two operands and assigns the result to the left equivalent to
operand. C=C%A

<<= Left shift AND assignment operator. C <<= 2 is same as


C = C << 2

>>= Right shift AND assignment operator. C >>= 2 is same as


C = C >> 2

&= Bitwise AND assignment operator. C &= 2 is same as


C=C&2

^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as


C=C^2

|= Bitwise inclusive OR and assignment operator. C |= 2 is same as


C=C|2

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 44


Misc Operators , sizeof & ternary
Besides the operators discussed above, there are a few other important
operators including sizeof and ? : supported by the C Language.

Operator Description Example

Eg. int a;
sizeof() Returns the size of a variable. sizeof(a),
where ‗a‟ is integer, will return 2.

& Returns the address of a &a; returns the actual address of the
variable. variable.

* Pointer to a variable. *a;

Ternary or Conditional Operators (? : )


Ternary operator instead of if…….else statement.

It will take three arguments.

 First argument is comparison statement.


 Second argument will be executed, if the comparison becomes true.
 Third argument will be executed, if the comparison becomes false.

Syntax:

In the above syntax, the expression 1 is a condition which is evaluated, if


the condition is true (Non-zero), then the control is transferred to expression 2,
otherwise, the control passes to expression 3.

Example

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 45


Unary Operators / Modify operators

A unary operator means an operator can perform operations on a single operand


only. That means one operand is enough to perform the operation is called a
unary operator.

Example:

Int a, b = 10;
a = -(b)
The result of this expression is a = -10, because variable b has a positive value.
After applying unary minus operator (-) on the operand b, the value becomes -10,
which indicates it as a negative value.

Increment & Decrement Operators (++ & --)

The increment and decrement operators are called as unary operators because,
both needs only one operand. The increment operator adds one to the existing
value of the operand and the decrement operator subtracts one from the existing
value of the operand.

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 46


Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 47
The increment and decrement operators are used infront of the operand (++a) /
(--a) or after the operand (a++) / (a--).

If it is used infront of the operand, we call it as pre-increment or pre-decrement


and if it is used after the operand, we call it as post-increment or post-decrement.

Pre-Increment or Pre-Decrement

In case of pre-increment, the value of the variable is increased by one before the
expression evaluation. In case of pre-decrement, the value of the variable is
decreased by one before the expression evaluation. That means, when we use pre
increment or pre decrement, first the value of the variable is incremented or
decremented by one, and then modified value is used in the expression
evaluation.

Pre-Increment Pre-Decrement

#include <stdio.h> #include <stdio.h>

main(){ main(){

int i = 5,j; int i = 5,j;

j = ++i; // Pre-Increment j = --i; // Pre-decrement

printf("i = %d, j = %d",i,j); printf("i = %d, j = %d",i,j);

} }

Output: i =6 j=6 Output: i =4 j=4

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 48


Post-Increment or Post-Decrement

In case of post-increment, the value of the variable is increased by one


after the expression evaluation. In case of post-decrement, the value of the
variable is decreased by one after the expression evaluation. That means, when
we use post-increment or post-decrement, first the expression is evaluated with
existing value, then the value of the variable is incremented or decremented by
one.

Post-Increment Post-Decrement

#include <stdio.h> #include <stdio.h>

main(){ main(){

int i = 5,j; int i = 5,j;

j = i++; // Post-Increment j = i--; // Post-decrement

printf("i = %d, j = %d",i,j); } printf("i = %d, j = %d",i,j); }

Output: i = 6 j=5 Output: i = 4 j=5

CODING

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 49


Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 50
What is Operator Precedence?

Operator precedence is used to determine the order of operators


evaluated in an expression. In c programming language every operator has
precedence (priority). When there is more than one operator in an expression
the operator with higher precedence is evaluated first and the operator with
least precedence is evaluated last.

What is Operator Associativity?

Operator associativity is used to determine the order of operators with


equal precedence evaluated in an expression. In c programming language, when
an expression contains multiple operators with equal precedence, we use
associativity to determine the order of evaluation of those operators.

In c programming language the operator precedence and associativity is as


shown in the following table...

Precedence Operator Operator Meaning Associativity

() function call

[] array reference
1 Left to Right
-> structure member access

. structure member access

! negation

~ 1's complement

+ Unary plus

- Unary minus

++ increment operator
2 Right to Left
-- decrement operator

& address of operator

* pointer

sizeof returns size of a variable

(type) type conversion

* multiplication

3 / division Left to Right

% remainder

4 + addition Left to Right

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 51


- subtraction

<< left shift


5 Left to Right
>> right shift

< less than

<= less than or equal to


6 Left to Right
> greater than

>= greater than or equal to

== equal to
7 Left to Right
!= not equal to

8 & bitwise AND Left to Right

9 ^ bitwise EXCLUSIVE OR Left to Right

10 | bitwise OR Left to Right

11 && logical AND Left to Right

12 || logical OR Left to Right

13 ?: conditional operator Left to Right

= assignment

*= assign multiplication

/= assign division

%= assign remainder

+= assign additon

14 -= assign subtraction Right to Left

&= assign bitwise AND

^= assign bitwise XOR

|= assign bitwise OR

<<= assign left shift

>>= assign right shift

15 , separator Left to Right

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 52


Expressions

In any programming language, if we want to perform any calculation or to


frame any condition etc., we use a set of symbols to perform the task. These set
of symbols makes an expression.

An expression is a collection of operators and operands that represents


a specific value.

In the above definition, operator is a symbol which performs tasks like


arithmetic operations, logical operations and conditional operations etc.,

Operands are the values on which the operators perform the task. Here
operand can be a direct value or variable or address of memory location.

Expression Types in C

In C programming language, expressions are divided into THREE types. They are
as follows...

Prefix Expression Infix Expression Postfix Expression

The expression in which The expression in which The expression in which


operator is used before operator is used between operator is used after
operands is called as operands is called as infix operands is called as
prefix expression. expression. postfix expression.

Expression Evaluation

In C programming language, 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.
The operator with higher precedence is evaluated first and the operator with
least precedence is evaluated last.

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 53


Types of Expression Evaluation in C

Based on the operators and operators used in the expression, they are
divided into several types. Types of Expression Evaluation in C are:

 Integer expressions – expressions which contains integers and operators


 Real expressions – expressions which contains floating point values and
operators
 Arithmetic expressions – expressions which contain operands and
arithmetic operators
 Mixed mode arithmetic expressions – expressions which contain both
integer and real operands
 Relational expressions – expressions which contain relational operators
and operands
 Logical expressions – expressions which contain logical operators and
operands
 Assignment expressions and so on… – expressions which contain
assignment operators and operands

An expression is evaluated based on the precedence and associativity


of the operators in that expression.

Example 1

10 + 4 * 3 / 2

In the above expression there are three operators +, * and /. Among these
three operators, both multiplication and division have same higher precedence
and addition has lower precedence. So, according to the operator precedence
both multiplication and division are evaluated first and then addition is
evaluated. As multiplication and division have same precedence they are
evaluated based on the associativity. Here, the associativity of multiplication and
division is left to right. So, multiplication is performed first, then division and
finally addition. So, the above expression is evaluated in the order of * / and +.
It is evaluated as follows...

Step1 4 * 3 ====> 12

Step2 12 / 2 ===> 6

Step3 10 + 6 ===> 16

The expression is evaluated to 16.

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 54


Example 2

6*2/ (2+1 * 2/3 + 6) + 8 * (8/4)

Evaluation of expression Description of each operation

Step1 6*3/( 2+1 * 2/2 +6) +8 * (8/4) An expression is given.

Step2 6*3/(2+2/2 + 6) + 8 * (8/4) 2 is multiplied by 1, giving value 2.

Step3 6*3/(2+1+6) + 8 * (8/4) 2 is divided by 2, giving value 1.

Step4 6*3/ (3+6) + 8 * (8/4) 2 is added to 1, giving value 3.

Step5 6*3/ 9+ 8 * (8/4) 3 is added to 6, giving value 9.

Step6 6*3/9 + 8 * 2 8 is divided by 4, giving value 2.

Step7 18/9 +8 * 2 6 is multiplied by 3, giving value 18.

Step8 2+8*2 18 is divided by 9, giving value 2.

Step9 2 + 16 8 is multiplied by 2, giving value 16.

Step10 18 2 is added to 16, giving value 18.

Example: step1: pow (2, pow (3, 2))

Step2: pow (2, 9)

Step3: 512 (right to left associativity)

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 55


There are two basic types of input and output statements available in ‗C‘.
They are

4. Formatted input and output functions

Input data or output results are formatted as per requirement. Formatted


function improves the readability of the input and output. Formatted functions
can be used to read and write data of all data type (char, int, float and double).
Formatted input and output functions require format specifiers (%c, %d, %f,
%lf) to identify the type of data.

5. Unformatted IO Functions

Only work with character data type. Unformatted input and output functions
do not require any format specifiers. Because they only work with character
data type.

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 56


Input Functions

C programming language provides built-in functions to perform input


operations. The input operations are used to read user values (input) from
keyboard. C programming language provides the following built-in input
functions...

1. scanf()
2. getchar()
3. getch()
4. gets()
5. fscanf()

scanf() function

The scanf() function is used to read multiple data values of different data
types from the keyboard. The scanf() function is built-in function defined in a
header file called "stdio.h". When we want to use scanf() function in our
program, we need to include the respective header file (stdio.h) using #include
statement. The scanf() function has the following syntax...

Syntax: scanf("format strings", &variableNames);

Example Program1

#include <stdio.h>

void main()

int i;

printf("\nEnter any integer value: ");

scanf("%d",&i);

printf("\nYou have entered number is : %d ",i);

Output:

Enter any integer value: 55

You have entered number is : 55

In the above example program, we used the scanf() function to read an


integer value from the keyboard and store it into variable 'i'.

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 57


Example Program

The scanf function also used to read multiple data values of different or same
data types. Consider the following example program...

#include <stdio.h>

main()

int i;

float x;

printf("\nEnter one integer followed by one float value : ");

scanf("%d %f", &i, &x);

printf("\n Integer = %d, Float = %f", i, x);

Output:

Enter one integer followed by one float value: 20 30.5

Integer = 20, Float = 30.5

In the above example program, we used the scanf() function to read one
integer value and one float value from the keyboard. Here 'i' is an integer
variable so we have used format string %d, and 'x' is a float variable so we have
used format string %f.

The scanf() function returns an integer value equal to the total number of input
values read using scanf function.

Program to count number of input values

#include <stdio.h>

main()

int i,a,b;

float x;

printf("\nEnter two integers and one float: ");

i = scanf("%d%d%f",&a, &b, &x);

printf("\n Total inputs read: %d",i);

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 58


Output:

Enter two integers and one float: 10 20 55.5

Total inputs read: 3

getchar() function

The getchar() function is used to read a character from the keyboard and
return it to the program. This function is used to read only single character. To
read multiple characters we need to write multiple times or use a looping
statement. Consider the following example program...

#include <stdio.h>

main()

char ch;

printf("\nEnter any character: ");

ch = getchar();

printf("\nYou have entered: %c",ch);

Output:

Enter any character: A

You have entered: A

getch() function

The getch() function is similar to getchar function. The getch() function is


used to read a character from the keyboard and return it to the program. This
function is used to read only single character. To read multiple characters we
need to write multiple times or use a looping statement. Consider the following
example program...

#include <stdio.h>

main()

char ch;

printf("\nEnter any character : ");

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 59


ch = getch();

printf("\nYou have entered : %c",ch);

Output:

Enter any character: A

You have entered: A

gets() function

The gets() function is used to read a line of string and stores it into
character array. The gets() function reads a line of string or sequence of
characters till a newline symbol enters. Consider the following example
program...

#include <stdio.h>

main()

char name[30];

printf("\n Enter your favourite University website: ");

gets(name);

printf("%s",name);

Output:

Enter your favourite University website: www.annauniv.edu

www.annauniv.edu

fscanf() function

The fscanf() function is used with the concept of files.

The fscanf() function is used to read data values from a file.

When you want to use fscanf() function the file must be opened in reading
mode.

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 60


Output Functions

C programming language provides built-in functions to perform output


operation. The output opearations are used to display data on user screen
(output screen) or printer or any file. C programming language provides the
following built-in output functions...

1. printf()
2. putchar()
3. puts()
4. fprintf()

printf() function

The printf() function is used to print string or data values or combination


of string and data values on the output screen (User screen). The printf()
function is built-in function defined in a header file called "stdio.h". When we
want to use printf() function in our program we need to include the respective
header file (stdio.h) using #include statement.

Syntax: printf("message to be display!");

#include <stdio.h>

main()

printf("Hello! Welcome to C Program");

Output: Hello! Welcome to C Program

In the above example program, we used the printf() function to print a


string on to the output screen. The printf() function is also used to display data
values.

When we want to display data values we use format string of the data
value to be display.

Syntax: printf("format string",Variable_Name);

The format string can be %d (integer), %c (character), %s (string), %f


(float) etc.

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 61


#include <stdio.h>

main()

int i = 10;

float x = 5.5;

printf("%d %f",i, x);

Output: 10 5.5

In the above example program, we used the printf() function to print data
values of variables i and x on to the output screen. Here i is a integer variable so
we have used format string %d and x is a float variable so we have used format
string %f.

The printf() function can also used to display string along with data
values.

Syntax: printf("String format string",variableName);

#include <stdio.h>

main()

int i = 10;

float x = 5.5;

printf("Integer value = %d, Float value = %f",i, x);

Output: Integer value = 10, Float value = 5.5

In the above program we are displaying string along with data values.

Every function in C programming language must have a return value. The


printf() function also have integer as return value. The printf() function returns
an integer value equalent to the total number of characters it has printed.

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 62


#include <stdio.h>

main()

int i;

i = printf("Tiruchirappalli");

printf(" is %d number of characters.",i);

Output:

Tiruchirappalli is 15 number of characters.

In the above program, first printf() function printing " Tiruchirappalli " which is
of 15 characters. So it returns integer value 15 to variable "i". The value of "i" is
printed in the second printf() function.

Formatted printf() function

Generally, when we write multiple printf() statements the result is displayed in


single line because the printf() function displays the output in a single line.
Consider the following example program...

#include <stdio.h>

main()

printf("Welcome to ");

printf("C ");

printf("Language");

Output:

Welcome to C Language

In the above program, there are 3 printf() statements written in different lines
but the output is displayed in single line only.

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 63


To display the output in different lines or as we wish, we use some special
characters called escape sequences. Escape sequences are special characters
with special functionality used in printf() function to format the output according
to the user requirement.

#include <stdio.h>

main()

printf("Welcome to\n");

printf("C\n");

printf("Language");

Output:

Welcome to

Language

putchar() function

The putchar() function is used to display single character on the output


screen. The putchar() functions prints the character which is passed as
parameter to it and returns the same character as return value. This function is
used to print only single charater. To print multiple characters we need to write
multiple times or use a looping statement. Consiider the following example
program...

#include <stdio.h>

main()

char ch = 'A';

putchar(ch);

Output: A

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 64


puts() function

The puts() function is used to display string on the output screen. The puts()
functions prints a string or sequence of characters till the newline. Consiider the
following example program...

#include <stdio.h>

main()

char name[30];

printf("\nEnter your favourite website: ");

gets(name);

puts(name);

Output:

Enter your favourite website: www.annauniv.edu

www.annauniv.edu

fprintf() function

The fprintf() function is used with the concept of files.

The fprintf() function is used to print a line into the file.

When you want to use fprintf() function the file must be opened in writting
mode.

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 65


An assignment statement, assigns value on the right hand side of an
expression to the variable on the left hand side of the assignment operator. „=‟
is the assignment operator. For example the different styles of assigning values
to the variables are as follow:

An assignment statement gives a value to a variable.

Syntax:

datatype variable = expression;

Example:

int x = 5;

gives x the value 5.

The value of a variable may be changed. For example, if x has the value 5, then the
assignment statement

x = x + 1; will give x the value 6.

Example:

int i = 0;

int i = j = k = 0; sets all of i, j, and k to zero.

What happens FIRST when the following statement executes?

value1 = 2*3 ;

FIRST, do the multiplication 2*3 to get the value 6.

NEXT, put the result of the calculation into the variable value1.

Compound Operators

a=a+b is written as

a += b

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 66


Unary Assignment Operators

sum = ++count (count incremented then added to sum)

sum = count++ (count added to sum then incremented)

Array initialization syntax:

data_type arr_name [arr_size] = {value1, value2, value3,….};

or

data_type arr_name1 = value1;

data_type arr_name2 = value2;

data_type arr_name3 = value3;

Example:

int age[3]={10, 20, 30};

age[0]; /*10 is accessed*/


age[1]; /*20 is accessed*/
age[2]; /*30 is accessed*/

Character array example:

char str[4]={‗H‘,‗a‘,‗i‘};

it will store

str[0]; /*H is accessed*/


str[1]; /*a is accessed*/
str[2]; /*i is accessed*/

(or)

str[0] = ‗H‘;
str[1] = ‗a‘;
str[2] = ‗i;

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 67


Decision Making Statement: Branching statement
In c programming language, the program execution flow is, line by line
from top to bottom. That means the c program is executed line by line from the
main method. Sometimes, we make some decisions or we may skip the
execution of one or more lines of code.

Consider a situation,

Write a program to check whether a student has passed or failed in a


particular subject. Here, we need to check whether the marks are greater than
the pass marks or not. If marks are greater, then we take the decision that the
student has passed otherwise failed. To solve such kind of problems in c we use
the statements called decision making statements.

Decision making statements are the statements that are used to verify a
given condition and decide whether a block of statements gets executed or not
based on the condition result.

There are two decision making statements they are as follows...

1. Conditional
2. Unconditional

Conditional Statements (Two Types)

1. if statement
2. switch statement

if statement in c

In c, if statement is used to make decisions based on a condition. if statement


verifies the given condition and decides whether a block of statements are
executed or not based on the condition result. In c, if statement is classified into
four types as follows...

Simple if statement
if - else statement
Nested if statement
if-else-if statement (if-else ladder)
Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 68
Simple if statement
The ‗if‘ statement evaluates a condition, if the condition is true then a true-
block (a statement or set of statements) is executed, otherwise the true-block is
skipped.

Example:

#include <stdio.h> #include <stdio.h>


main() main()
{ {
int m=40,n=40; int age;
if (m == n) printf("Enter your age : \t");
{ scanf(―%d‖, &age);
printf("m and n are equal"); if (age >= 18)
} {
} printf("You are eligible for voting");
}
}

Output
Output Enter your age: 23
m and n are equal You are eligible for voting

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 69


if - else statement

The if-else statement evaluates the specified condition. If it is TRUE, it


executes a block of statements (True block). If the condition is FALSE, it
executes another block of statements (False block ie. Else block).

Syntax

if (test-expression)
{
True block of statements
}
else
{
False block of statements
}
Statements;

Execution Flow diagram

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 70


// C program to find the given // C program to find the greatest of
number is odd or even two numbers

#include <stdio.h> #include<stdio.h>


main() main()
{ {
int num, rem; int num1, num2;
printf("Enter a number : \t"); printf(―Enter two numbers : \n―);
scanf(―%d‖, &num); scanf(―%d %d‖,&num1,&num2);
rem = num % 2; if(num1 > num2)
if (rem == 0) {
{ printf(―%d is greater‖,num1);
printf("The given number %d is }
Even", num); else
} {
else printf(―%d is greater‖,num2);
{ }
printf("The given number %d is }
Odd", num);
}
}
Output
Output
Enter two numbers :
Enter number: 10 10
The given number 10 is Even 15
15 is greater

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 71


Nested if statement

An if statement which contains another if statement is called nested if.


The nested can have one of the following three forms.
1. If nested inside if part
2. If nested inside else part
3. If nested inside both if part and else part
The syntax of the nested if:

Syntax

if ( test condition1)
{
if ( test condition2)
{
Test condition2 True statements;
}
else
{
Test condition2 False statements;
}
}
else
{
Test condition1 False statements;
}

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 72


In the first syntax of the nested if mentioned above the expression-1 is
evaluated and the expression result is false then control passes to statement-m.
Otherwise, expression-2 is evaluated, if the condition is true, then Nested-True-
block is executed, next statement-n is also executed. Otherwise Nested-False-
Block, statement-n and statement-m are executed.

The working procedure of the above said if..else structures are given as
flowchart below:

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 73


Example (if nested inside if part)

#include <stdio.h>
#include<conio.h>
void main()
{
int n ;
clrscr() ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n < 100 )
{
printf("Given number is below 100\n") ;
if( n%2 == 0)
printf("And it is EVEN") ;
else
printf("And it is ODD") ;
}
else
printf("Given number is not below 100") ;
}

Output 1:

Enter any integer number: 55


Given number is below 100
And it is ODD

Output 2:
Enter any integer number: 999
Given number is not below 100

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 74


Example (if nested inside else part)

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 75


if - else - if statement (if-else ladder)

The if-else ladder is a multi-path decision making statement. In this type of


statement 'if' is followed by one or more else if statements and finally end with
an else statement.

Syntax

if (testExpression1)
{
// statements to be executed if testExpression1 is true
}
else if(testExpression2)
{
// statements to be executed if testExpression1 is false and testExpression2 is
true
}
else if (testExpression 3)
{
// statements to be executed if testExpression1 and testExpression2 is false
and testExpression3 is true
}
.
.
else
{
// statements to be executed if all test expressions are false
}

When the respective expression becomes true, the statement associated with
block is executed, and the rest of the ladder is bypassed. If none of the
conditions is true, then the final else statement will be executed.

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 76


Find the largest of three numbers.
#include <stdio.h>
#include<conio.h>
void main()
{
int a, b, c ;
printf("Enter any three integer numbers: ") ;
scanf("%d%d%d", &a, &b, &c) ;

if( a>=b && a>=c)


printf("%d is the largest number", a) ;
else if (b>=a && b>=c)
printf("%d is the largest number", b) ;
else
printf("%d is the largest number", c) ;
}

Output
Enter any three integer numbers: 55 60 20
60 is the largest number

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 77


C Program to print grade of a student using if else ladder Statement

Grade selection based on score.


Here, if our score is more than 90, we will get S grade
If our score is in between 80 and 90, we will get A grade
If our score is in between 70 and 80, we will get B grade
If our score is in between 60 and 70, we will get C grade
If our score is in between 51 and 60, we will get D grade
If our score is 50, we will get E grade
Below 50 will be declared as U.

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 78


The switch statement is a multi-way branch statement. It provides an
easy way to dispatch execution to different parts of code based on the value of
the expression. The switch statement replaces multiple if-else sequence.

Syntax

switch ( expression )
{
case label1:
statement(s);
break;
case label2:
statement(s);
break;
case label3:
statement(s);
break;
default:
statement(s);

In the above syntax, the expression is evaluated and if its value matches
against the constant value specified in one of the case statements, that
respective set of statements are executed. Otherwise, the statements under the
default option are executed. The workflow of switch statement and flow chart
are shown below.

Rules

1) The switch expression must be of integer or character type.

2) The case value must be integer or character constant.

3) The case value can be used only inside the switch statement.

4) The break statement in switch case is not must. It is optional. If there is no


break statement found in switch case, all the cases will be executed after
matching the case value. It is known as fall through state of C switch
statement.

Why break statement?

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 79


Break statement is used to terminate switch statement execution, once we have
achieved our result.

Rule 1 : Case Label must be unique

int id = 3 ;
switch(id)
{
case 2:
printf("C++ Programming Language");
break;
case 2: //error
printf("Web Technology");
break;

Rule 2 : Case Labels must ends with Colon

case 1 :
printf("C Programming Language");
break;

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 80


Rule 3 : Case labels must have constants / constant expression

case 1+1: //error


case 'A':
case 67:

However variables are not allowed in switch case labels.

case var : //error


case num1 : //error
case n1+n2 : //error

Rule 4 : Case label must be of integral Type ( Integer, Character) whereas Case label
should not be ‘floating point number ‘

case 10:
case 20+20:
case 'A':
case 'a':

Illegal examples

case 10.12: //error


case 7.5: //error

Rule 5 : Switch case should have at most one default label

switch(roll)
{
case 1:
printf("C Programming Language");
break;
case 2:
printf("C++ Programming Language");
break;
default :
printf("Default Version 1");
break;
default : //error
printf("Default Version 2");
break;
}
It violets rule.

Rule 6 : Default label is Optional

switch(roll)
{
case 1 :
printf("C Programming Language");

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 81


break;
case 2 :
printf("C++ Programming Language");
break;
}

default statement is optional. It can be neglected.

Rule 7 : Default can be placed anywhere in the switch

switch(roll)
{
case 1 :
printf("C Programming Language");
break;
default: //ANYWHERE
printf("No Student Found");
break;
case 2 :
printf("C++ Programming Language");
break;

Rule 8 : Break Statement takes control out of the switch

Rule 9 : Two or more cases may share one break statement

switch(alpha)
{
case 'a':
case 'A':
printf("Alphabet A");
break;
case 'b':
case 'B':
printf("Alphabet B");
break;
}

Rule 10 : Nesting ( switch within switch ) is allowed

switch(alpha)
{
case 'a':
case 'A':
printf("Alphabet A");

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 82


break;
case 'b':
case 'B':

switch(alpha)
{
}
break;
}

Rule 11 : Relational Operators are not allowed in Switch Statement.

switch(num)
{
case >15: //error
printf("Number > 15");
break;
case =15: //error
printf("Number = 15");
break;

Rule 12 : Macro Identifier are allowed as Switch Case Label.

#define MAX 2

switch(num)
{
case MAX:
printf("Number = 2");
break;
}
as preprocessor will replace occurrence of MAX by constant value i.e 2 theref
or it is allowed.

Rule 13 : Const Variable is allowed in switch Case Statement.

int const var = 2;


switch(num)
{
case var:
printf("Number = 2");
break;
}

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 83


Example:
#include<stdio.h>
main()
{
char ch;
printf("Enter the Vowel (In Capital Letter):");
scanf("%c",&ch);
switch( ch )
{
case 'A' : printf( "Your Character Is A\n" );
break;

case 'E' : printf( "Your Character Is E\n" );


break;

case 'I' : printf( "Your Character Is I\n" );


break;

case 'O' : printf( "Your Character Is O\n" );


break;

case 'U' : printf( "Your Character Is U\n" );


break;
default : printf( "Your Character is Not Vowel.
Otherwise Not a Capital Letter\n" );
break;
}
getch();
}

Output:

Enter the Vowel (In Capital Letter): A


Your Character Is A
Enter the Vowel (In Capital Letter): O
Your Character Is O
Enter the Vowel (In Capital Letter): h
Your Character is Not Vowel. Or Not a Capital Letter

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 84


Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 85
In c, there is a control statement which does not need any condition to
control the program execution flow. These control statements are called
as unconditional control statements. C programming language provides the
following unconditional control statements...

1. break

2. continue

3. goto

Break Statement

The Break statement in C Programming is very useful to exit from any


loop such as For Loop, While Loop and Do While Loop. While executing these
loops, if compiler finds the break statement inside them, then the loop will stop
executing the statements and immediately exit from the loop.

NOTE: Break statement in C Programming is the most important


statement in Switch Case. Without using Break compiler won‘t exit from the
switch cases.

Syntax: break;

Example

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 86


Continue Statement in C

The continue statement works quite similar to the break statement. Instead
of terminating the loop (break statement), continue statement forces the loop to
continue or execute the next iteration. When the continue statement is executed
in the loop, the code inside the loop following the continue statement will be
skipped and next iteration of the loop will begin.
Syntax continue;

Difference between Break and Continue


Break Continue

Break is used to terminate the Continue is not used to terminate the


execution of the loop. execution of loop.

It breaks the iteration. It skips the iteration.

When this statement is executed, When this statement is executed, it will


control will come out from the loop and not come out of the loop but
executes the statement immediate after moves/jumps to the next iteration of
loop. loop.

Break is used with loops as well as Continue is only used in loops, it is not
switch case. used in switch case.

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 87


goto Statement in C

The goto statement in C Programming is used to alter the flow of a program.


When the compiler reaches the goto statement then it will jump unconditionally
(both forward and backward) to the location specified in the goto statement
(called it as label).

Syntax

Example:

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 88


Output:

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 89


Looping Statements or (Iteration statements)
Iteration (or looping) is a sequence of one or more statements that are
repeatedly executed until a condition is satisfied. These statements are also
called as control flow statements. It is used to reduce the length of code, to
reduce time, to execute program and takes less memory space. C supports three
types of iteration statements;

1. while statement
2. do-while statement
3. for statement

All looping statements repeat a set statements as long as a specified


condition is remains true. The specified condition is referred as a loop control.
For all three loop statements, a true condition is any nonzero value and a zero
value shows a false condition.

while Statement
A while loop is a control flow statement that allows the loop statements to be
executed as long as the condition is true. The while loop is an entry-controlled
loop because the test-expression is evaluated before entering into a loop.

 If the condition is True then it will execute the statements inside the loop.
 Next we have to use Increment and Decrement Operator inside the while
loop to increment and decrements the value. Please refer Increment and
Decrement Operator in C article to understand the functionality
 Again it will check for the condition after the value incremented. As long
as the condition is True, the statements inside the while loop will be
executed.
 If the condition is False then it will exit from the While loop

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 90


At first, the given condition is evaluated. If the condition is TRUE, the single
statement or block of statements gets executed. Once the execution gets
completed the condition is evaluated again. If it is TRUE, again the same
statements get executed. The same process is repeated until the condition is
evaluated to FALSE. Whenever the condition is evaluated to FALSE, the
execution control moves out of the while block.

Program to display even numbers upto 10.

#include <stdio.h>
main()
{
int n = 0;
clrscr() ;
printf("Even numbers upto 10\n");
while( n <= 10 )
{
if( n%2 == 0)
printf("%d\t", n) ;
n++ ;
}
getch() ;
}

Output :
Even numbers upto 10
0 2 4 6 8 10

#include <stdio.h>
main()
{
int count=1;
while (count <= 4)
{
printf("%d\t ", count);
count++;
}
return 0;
}
Ouput:

1 2 3 4

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 91


do-while Statement

The do-while loop is an exit-controlled loop. In do-while loop, the condition is


evaluated at the bottom of the loop after executing the body of the loop. This
means that the body of the loop is executed at least once, even when the
condition evaluates false during the first iteration.

Program to display even numbers upto 10.

#include <stdio.h>
#include<conio.h>
void main(){
int n = 0;
clrscr() ;
printf("Even numbers upto 10\n");

do
{
if( n%2 == 0)
printf("%d\t", n) ;
n++ ;
}while( n <= 10 ) ;

getch() ;
}
Output
Even numbers upto 10
0 2 4 6 8 10

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 92


for Statement
The for loop is a entry- controlled loop and is the easiest looping statement
which allows code to be executed repeatedly. It contains three different
statements (initialization, condition or test-expression and update expression(s))
separated by semicolons.

 for is a keyword so it must be used only in lower case letters.


 Every for statement must be provided with initialization, condition and
modification (They can be empty but must be separated with ";")
 Ex: for ( ; ; ) or for ( ; condition ; Increment/Decrement operator ) or
for ( ; condition ; )
 In for statement, the condition may be a direct integer value, a variable or
a condition.
 The for statement can be an empty statement.

Syntax

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 93


Initialization: For loop starts with the initialization statement so, initialization
of counters variables is done first (For example counter = 1 or i = 1.). The
initialization section is executed only once at the beginning of the for loop.

Test Condition: The value of the counter variable is tested against the test
condition. If the condition is True then it will execute the statements inside the
For loop. If the condition fails then For loop will be terminated.

Increment and decrement operator: This expression is executed after the


end of each iteration. This operator helps to increase or decrease the counter
variable as per our requirement. Please refer Increment and decrement operator
in C article to understand the operator

Example: Program to display numbers 0 upto 9.


#include <stdio.h>

main()
{
int i;
for(i=0;i<10;i++)
{
printf("%d ",i);
}
}

OUTPUT:
0123456789

Program to display even numbers upto 10.


#include <stdio.h>
main()
{
int n ;
clrscr() ;
printf("Even numbers upto 10\n");
for( n = 0 ; n <= 10 ; n++ )
{
if( n%2 == 0)
printf("%d\t", n) ;
}
getch();
}

Output
Even numbers upto 10
0 2 4 6 8 10

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 94


Nested for Loop, while loop and do...while loop

A loop which contains another loop is called as a nested loop.

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 95


Nested For Loop: A for loop inside another for loop is called nested for
loop.

Nested while loop : A while loop inside another while loop is called nested while
loop.

Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 96


Dr. Aravinda NarayananP alias KarthikeyanP, 8100, AUT Page 97

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy