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

CS8251 Programming in C

This document provides an overview of the CS8251 Programming in C course. It discusses various programming paradigms like imperative, structured, declarative, functional and object-oriented programming. It then describes the basic structure of a C program including preprocessor commands, functions, variables, statements, expressions and comments. It also covers tokens, identifiers, keywords, whitespace, data types and more foundational C programming concepts.

Uploaded by

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

CS8251 Programming in C

This document provides an overview of the CS8251 Programming in C course. It discusses various programming paradigms like imperative, structured, declarative, functional and object-oriented programming. It then describes the basic structure of a C program including preprocessor commands, functions, variables, statements, expressions and comments. It also covers tokens, identifiers, keywords, whitespace, data types and more foundational C programming concepts.

Uploaded by

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

CS8251 PROGRAMMING IN C

Unit 1: PROGRAMMING IN C

Introduction to programming paradigms

A programming paradigm is a way of programming, a style of solving problems and


thinking about the domain. Languages directly or indirectly influence
programming style; for example, Haskell is purely functional while Python allows a
blend of OOP, functional and imperative programming.

Even though most new languages are multi-paradigm, they usually make it easiest to
program in a single paradigm; C programs can be written in a functional
programming style (instead of the orthodox procedural fashion) –  it is just
extremely difficult. Ever wondered why classes are needed to add two numbers in
OOP Java?

Paradigms can be viewed as abstractions and metaphors for modelling problems –


logic programs can be viewed as theorem solvers; functional programs rely
on mathematical models while OOP models real-life objects and their interactions.

Nearly every standard problem can be solved using any of the programming
paradigms however some problems are best solved using some paradigms (e.g.
recursion vs loops). Thus knowing many paradigms helps programmers in
producing very neat and elegant solutions; since they know different ways of solving
problems and modelling domains.

Let’s take a shallow dive into some of the popular paradigms.

1. Imperative Programming

imperate: Done by express direction, not involuntary; commanded

In the imperative paradigm, programs are written as a series of instructions that affect


global state. It is conceptually similar to cooking recipes which strictly list the steps
in preparing a dish.

The imperative paradigm was quite popular until Dijkstra published his famous
‘GOTO considered harmful‘ letter. This fueled the adoption of the structured
programming paradigm (albeit at the detriment of imperative programming).

2. Structured Programming
Structured programming is somewhat similar to imperative programming however
control flow is defined in terms of loops, subroutines and conditionals; this
distinguishes it from the imperative model of jumping around at the heck and bequest
of every GOTO call.

The introduction of lexical scoping also helps to prevent the inadvertent overwriting
of variables in the global scope.

3. Declarative Programming

Declarative programs have implicit execution: programs say what they want but not
how the results should be gotten. SQL is a popular example, have you ever wondered
how the SQL engine is able to calculate sums, averages, max etc.

A conceptual example is that of a manager declaring sales targets for his marketing


team: the team is smart enough to figure out heuristics and also to go do it on their
own (hopefully within ethical and legal limits).

4. Functional Programming (FP)

The functional programming paradigm is a subset of the declarative paradigm. All


computation is done using functions – it attempts to do away with the use of
variables and value assignments.

Pure functional programs are written as a combination of function calls which have
no side effects and return the same result every time they are called with the same
input no matter the environment. The elegance of FP comes from the use of higher-
order functions (functions which can accept/return other functions e.g.
differentiation/integration in the maths domain), referential transparency and high
levels of abstraction.

On the other hand, some concepts might be inefficient (e.g. Y combinator) or ugly.

5. Object Oriented Programming (OOP)

This is probably the most popular and probably most widely-used of all


programming paradigms. Object oriented programming is built on four major
principles – encapsulation, polymorphism, inheritance and data abstraction.

OOP allows the creation of abstract models that mirror real-life objects’ interactions
and behaviour. This enables the creation of huge complex software systems having
intricate interactions such as state preservation, communication exchanges and
behaviour handling.
There are two flavours: classical (where objects are defined and share their
characteristics and behaviour based on a class’ blueprint) and prototypical (objects
get their behaviour and characteristics from an original prototype object).

Conclusion

Some other paradigms include the event-driven where program respond to events
(think web apps) while the logical programming paradigm tries to infer the solution
when it is given a set of constraints and or conditions.

Structure of C program
Before we study the basic building blocks of the C programming language, let us
look at a bare minimum C program structure so that we can take it as a reference in
the upcoming chapters.
A C program basically consists of the following parts −
Preprocessor Commands
Functions
Variables
Statements & Expressions
Comments
Let us look at a simple code that would print the words "Hello World" −
#include <stdio.h>

int main() {
/* my first program in C */
printf("Hello, World! \n");

return 0;
}

Let us take a look at the various parts of the above program −


The first line of the program #include <stdio.h> is a preprocessor command, which
tells a C compiler to include stdio.h file before going to actual compilation.
The next line int main() is the main function where the program execution begins.
The next line /*...*/ will be ignored by the compiler and it has been put to add
additional comments in the program. So such lines are called comments in the
program.
The next line printf(...) is another function available in C which causes the message
"Hello, World!" to be displayed on the screen.
The next line return 0; terminates the main() function and returns the value 0.

Compile and Execute C Program


Let us see how to save the source code in a file, and how to compile and run it.
Following are the simple steps −
Open a text editor and add the above-mentioned code.
Save the file as hello.c
Open a command prompt and go to the directory where you have saved the file.
Type gcc hello.c and press enter to compile your code.
If there are no errors in your code, the command prompt will take you to the next
line and would generate a.out executable file.
Now, type a.out to execute your program.
You will see the output "Hello World" printed on the screen.
$ gcc hello.c
$ ./a.out
Hello, World!
Make sure the gcc compiler is in your path and that you are running it in the
directory containing the source file hello.c.

You have seen the basic structure of a C program, so it will be easy to understand
other basic building blocks of the C programming language.
Tokens in C
A C program consists of various tokens and a token is either a keyword, an
identifier, a constant, a string literal, or a symbol. For example, the following C
statement consists of five tokens −
printf("Hello, World! \n");
The individual tokens are −
printf
("Hello, World! \n"
)
;

Semicolons
In a C program, the semicolon is a statement terminator. That is, each individual
statement must be ended with a semicolon. It indicates the end of one logical entity.
Given below are two different statements −
printf("Hello, World! \n");
return 0;

Comments
Comments are like helping text in your C program and they are ignored by the
compiler. They start with /* and terminate with the characters */ as shown below −
/* my first program in C */
You cannot have comments within comments and they do not occur within a string
or character literals.

Identifiers
A C identifier is a name used to identify a variable, function, or any other user-
defined item. An identifier starts with a letter A to Z, a to z, or an underscore '_'
followed by zero or more letters, underscores, and digits (0 to 9).
C does not allow punctuation characters such as @, $, and % within identifiers. C is
a case-sensitive programming language. Thus, Manpower and manpower are two
different identifiers in C. Here are some examples of acceptable identifiers −
mohd zara abc move_name a_123
myname50 _temp j a23b9 retVal
Keywords
The following list shows the reserved words in C. These reserved words may not be
used as constants or variables or any other identifier names.

auto else long switch

break enum register typedef

case extern return union

char float short unsigned

const for signed void

continue goto sizeof volatile

default if static while

do int struct _Packed

double

Whitespace in C
A line containing only whitespace, possibly with a comment, is known as a blank
line, and a C compiler totally ignores it.
Whitespace is the term used in C to describe blanks, tabs, newline characters and
comments. Whitespace separates one part of a statement from another and
enables the compiler to identify where one element in a statement, such as int,
ends and the next element begins. Therefore, in the following statement −
int age;
there must be at least one whitespace character (usually a space) between int and
age for the compiler to be able to distinguish them. On the other hand, in the
following statement −
fruit = apples + oranges; // get the total fruit
no whitespace characters are necessary between fruit and =, or between = and
apples, although you are free to include some if you wish to increase readability.

C Programming:

Data Types
Data types in c refer to an extensive system used for declaring variables or functions
of different types. The type of a variable determines how much space it occupies in
storage and how the bit pattern stored is interpreted.

The types in C can be classified as follows −


Sr.No. Types & Description

1 Basic Types
They are arithmetic types and are further classified into: (a) integer
types and (b) floating-point types.

2 Enumerated types
They are again arithmetic types and they are used to define variables
that can only assign certain discrete integer values throughout the
program.

3 The type void


The type specifier void indicates that no value is available.

4 Derived types
They include (a) Pointer types, (b) Array types, (c) Structure types,
(d) Union types and (e) Function types.

The array types and structure types are referred collectively as the aggregate types.
The type of a function specifies the type of the function's return value. We will see
the basic types in the following section, where as other types will be covered in the
upcoming chapters.

Integer Types
The following table provides the details of standard integer types with their storage
sizes and value ranges −
Type Storage size Value range

char 1 byte -128 to 127 or 0 to 255

unsigned char 1 byte 0 to 255

signed char 1 byte -128 to 127

-32,768 to 32,767 or -2,147,483,648 to


int 2 or 4 bytes
2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295

short 2 bytes -32,768 to 32,767

unsigned short 2 bytes 0 to 65,535

long 4 bytes -2,147,483,648 to 2,147,483,647

unsigned long 4 bytes 0 to 4,294,967,295

To get the exact size of a type or a variable on a particular platform, you can use the
sizeof operator. The expressions sizeof(type) yields the storage size of the object or
type in bytes. Given below is an example to get the size of int type on any machine −
#include <stdio.h>
#include <limits.h>
int main() {
printf("Storage size for int : %d \n", sizeof(int));
return 0;
}
When you compile and execute the above program, it produces the following result
on Linux −
Storage size for int : 4

Floating-Point Types
The following table provide the details of standard floating-point types with storage
sizes and value ranges and their precision −

Type Storage size Value range Precision

float 4 byte 1.2E-38 to 3.4E+38 6 decimal places

double 8 byte 2.3E-308 to 1.7E+308 15 decimal places

long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places

The header file float.h defines macros that allow you to use these values and other
details about the binary representation of real numbers in your programs. The
following example prints the storage space taken by a float type and its range values

#include <stdio.h>
#include <float.h>
int main() {
printf("Storage size for float : %d \n", sizeof(float));
printf("Minimum float positive value: %E\n", FLT_MIN );
printf("Maximum float positive value: %E\n", FLT_MAX );
printf("Precision value: %d\n", FLT_DIG );
return 0;
}
When you compile and execute the above program, it produces the following result
on Linux −
Storage size for float : 4
Minimum float positive value: 1.175494E-38
Maximum float positive value: 3.402823E+38
Precision value: 6

The void Type


The void type specifies that no value is available. It is used in three kinds of
situations −
Sr.No. Types & Description

1 Function returns as void


There are various functions in C which do not return any value or
you can say they return void. A function with no return value has the
return type as void. For example, void exit (int status);

2 Function arguments as void


There are various functions in C which do not accept any parameter.
A function with no parameter can accept a void. For example, int
rand(void);

3 Pointers to void
A pointer of type void * represents the address of an object, but not
its type. For example, a memory allocation function void
*malloc( size_t size ); returns a pointer to void which can be casted
to any data type.

A variable is nothing but a name given to a storage area that our programs can
manipulate. Each variable in C has a specific type, which determines the size and
layout of the variable's memory; the range of values that can be stored within that
memory; and the set of operations that can be applied to the variable.

The name of a variable can be composed of letters, digits, and the underscore
character. It must begin with either a letter or an underscore. Upper and lowercase
letters are distinct because C is case-sensitive. Based on the basic types explained in
the previous chapter, there will be the following basic variable types −
Sr.No. Type & Description
1 char
Typically a single octet(one byte). This is an integer type.

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

3 float
A single-precision floating point value.

4 double
A double-precision floating point value.

5 void
Represents the absence of type.

C programming language also allows to define various other types of variables,


which we will cover in subsequent chapters like Enumeration, Pointer, Array,
Structure, Union, etc. For this chapter, let us study only basic variable types.

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

Variable Declaration in C
A variable declaration provides assurance to the compiler that there exists a variable
with the given type and name so that the compiler can proceed for further
compilation without requiring the complete detail about the variable. A variable
definition has its meaning at the time of compilation only, the compiler needs actual
variable definition at the time of linking the program.

A variable declaration is useful when you are using multiple files and you define
your variable in one of the files which will be available at the time of linking of the
program. You will use the keyword extern to declare a variable at any place. Though
you can declare a variable multiple times in your C program, it can be defined only
once in a file, a function, or a block of code.

Example
Try the following example, where variables have been declared at the top, but they
have been defined and initialized inside the main function −
#include <stdio.h>

// Variable declaration:
extern int a, b;
extern int c;
extern float f;

int main () {

/* variable definition: */
int a, b;
int c;
float f;

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

c = a + b;
printf("value of c : %d \n", c);

f = 70.0/3.0;
printf("value of f : %f \n", f);

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

value of c : 30
value of f : 23.333334
The same concept applies on function declaration where you provide a function name
at the time of its declaration and its actual definition can be given anywhere else. For
example −

// function declaration
int func();

int main() {

// function call
int i = func();
}

// function definition
int func() {
return 0;
}

Lvalues and Rvalues in C


There are two kinds of expressions in C −

lvalue − Expressions that refer to a memory location are called "lvalue" expressions.
An lvalue may appear as either the left-hand or right-hand side of an assignment.

rvalue − The term rvalue refers to a data value that is stored at some address in
memory. An rvalue is an expression that cannot have a value assigned to it which
means an rvalue may appear on the right-hand side but not on the left-hand side of an
assignment.

Variables are lvalues and so they may appear on the left-hand side of an assignment.
Numeric literals are rvalues and so they may not be assigned and cannot appear on
the left-hand side. Take a look at the following valid and invalid statements −

int g = 20; // valid statement

10 = 20; // invalid statement; would generate compile-time error

Storage Classes
A storage class defines the scope (visibility) and life-time of variables and/or
functions within a C Program. They precede the type that they modify. We have four
different storage classes in a C program −
auto
register
static
extern
The auto Storage Class
The auto storage class is the default storage class for all local variables.

{
int mount;
auto int month;
}
The example above defines two variables with in the same storage class. 'auto' can
only be used within functions, i.e., local variables.

The register Storage Class


The register storage class is used to define local variables that should be stored in a
register instead of RAM. This means that the variable has a maximum size equal to
the register size (usually one word) and can't have the unary '&' operator applied to it
(as it does not have a memory location).

{
register int miles;
}
The register should only be used for variables that require quick access such as
counters. It should also be noted that defining 'register' does not mean that the
variable will be stored in a register. It means that it MIGHT be stored in a register
depending on hardware and implementation restrictions.

The static Storage Class


The static storage class instructs the compiler to keep a local variable in existence
during the life-time of the program instead of creating and destroying it each time it
comes into and goes out of scope. Therefore, making local variables static allows
them to maintain their values between function calls.

The static modifier may also be applied to global variables. When this is done, it
causes that variable's scope to be restricted to the file in which it is declared.

In C programming, when static is used on a global variable, it causes only one copy
of that member to be shared by all the objects of its class.
#include <stdio.h>

/* function declaration */
void func(void);

static int count = 5; /* global variable */


main() {

while(count--) {
func();
}

return 0;
}

/* function definition */
void func( void ) {

static int i = 5; /* local static variable */


i++;

printf("i is %d and count is %d\n", i, count);


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

i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0

The extern Storage Class


The extern storage class is used to give a reference of a global variable that is visible
to ALL the program files. When you use 'extern', the variable cannot be initialized
however, it points the variable name at a storage location that has been previously
defined.

When you have multiple files and you define a global variable or function, which
will also be used in other files, then extern will be used in another file to provide the
reference of defined variable or function. Just for understanding, extern is used to
declare a global variable or function in another file.

The extern modifier is most commonly used when there are two or more files sharing
the same global variables or functions as explained below.

First File: main.c

#include <stdio.h>

int count ;
extern void write_extern();
main() {
count = 5;
write_extern();
}
Second File: support.c

#include <stdio.h>

extern int count;

void write_extern(void) {
printf("count is %d\n", count);
}
Here, extern is being used to declare count in the second file, where as it has its
definition in the first file, main.c. Now, compile these two files as follows −

$gcc main.c support.c


It will produce the executable program a.out. When this program is executed, it
produces the following result −

count is 5

Constants
Constants refer to fixed values that the program may not alter during its execution.
These fixed values are also called literals.

Constants can be of any of the basic data types like an integer constant, a floating
constant, a character constant, or a string literal. There are enumeration constants as
well.

Constants are treated just like regular variables except that their values cannot be
modified after their definition.

Integer Literals
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies
the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.

An integer literal can also have a suffix that is a combination of U and L, for
unsigned and long, respectively. The suffix can be uppercase or lowercase and can be
in any order.

Here are some examples of integer literals −

212 /* Legal */
215u /* Legal */
0xFeeL /* Legal */
078 /* Illegal: 8 is not an octal digit */
032UU /* Illegal: cannot repeat a suffix */
Following are other examples of various types of integer literals −

85 /* decimal */
0213 /* octal */
0x4b /* hexadecimal */
30 /* int */
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */
Floating-point Literals
A floating-point literal has an integer part, a decimal point, a fractional part, and an
exponent part. You can represent floating point literals either in decimal form or
exponential form.

While representing decimal form, you must include the decimal point, the exponent,
or both; and while representing exponential form, you must include the integer part,
the fractional part, or both. The signed exponent is introduced by e or E.

Here are some examples of floating-point literals −

3.14159 /* Legal */
314159E-5L /* Legal */
510E /* Illegal: incomplete exponent */
210f /* Illegal: no decimal or exponent */
.e55 /* Illegal: missing integer or fraction */
Character Constants
Character literals are enclosed in single quotes, e.g., 'x' can be stored in a simple
variable of char type.

A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or
a universal character (e.g., '\u02C0').

There are certain characters in C that represent special meaning when preceded by a
backslash for example, newline (\n) or tab (\t).

Here, you have a list of such escape sequence codes −


Following is the example to show a few escape sequence characters −

#include <stdio.h>

int main() {
printf("Hello\tWorld\n\n");
return 0;
}
When the above code is compiled and executed, it produces the following result −
Hello World

String Literals
String literals or constants are enclosed in double quotes "". A string contains
characters that are similar to character literals: plain characters, escape sequences,
and universal characters.

You can break a long line into multiple lines using string literals and separating them
using white spaces.

Here are some examples of string literals. All the three forms are identical strings.

"hello, dear"

"hello, \

dear"

"hello, " "d" "ear"

Defining Constants
There are two simple ways in C to define constants −

Using #define preprocessor.

Using const keyword.

The #define Preprocessor


Given below is the form to use #define preprocessor to define a constant −

#define identifier value


The following example explains it in detail −

#include <stdio.h>

#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'

int main() {
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);

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

value of area : 50

The const Keyword


You can use const prefix to declare constants with a specific type as follows −

const type variable = value;


The following example explains it in detail −

#include <stdio.h>

int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;

area = LENGTH * WIDTH;


printf("value of area : %d", area);
printf("%c", NEWLINE);

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

value of area : 50
Note that it is a good programming practice to define constants in CAPITALS.

Enumeration Constants
An enumeration is a user-defined data type that consists of integral constants. To
define an enumeration, keyword enum is used.

enum flag { const1, const2, ..., constN };


Here, name of the enumeration is flag.

And, const1, const2,...., constN are values of type flag.

By default, const1 is 0, const2 is 1 and so on. You can change default values of
enum elements during declaration (if necessary).
// Changing default values of enum
enum suit {
club = 0,
diamonds = 10,
hearts = 20,
spades = 3,
};
Enumerated Type Declaration
When you create an enumerated type, only blueprint for the variable is created.
Here's how you can create variables of enum type.

enum boolean { false, true };


enum boolean check;
Here, a variable check of type enum boolean is created.

Here is another way to declare same check variable using different syntax.

enum boolean
{
false, true
} check;

Example: Enumeration Type


#include <stdio.h>

enum week { sunday, monday, tuesday, wednesday, thursday, friday, saturday };

int main()
{
enum week today;
today = wednesday;
printf("Day %d",today+1);
return 0;
}
Output

Day 4
Why enums are used in C programming?
Enum variable takes only one value out of many possible values. Example to
demonstrate it,

#include <stdio.h>

enum suit {
club = 0,
diamonds = 10,
hearts = 20,
spades = 3
} card;

int main()
{
card = club;
printf("Size of enum variable = %d bytes", sizeof(card));
return 0;
}
Output

Size of enum variable = 4 bytes


It's because the size of an integer is 4 bytes.

This makes enum a good choice to work with flags.

You can accomplish the same task using structures. However, working with enums
gives you efficiency along with flexibility.

How to use enums for flags?


Let us take an example,

enum designFlags {
ITALICS = 1,
BOLD = 2,
UNDERLINE = 4
} button;
Suppose you are designing a button for Windows application. You can set flags
ITALICS, BOLD and UNDERLINE to work with text.

There is a reason why all the integral constants are power of 2 in above pseudocode.

// In binary

ITALICS = 00000001
BOLD = 00000010
UNDERLINE = 00000100
Since, the integral constants are power of 2, you can combine two or more flags at
once without overlapping using bitwise OR | operator. This allows you to choose two
or more flags at once. For example,

#include <stdio.h>
enum designFlags {
BOLD = 1,
ITALICS = 2,
UNDERLINE = 4
};

int main() {
int myDesign = BOLD | UNDERLINE;

// 00000001
// | 00000100
// ___________
// 00000101

printf("%d", myDesign);

return 0;
}
Output

5
When the output is 5, you always know that bold and underline is used.

Also, you can add flag to your requirements.

if (myDesign & ITALICS) {


// code for italics
}
Here, we have added italics to our design. Note, only code for italics is written inside
if statement.

You can accomplish almost anything in C programming without using enumerations.


However, they can be pretty handy in certain situations. That's what differentiates
good programmers from great programmers.

Keywords
Keywords in C Programming

auto break case char

const continue default do

double else enum extern


Keywords in C Programming

float for goto if

int long register return

short signed sizeof static

struct switch typedef union

unsigned void volatile while

Description of all Keywords in C

auto
The auto keyword declares automatic variables. For example:

auto int var1;


This statement suggests that var1 is a variable of storage class auto and type int.

Variables declared within function bodies are automatic by default. They are
recreated each time a function is executed.

Since, automatic variables are local to a function, they are also called local variables.

break and continue


The break statement makes program jump out of the innermost enclosing loop
(while, do, for or switch statements) explicitly.

The continue statement skips the certain statements inside the loop.

for (i=1;i<=10;++i)
{
if (i==3)
continue;
if (i==7)
break;
printf("%d ",i);
}

Output

12456
When i is equal to 3, continue statement comes into effect and skips 3. When i is
equal to 7, break statement comes into effect and terminates the for loop.

switch, case and default


The switch and case statement is used when a block of statements has to be executed
among many blocks. For example:

switch(expression)
{
case '1':
//some statements to execute when 1
break;
case '5':
//some statements to execute when 5
break;
default:
//some statements to execute when default;
}

char
The char keyword declares a character variable. For example:

char alphabet;
Here, alphabet is a character type variable.

const
An identifier can be declared constant by using const keyword.

const int a = 5;

do...while
int i;
do
{
print("%d ",i);
i++;
}
while (i<10)

double and float


Keywords double and float are used for declaring floating type variables. For
example:

float number;
double longNumber;
Here, number is single precision floating type variable whereas, longNumber is a
double precision floating type variable.

if and else
In C programming, if and else are used to make decisions.

if (i == 1)
printf("i is 1.")
else
prinf("i is not 1.")
If value of i is other than 1, output will be :

i is not 1

enum
Enumeration types are declared in C programming using keyword enum. For
example:

enum suit
{
hearts;
spades;
clubs;
diamonds;
};
Here, a enumerated variable suit is created having tags: hearts, spades, clubs and
diamonds.

extern
The extern keyword declares that a variable or a function has external linkage outside
of the file it is declared.

for
There are three types of loops in C programming. The for loop is written in C
programming using keyword for. For example:

for (i=0; i< 9;++i)


{
printf("%d ",i);
}
Output

012345678
goto
The goto keyword is used for unconditional jump to a labeled statement inside a
function. For example:
for(i=1; i<5; ++i)
{
if (i==10)
goto error;
}
printf("i is not 10");
error:
printf("Error, count cannot be 10.");
Output

Error, count cannot be 10.

int
The int keyword declares integer type variable. For example:

int count;
Here, count is a integer variable.

short, long, signed and unsigned


The short, long, signed and unsigned keywodrs are type modifiers that alters the
meaning of a base data type to yield a new type.

short int smallInteger;


long int bigInteger;
signed int normalInteger;
unsigned int positiveInteger;
Range of int type data types
Data types Range
short int -32768 to 32767
long int -2147483648 to 214743648
signed int -32768 to 32767
unsigned int 0 to 65535

return
The return keyword terminates the function and returns the value.

int func()
{
int b = 5;
return b;
}
This function func() returns 5 to the calling function.

sizeof
The sizeof keyword evaluates the size of data (a variable or a constant).

#include <stdio.h>
int main()
{
printf("%u bytes.",sizeof(char));
}

Output

1 bytes.

register
The register keyword creates register variables which are much faster than normal
variables.

register int var1;

static
The static keyword creates static variable. The value of the static variables persists
until the end of the program. For example:

static int var;

struct
The struct keyword is used for declaring a structure. A structure can hold variables of
different types under a single name.

struct student{
char name[80];
float marks;
int age;
}s1, s2;

typedef
The typedef keyword is used to explicitly associate a type with an identifier.

typedef float kg;


kg bear, tiger;

union
A Union is used for grouping different types of variable under a single name.

union student
{
char name[80];
float marks;
int age;
}

void
The void keyword indicates that a function doesn't return any value.

void testFunction(int a)
{
.....
}
Here, function testFunction( ) cannot return a value because the return type is void.

volatile
The volatile keyword is used for creating volatile objects. A volatile object can be
modified in an unspecified way by the hardware.

const volatile number


Here, number is a volatile object.

Since, number is a constant variable, the program cannot change it. However,
hardware can change it since it is a volatile object.

Opeartors: Precedence and Associativity


An operator is a symbol that tells the compiler to perform specific mathematical or
logical functions. C language is rich in built-in operators and provides the following
types of operators −

Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
We will, in this chapter, look into the way each operator works.

Arithmetic Operators
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 B%A=0


an integer division.

++ Increment operator increases the integer A++ = 11


value by one.

-- Decrement operator decreases the integer A-- = 9


value by one.

Try the following example to understand all the arithmetic operators available in C −

Live Demo
#include <stdio.h>

main() {

int a = 21;
int b = 10;
int c ;

c = a + b;
printf("Line 1 - Value of c is %d\n", c );

c = a - b;
printf("Line 2 - Value of c is %d\n", c );

c = a * b;
printf("Line 3 - Value of c is %d\n", c );

c = a / b;
printf("Line 4 - Value of c is %d\n", c );

c = a % b;
printf("Line 5 - Value of c is %d\n", c );

c = a++;
printf("Line 6 - Value of c is %d\n", c );

c = a--;
printf("Line 7 - Value of c is %d\n", c );
}
When you compile and execute the above program, it produces the following result −
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 21
Line 7 - Value of c is 22

Relational Operators
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 values of two operands are (A == B) is not true.


equal or not. If yes, then the condition
becomes true.

!= Checks if the values of two operands are (A != B) is true.


equal or not. If the values are not equal,
then the condition becomes true.

> Checks if the value of left operand is (A > B) is not true.


greater than the value of right operand. If
yes, then the condition becomes true.

< Checks if the value of left operand is less (A < B) is true.


than the value of right operand. If yes,
then the condition becomes true.

>= Checks if the value of left operand is (A >= B) is not true.


greater than or equal to the value of right
operand. If yes, then the condition
becomes true.

<= Checks if the value of left operand is less (A <= B) is true.


than or equal to the value of right
operand. If yes, then the condition
becomes true.

Example
Try the following example to understand all the relational operators available in C −

Live Demo
#include <stdio.h>

main() {
int a = 21;
int b = 10;
int c ;

if( a == b ) {
printf("Line 1 - a is equal to b\n" );
} else {
printf("Line 1 - a is not equal to b\n" );
}

if ( a < b ) {
printf("Line 2 - a is less than b\n" );
} else {
printf("Line 2 - a is not less than b\n" );
}

if ( a > b ) {
printf("Line 3 - a is greater than b\n" );
} else {
printf("Line 3 - a is not greater than b\n" );
}

/* Lets change value of a and b */


a = 5;
b = 20;

if ( a <= b ) {
printf("Line 4 - a is either less than or equal to b\n" );
}

if ( b >= a ) {
printf("Line 5 - b is either greater than or equal to b\n" );
}
}
When you compile and execute the above program, it produces the following result −

Line 1 - a is not equal to b


Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either less than or equal to b
Line 5 - b is either greater than or equal to b
Logical Operators
Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then −
Operator Description Example
&& Called Logical AND operator. If both the (A && B) is false.
operands are non-zero, then the condition
becomes true.

|| Called Logical OR Operator. If any of the (A || B) is true.


two operands is non-zero, then the
condition becomes true.

! Called Logical NOT Operator. It is used !(A && B) is true.


to reverse the logical state of its operand.
If a condition is true, then Logical NOT
operator will make it false.

Example
Try the following example to understand all the logical operators available in C −

Live Demo
#include <stdio.h>

main() {

int a = 5;
int b = 20;
int c ;

if ( a && b ) {
printf("Line 1 - Condition is true\n" );
}

if ( a || b ) {
printf("Line 2 - Condition is true\n" );
}

/* lets change the value of a and b */


a = 0;
b = 10;

if ( a && b ) {
printf("Line 3 - Condition is true\n" );
} else {
printf("Line 3 - Condition is not true\n" );
}

if ( !(a && b) ) {
printf("Line 4 - Condition is true\n" );
}

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

Line 1 - Condition is true


Line 2 - Condition is true
Line 3 - Condition is not true
Line 4 - Condition is true

Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for
&, |, and ^ is as follows −
p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

Assume A = 60 and B = 13 in binary format, they will be as follows −

A = 0011 1100

B = 0000 1101

-----------------

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A = 1100 0011

The following table lists the bitwise operators supported by C. Assume variable 'A'
holds 60 and variable 'B' holds 13, then −
Operator Description Example

& Binary AND Operator copies a bit to the (A & B) = 12, i.e.,
result if it exists in both operands. 0000 1100
| Binary OR Operator copies a bit if it (A | B) = 61, i.e.,
exists in either operand. 0011 1101

^ Binary XOR Operator copies the bit if it (A ^ B) = 49, i.e.,


is set in one operand but not both. 0011 0001

~ (~A ) = -60, i.e,. 1100


Binary Ones Complement Operator is
0100 in 2's
unary and has the effect of 'flipping' bits.
complement form.

<< Binary Left Shift Operator. The left


operands value is moved left by the A << 2 = 240 i.e.,
number of bits specified by the right 1111 0000
operand.

>> Binary Right Shift Operator. The left


operands value is moved right by the A >> 2 = 15 i.e.,
number of bits specified by the right 0000 1111
operand.

Example
Try the following example to understand all the bitwise operators available in C −
#include <stdio.h>

main() {

unsigned int a = 60; /* 60 = 0011 1100 */


unsigned int b = 13; /* 13 = 0000 1101 */
int c = 0;

c = a & b; /* 12 = 0000 1100 */


printf("Line 1 - Value of c is %d\n", c );

c = a | b; /* 61 = 0011 1101 */
printf("Line 2 - Value of c is %d\n", c );

c = a ^ b; /* 49 = 0011 0001 */
printf("Line 3 - Value of c is %d\n", c );

c = ~a; /*-61 = 1100 0011 */


printf("Line 4 - Value of c is %d\n", c );

c = a << 2; /* 240 = 1111 0000 */


printf("Line 5 - Value of c is %d\n", c );
c = a >> 2; /* 15 = 0000 1111 */
printf("Line 6 - Value of c is %d\n", c );
}
When you compile and execute the above program, it produces the following result −

Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15

Assignment Operators
The following table lists the assignment operators supported by the C language −
Operator Description Example

= Simple assignment operator. Assigns C = A + B will assign


values from right side operands to left the value of A + B to
side operand C

+= Add AND assignment operator. It adds


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

-= Subtract AND assignment operator. It


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

*= Multiply AND assignment operator. It


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

/= Divide AND assignment operator. It


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

%= Modulus AND assignment operator. It


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

<<= 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 C ^= 2 is same as C =


operator. C^2

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


operator. C|2

Example
Try the following example to understand all the assignment operators available in C

#include <stdio.h>

main() {

int a = 21;
int c ;

c = a;
printf("Line 1 - = Operator Example, Value of c = %d\n", c );

c += a;
printf("Line 2 - += Operator Example, Value of c = %d\n", c );

c -= a;
printf("Line 3 - -= Operator Example, Value of c = %d\n", c );

c *= a;
printf("Line 4 - *= Operator Example, Value of c = %d\n", c );

c /= a;
printf("Line 5 - /= Operator Example, Value of c = %d\n", c );

c = 200;
c %= a;
printf("Line 6 - %= Operator Example, Value of c = %d\n", c );

c <<= 2;
printf("Line 7 - <<= Operator Example, Value of c = %d\n", c );

c >>= 2;
printf("Line 8 - >>= Operator Example, Value of c = %d\n", c );

c &= 2;
printf("Line 9 - &= Operator Example, Value of c = %d\n", c );

c ^= 2;
printf("Line 10 - ^= Operator Example, Value of c = %d\n", c );

c |= 2;
printf("Line 11 - |= Operator Example, Value of c = %d\n", c );
}
When you compile and execute the above program, it produces the following result −

Line 1 - = Operator Example, Value of c = 21


Line 2 - += Operator Example, Value of c = 42
Line 3 - -= Operator Example, Value of c = 21
Line 4 - *= Operator Example, Value of c = 441
Line 5 - /= Operator Example, Value of c = 21
Line 6 - %= Operator Example, Value of c = 11
Line 7 - <<= Operator Example, Value of c = 44
Line 8 - >>= Operator Example, Value of c = 11
Line 9 - &= Operator Example, Value of c = 2
Line 10 - ^= Operator Example, Value of c = 0
Line 11 - |= Operator Example, Value of c = 2

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

sizeof() sizeof(a), where a is integer,


Returns the size of a variable.
will return 4.

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


variable. of the variable.

* Pointer to a variable. *a;

?: If Condition is true ? then value


Conditional Expression.
X : otherwise value Y

Example
Try following example to understand all the miscellaneous operators available in C −
#include <stdio.h>

main() {

int a = 4;
short b;
double c;
int* ptr;

/* example of sizeof operator */


printf("Line 1 - Size of variable a = %d\n", sizeof(a) );
printf("Line 2 - Size of variable b = %d\n", sizeof(b) );
printf("Line 3 - Size of variable c= %d\n", sizeof(c) );

/* example of & and * operators */


ptr = &a;/* 'ptr' now contains the address of 'a'*/
printf("value of a is %d\n", a);
printf("*ptr is %d.\n", *ptr);

/* example of ternary operator */


a = 10;
b = (a == 1) ? 20: 30;
printf( "Value of b is %d\n", b );

b = (a == 10) ? 20: 30;


printf( "Value of b is %d\n", b );
}
When you compile and execute the above program, it produces the following result −

Line 1 - Size of variable a = 4


Line 2 - Size of variable b = 2
Line 3 - Size of variable c= 8
value of a is 4
*ptr is 4.
Value of b is 30
Value of b is 20

Operators Precedence in C
Operator precedence determines the grouping of terms in an expression and decides
how an expression is evaluated. Certain operators have higher precedence than
others; for example, the multiplication operator has a higher precedence than the
addition operator.

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


higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with
the lowest appear at the bottom. Within an expression, higher precedence operators
will be evaluated first.

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

Example
Try the following example to understand operator precedence in C −

#include <stdio.h>

main() {

int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;

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

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

e = (a + b) * (c / d); // (30) * (15/5)


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

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

return 0;
}
When you compile and execute the above program, it produces the following result −

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

Expressions
In programming, an expression is any legal combination of symbols that represents a
value.
C Programming Provides its own rules of Expression, whether it is legal expression
or illegal expression. For example, in the C language x+5 is a legal expression.
Every expression consists of at least one operand and can have one or more
operators.
Operands are values and Operators are symbols that represent particular actions.

Valid C Programming Expression :


C Programming code gets compiled firstly before execution. In the different phases
of compiler, c programming expression is checked for its validity.

Expressions Validity

Expression is valid since it contain + operator which is


a+b
binary operator

++a+b Invalid Expression

Types of Expression :
In Programming, different verities of expressions are given to the compiler.
Expressions can be classified on the basis of Position of Operators in an expression –

Type Explanation Example

Expression in which Operator is in between


Infix a+b
Operands

Expression in which Operator is written before


Prefix +ab
Operands

Expression in which Operator is written after


Postfix ab+
Operands

These expressions are solved using the stack.

Examples of Expression :
Now we will be looking into some of the C Programming Expressions, Expression
can be created by combining the operators and operands

Each of the expression results into the some resultant output value. Consider few
expressions in below table

Expression Examples,Explanation
n1 + n2,This is an expression which is going to add two numbers and we can assign
the result of addition to another variable.
x = y,This is an expression which assigns the value of right hand side operand to left
side variable
v = u + a * t,We are multiplying two numbers and result is added to ‘u’ and total
result is assigned to v
x <= y,This expression will return Boolean value because comparison operator will
give us output either true or false ++j,This is expression having pre increment
operator\, it is used to increment the value of j before using it in expression [/table]

What is L-Value of Expression ?

1. L-Value stands for left value


2. L-Value of Expressions refer to a memory locations
3. In any assignment statement L-Value of Expression must be a container(i.e.
must have ability to hold the data)
4. Variable is the only container in C programming thus L Value must be any
Variable.
5. L Value Cannot be Constant,Function or any of the available data type in C
Diagram Showing L-Value of Expression :

Example of L-Value of Expression :

#include<stdio.h>
int main(){
int num;
num = 5;return(0);}

In the above expression, Constant value 5 is being assigned to a variable ‘num’.


Variable ‘num’ is called as storage region’s , ‘num’ can considered as LValue of an
expression.
Re-commanded Concepts : Concept of Variables and Constants in C
Important Tips :

Below are some of the tips which are useful to make your concept about L-Value of
Expression more clear.
Lvalue cannot be a Constant

int main(){int num;


5 = num; //Error
return(0);}

You cannot assign the value or any constant value to another constant value because
meaning of constant is already defined and it cannot be modified.
Lvalue cannot be a Constant Variable
Even we cannot assign a value to a constant variable. Constant variable should not be
used as L Value.

int main(){const num;


num = 20; //Errorreturn(0);}

Lvalue cannot be a MACRO

We know that macros gets expanded before processing source code by compiler. All
the macros will be replaced by defined value using pre-processor before compiling
program.

#define MAX 20int main(){


MAX = 20; //Errorreturn(0);}

pre-processor will replace all the occurances of macros and hand over modified
source code to compiler. following code will be given to compiler after doing pre-
processor task

#define MAX 20
int main(){20 = 20;return(0);}

Re-commanded Reading : Preprocessor macro


Lvalue cannot be a Enum Constant

enum {JAN,FEB,MARCH};int main(){


JAN = 20; //Errorreturn(0);}

Lvalue cannot be a Data Type

#define<stdio.h>#define max 125struct book{


char *name;
int pages;};void main(){
book = {"C Programming",100};}

L-Value Require error ?

Causes of Error :

1. Whenever we are trying to assign value to constant value


2. Whenever we are trying to increment or decrement Constant Expression
3. Inside if statement , if we try to write comparison operator as “= =” instead of
“==”, then we will get this error.

Solution :
Solution to this problem is very simple –

1. Always try to assign constant value to “Variable“.


2. If you are using comparison operator then we don’t provide space in between
operators.

In the next chapter we will be learning RValue of an expression which is also called


as right value of an expression.

What is R-Value of Expression ?

1. R Value stands for Right value of the expression.


2. In any Assignment statement R-Value of Expression must be anything which
is capable of returning Constant Expression or Constant Value.
3. R Value Can be anything of following –

Examples of R-Value of Expression

Variable Constant

Function Macro

Enum Constant Any other data type


Diagram Showing Lvalue :

Example of R-Value of Expression

#include<stdio.h>
int main(){int num;
num = 5;
return(0);}

In the above example, Constant Value 5 is assigned to the variable will be considered
as right Value of the variable.
Tips : R-Value of Expression
Tip 1 : R value may be constant or constant expression

num = 20; //Constant RValue


num = 20 + 20; //Constant Expression as RValue

1. In the example, we have assigned constant value to the variable.


2. Constant value “20” is considered as RValue.
3. In the next line we have assigned constant expression to the variable. “20 +
20” will be evaluated first and then result of expression will be assigned to an
Variable.

Tip 2 : R value may be MACRO


#define MAX 20main() {
int num = MAX;}

If we have defined a MACRO then we can use MACRO as right value. In the above
example we have assigned the 20 to the variable “num”.
In case if we defined the MACRO value of different data type then it may results into
compile error.
Tip 3 : R Value may be variable

#define MAX 20main() {


int flag = 0;
int num = flag;}

Input/Output Statements
There are some library functions which are available for transferring the information
between the computer and the standard input and output devices.
These functions are related to the symbolic constants and are available in the header
file.

Some of the input and output functions are as follows:

i) printf
This function is used for displaying the output on the screen i.e the data is moved
from the computer memory to the output device. 

Syntax:
printf(“format string”, arg1, arg2, …..);

In the above syntax, 'format string' will contain the information that is formatted.
They are the general characters which will be displayed as they are .
arg1, arg2 are the output data items.

Example: Demonstrating the printf function


printf(“Enter a value:”);

 printf will generally examine from left to right of the string.


 The characters are displayed on the screen in the manner they are encountered
until it comes across % or \.
 Once it comes across the conversion specifiers it will take the first argument
and print it in the format given.
ii) scanf
scanf is used when we enter data by using an input device.

Syntax:
scanf (“format string”, &arg1, &arg2, …..);

The number of items which are successful are returned.

Format string consists of the conversion specifier. Arguments can be variables or


array name and represent the address of the variable. Each variable must be preceded
by an ampersand (&). Array names should never begin with an ampersand. 

Example: Demonstrating scanf
int avg;
float per;
char grade;
scanf(“%d %f %c”,&avg, &per, &grade):

 scanf works totally opposite to printf. The input is read, interpret using the


conversion specifier and stores it in the given variable.
 The conversion specifier for scanf is the same as printf.
 scanf reads the characters from the input as long as the characters match or it
will terminate. The order of the characters that are entered are not important.
 It requires an enter key in order to accept an input.
iii) getch 
This function is used to input a single character. The character is read instantly and it
does not require an enter key to be pressed. The character type is returned but it does
not echo on the screen.

Syntax:
int getch(void);
ch=getch();

where,
ch - assigned the character that is returned by getch.

iv) putch
this function is a counterpart of getch. Which means that it will display a single
character on the screen. The character that is displayed is returned.

Syntax:
int putch(int);
putch(ch);
where,
ch - the character that is to be printed.

v) getche 
This function is used to input a single character. The main difference between getch
and getche is that getche displays the (echoes) the character that we type on the
screen.

Syntax:
int getch(void);
ch=getche();

vi) getchar
This function is used to input a single character. The enter key is pressed which is
followed by the character that is typed. The character that is entered is echoed.

Syntax:
ch=getchar;

vii) putchar
This function is the other side of getchar. A single character is displayed on the
screen.

Syntax:
putchar(ch);

viii) gets and puts


They help in transferring the strings between the computer and the standard input-
output devices. Only single arguments are accepted. The arguments must be such that
it represents a string. It may include white space characters. If gets is used enter key
has to be pressed for ending the string. The gets and puts function are used to offer
simple alternatives of scanf and printf for reading and displaying.

Example:

#include <stdio.h>
void main()
{
    char line[30];
    gets (line);
    puts (line);
}

Assignment Statements
The assignment statement has the following form:
variable = expression
Its purpose is saving the result of the expression to the right of the assignment
operator to the variable on the left. Here are some rules:
The expression is evaluated first with the rules discussed in the single mode or the
mixed mode expressions pages.
If the type of the expression is identical to that of the variable, the result is saved in
the variable.
Otherwise, the result is converted to the type of the variable and saved there.
If the type of the variable is INTEGER while the type of the result is REAL, the
fractional part, including the decimal point, is removed making it an integer result.
If the type of the variable is REAL while the type of the result is INTEGER, then a
decimal point is appended to the integer making it a real number.
Once the variable receives a new value, the original one disappears and is no more
available.
CHARACTER assignment follows the rules stated in the discussion of the
PARAMETER attribute.

Examples:
The program segment below declares three INTEGER variables. The first
assignment statement saves an integer value to variable Unit. The second saves a real
number 100.99 into variable Amount. However, since Amount is an INTEGER
variable, the real value 100.99 is converted to an integer, 100, and saved into
Amount. Thus, after the second assignment completes, variable Amount holds 100.
The third assignment computes the single mode expression, yielding a result 500 =
5*100. Thus, variable Total receives 500.
INTEGER :: Total, Amount, Unit

Unit = 5
Amount = 100.99
Total = Unit * Amount
In the following, PI is a PARAMETER and is an alias of 3.1415926. The first
assignment statement puts integer value 5 into integer variable Radius. The
expression in the second assignment is first evaluated, yielding a result 78.539815,
which is then saved into REAL variable Area.
REAL, PARAMETER :: PI = 3.1415926
REAL :: Area
INTEGER :: Radius

Radius = 5
Area = (Radius ** 2) * PI
In the following, Counter is an INTEGER variable initialized to zero.
The meaning of the first assignment is computing the sum of the value in Counter
and 1, and saves it back to Counter. Since Counter's current value is zero, Counter +
1 is 1+0 = 1 and hence 1 is saved into Counter. Therefore, the new value of Counter
becomes 1 and its original value 0 disappears.

The second assignment statement computes the sum of Counter's current value and 3,
and saves the result back to Counter. Thus, the new value of Counter is 1+3=4.

INTEGER :: Counter = 0

Counter = Counter + 1
Counter = Counter + 3
The following swaps the values in A and B, with the help of C. That is, after
completing the following three assignment statements, A and B have 5 and 3,
respectively.
Initially, A and B are initialized to 3 and 5, respectively, while C is uninitialized. The
first assignment statement puts A's value into C, making A=3, B=5 and C=3.

The second assignment statements puts B's value into A. This destroys A's original
value 3. After this, A = 5, B = 5 and C = 3.

The third assignment statement puts C's value into B. This makes A=5, B=3 and
C=3. Therefore, the values in A and B are exchanged.

INTEGER :: A = 3, B = 5, C

C=A
A=B
B=C
The following is another possible solution; but, it uses one more variable.
INTEGER :: A = 3, B = 5, C, D

C=A
D=B
A=D
B=C

An Important Note:
A name declared with the PARAMETER attribute is an alias of a value and is not a
variable. Therefore, it cannot be used on the left-hand side of =, although it can be
used on the right-hand side. The following is wrong!
INTEGER, PARAMETER :: InchToCM = 2.54, factor = 123.45
INTEGER :: X = 15

InchToCM = factor * X

Decision making statements


Decision making is anticipation of conditions occurring while execution of the
program and specifying actions taken according to the conditions.
Decision structures evaluate multiple expressions which produce TRUE or FALSE
as outcome. You need to determine which action to take and which statements to
execute if outcome is TRUE or FALSE otherwise.
Following is the general form of a typical decision making structure found in most
of the programming languages −

Python programming language assumes any non-zero and non-null values as


TRUE, and if it is either zero or null, then it is assumed as FALSE value.
Python programming language provides following types of decision making
statements. Click the following links to check their detail.

Sr.No. Statement & Description

1 if statements
An if statement consists of a boolean expression followed by one or
more statements.

2 if...else statements
An if statement can be followed by an optional else statement,
which executes when the boolean expression is FALSE.

3 nested if statements
You can use one if or else if statement inside another if or else
ifstatement(s).
Let us go through each decision making briefly −
Single Statement Suites
If the suite of an if clause consists only of a single line, it may go on the same line as
the header statement.
Here is an example of a one-line if clause −

#!/usr/bin/python
var = 100if ( var == 100 ) : print "Value of expression is 100"print "Good bye!"

When the above code is executed, it produces the following result −


Value of expression is 100
Good bye!

You might also like