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

PWC Unit-1 Part-2 (Basics of Programming)

This document serves as an introduction to the basics of programming, specifically focusing on the C programming language. It covers the history, features, structure, and compiling process of C programs, as well as essential concepts such as data types, variables, operators, and keywords. The material is prepared for educational purposes by Mr. Viral H. Panchal at the Chhotubhai Gopalbhai Patel Institute of Technology, Bardoli.

Uploaded by

akbarikavya13
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

PWC Unit-1 Part-2 (Basics of Programming)

This document serves as an introduction to the basics of programming, specifically focusing on the C programming language. It covers the history, features, structure, and compiling process of C programs, as well as essential concepts such as data types, variables, operators, and keywords. The material is prepared for educational purposes by Mr. Viral H. Panchal at the Chhotubhai Gopalbhai Patel Institute of Technology, Bardoli.

Uploaded by

akbarikavya13
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

Chhotubhai Gopalbhai Patel Institute of


Technology, Bardoli

Subject
Basics of Logic Development

Unit – 2 (Part – 1)
Basics of Programming

Prepared by – Mr. Viral H. Panchal 1


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

CONTENTS
1. Introduction to Programming Language
1.1. History of C Language
1.2. Features (Characteristics) of C Language
2. Structure of a C Program
3. Compiling Process of a C Program
4. Character Set of C Language
5. C Tokens
6. Keywords
7. Identifiers
8. Constants
8.1. Integer Constants
8.2. Real Constants
8.3. Single Character Constants
8.4. String Literals or String Constants
8.5. Backslash Character Constants/Escape Sequences
9. Variables
9.1. Declaring a Variable
9.2. Initializing a Variable
10. Data Types
10.1. Primary or Fundamental Data Types
10.2. Derived Data Types
10.3. User-Defined Data Types
11. Creating Constants in C
11.1. const Keyword
11.2. #define Preprocessor Directive
11.3. const vs #define
11.4. volatile Keyword
12. Basic Input and Output in C
12.1. Reading Input from Keyboard
12.2. Printing onto Screen

Prepared by – Mr. Viral H. Panchal 2


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

13. Operators
13.1. Arithmetic Operators
13.2. Relational Operators
13.3. Logical Operators
13.4. Assignment Operators
13.5. Increment and Decrement Operators
13.6. Conditional Operator (Ternary Operator)
13.7. Bitwise Operators
13.8. Special Operators
14. Operator Precedence and Associativity
15. Type Conversion/Type Casting
15.1. Implicit Type Conversion
15.2. Explicit Type Conversion (Type Casting)
16. Basic C Programs

Prepared by – Mr. Viral H. Panchal 3


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

1. Introduction to Programming Language


Language is a mode of communication that is used to share ideas, opinions with
each other. For example, if we want to teach someone, we need a language that is
understandable by both communicators.
A programming language is a computer language that is used by programmers
(developers) to communicate with computers. It is a set of instructions written in any
specific language (C, C++, Java, Python) to perform a specific task.
C is a general-purpose programming language that is extremely popular, simple,
and flexible to use. It is a structured programming language that is machine-
independent and extensively used to write various applications, Operating Systems
like Windows, and many other complex programs like Oracle database, Python
interpreter, and more.
C is a base for the programming. If you know ‘C,’ you can easily grasp the
knowledge of the other programming languages that uses the concept of ‘C’.

1.1. History of C Language


The base or father of programming languages is ‘ALGOL.’ It was first introduced
in 1960. ‘ALGOL’ was used on a large basis in European countries. ‘ALGOL’
introduced the concept of structured programming to the developer community.
In 1967, a new computer programming language was announced called as ‘BCPL’
which stands for Basic Combined Programming Language. BCPL was designed and
developed by Martin Richards, especially for writing system software. This was the
era of programming languages.
Just after three years, in 1970 a new programming language called ‘B’ was
introduced by Ken Thompson that contained multiple features of ‘BCPL.’ This
programming language was created using UNIX operating system at AT&T and Bell
Laboratories. Both the ‘BCPL’ and ‘B’ were system programming languages.
In 1972, a great computer scientist Dennis Ritchie created a new programming
language called ‘C’ at the Bell Laboratories. It was created from ‘ALGOL’, ‘BCPL’
and ‘B’ programming languages. ‘C’ programming language contains all the features

Prepared by – Mr. Viral H. Panchal 4


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

of these languages and many more additional concepts that make it unique from
other languages.
‘C’ is a powerful programming language which is strongly associated with the
UNIX operating system. Even most of the UNIX operating system is coded in ‘C’.
Initially ‘C’ programming was limited to the UNIX operating system, but as it started
spreading around the world, it became commercial, and many compilers were
released for cross-platform systems.
Today ‘C’ runs under a variety of operating systems and hardware platforms. As
it started evolving many different versions of the language were released. At times it
became difficult for the developers to keep up with the latest version as the systems
were running under the older versions. To assure that ‘C’ language will remain
standard, American National Standards Institute (ANSI) defined a commercial
standard for ‘C’ language in 1989. Later, it was approved by the International
Standards Organization (ISO) in 1990. ‘C’ programming language is also called as
‘ANSI C’.
Table 2.1: History of C

Language Year Developed By

Algol 1960 International Group

BCPL 1967 Martin Richard

B 1970 Ken Thompson

Traditional C 1972 Dennis Ritchie

K&RC 1978 Kernighan & Dennis Ritchie

ANSI C 1989 ANSI Committee

ANSI/ISO C 1990 ISO Committee

C99 1999 Standardization Committee

Languages such as C++/Java are developed from ‘C’. These languages are
widely used in various technologies. Thus, ‘C’ forms a base for many other languages
that are currently in use.

Prepared by – Mr. Viral H. Panchal 5


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

1.2. Features (Characteristics) of C Language


C is the widely used language. It provides many features that are given below.
o Simple
o Machine Independent or Portable
o Mid-level programming language
o structured programming language
o Rich Library
o Memory Management
o Fast Speed
o Pointers
o Recursion
o Extensible

1. Simple - C is a simple language in the sense that it provides a structured


approach (to break the problem into parts), the rich set of library functions,
data types, etc.
2. Machine Independent or Portable - Unlike assembly language, c programs
can be executed on different machines with some machine specific changes.
Therefore, C is a machine independent language.
3. Mid-level programming language - Although, C is intended to do low-level
programming. It is used to develop system applications such as kernel, driver,
etc. It also supports the features of a high-level language. That is why it is
known as mid-level language.
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. Functions also provide code reusability.
5. Rich Library - C provides a lot of inbuilt functions that make 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.
7. Speed - The compilation and execution time of C language is fast since there
are lesser inbuilt functions and hence the lesser overhead.

Prepared by – Mr. Viral H. Panchal 6


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

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. Recursion enables us to use the approach of
backtracking.
10. Extensible - C language is extensible because it can easily adopt new
features.
2. Structure of a C Program

Figure 4.1: Structure of a C program

Every program written in C follows a certain structure. That structure is as shown in


figure 4.1.

• Documentation Section - The documentation section is used to improve the


readability and to understand various elements in the program. This section is
used to provide help for the general users. This section consists of plain text
written in English and includes information like author, purpose of the program,
date on which the program was created etc. This section is included inside
comments.
Prepared by – Mr. Viral H. Panchal 7
Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

Example –

/*********************************
* Author: Name
* Date: 7/10/2012
* Purpose: Theme of the program
********************************/

• Link Section - The link section is used to include the external header files in
which the pre-defined functions are available. To use the pre-defined functions
in our C programs, these files must be linked with our program. Files can be
included by using the “include” directive.
Example –

#include<stdio.h>

In the above example “stdio.h” is a header file which is available in the


system area in the programmer’s computer. The angular brackets “< and >”
tells the compiler to search the file “stdio.h” in the system area.
If we specify the above example as #include”stdio.h”, then the compiler
searches for the file “stdio.h” in the current directory.
• Definition Section - This section is used to define symbolic constants. Symbolic
constants can be declared by using the #define directive.
Example –
#define PI 3.142

• Global Declaration Section - This section is used for declaring global


variables which can be used throughout the program and for declaring
function prototypes. The global variables can be accessed by any function
within the file.
• main() Function Section - The main() function is necessary in every C program.
It specifies the starting point of execution in a program. There should be a
main() declared in every C program. The main() function consists of the
executable part and declaration part.
The Declaration part declares all the variables used in the executable
part. There is at least one statement in the executable part. These two parts

Prepared by – Mr. Viral H. Panchal 8


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

must appear between the opening and the closing braces. The main() function
may call other user defined functions.
• Subprogram section - It contains all the user-defined functions that are called
in the main functions. User-defined functions are generally placed immediately
after the main function, although they may appear in any order.

3. Compiling Process of a C Program

The compilation is a process of converting the source code into object code. It is
done with the help of the compiler. The compiler checks the source code for the
syntactical or structural errors, and if the source code is error-free, then it generates
the object code.
The c compilation process converts the source code taken as input into the object
code or machine code. The compilation process can be divided into four steps, i.e.,
Pre-processing, Compiling, Assembling, and Linking.
The preprocessor takes the source code as an input, and it removes all the
comments from the source code. The preprocessor takes the preprocessor directive
and interprets it. For example, if <stdio.h>, the directive is available in the program,
then the preprocessor interprets the directive and replace this directive with the
content of the 'stdio.h' file.
The following are the phases through which our program passes before being
transformed into an executable form:
o Preprocessor
o Compiler
o Assembler
o Linker

Prepared by – Mr. Viral H. Panchal 9


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

Figure 5.1: Phases of program compilation

• Preprocessor - The source code is the code which is written in a text editor and
the source code file is given an extension ".c". This source code is first passed
to the preprocessor, and then the preprocessor expands this code. After
expanding the code, the expanded code is passed to the compiler.
• Compiler - The code which is expanded by the preprocessor is passed to the
compiler. The compiler converts this code into assembly code. Or we can say
that the C compiler converts the pre-processed code into assembly code.
• Assembler - The assembly code is converted into object code by using an
assembler. The name of the object file generated by the assembler is the same
as the source file. The extension of the object file in DOS is '.obj,' and in UNIX,
the extension is 'o'. If the name of the source file is 'hello.c', then the name of
the object file would be 'hello.obj'.
• Linker - Mainly, all the programs written in C use library functions. These
library functions are pre-compiled, and the object code of these library files is
stored with '.lib' (or '.a') extension. The main working of the linker is to combine
the object code of library files with the object code of our program.
Sometimes the situation arises when our program refers to the functions
defined in other files; then linker plays a very important role in this. It links the
object code of these files to our program.

Prepared by – Mr. Viral H. Panchal 10


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

Therefore, we conclude that the job of the linker is to link the object
code of our program with the object code of the library files and other files.
The output of the linker is the executable file. The name of the executable file
is the same as the source file but differs only in their extensions. In DOS, the
extension of the executable file is '.exe', and in UNIX, the executable file can
be named as 'a.out'.

4. Character Set of C Language


The characters that can be used to form words, numbers and expressions
depend upon the computer on which the program is run. The characters in C, are
grouped into the following four categories:
1. Letters
2. Digits
3. Special Characters
4. Whitespaces
The compiler ignores the white spaces unless they are part of the string constants.
White spaces are used to separate words from each other, but they cannot be used
in between the characters of keywords and identifiers.

5. C Tokens

Figure 7.1: C tokens and examples

Prepared by – Mr. Viral H. Panchal 11


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

In a paragraph of text, individual words and punctuation marks are considered


as tokens. Likewise in a C program, the smallest individual units are known as C
tokens. C has six types of tokens as shown in figure 7.1. C programs are written using
these tokens and the syntax of the language.

6. Keywords
Every word used in a C program is classified as either a keyword or as an
identifier. A keyword in C is a reserved word which has a specific meaning.
Keywords in C cannot be used as identifiers. Keywords serve as the basic building
blocks for program statements.
Keywords in C are always in lowercase. ANSI C supports 32 keywords which are
listed in table 8.1.
Table 8.1: ANSI C Keywords
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

7. Identifiers
Identifiers refer to the names of variables, functions and arrays. These are user-
defined names and consist of sequence of letters and digits, with a letter as a first
character. Both uppercase and lowercase letters can be used, although lowercase
letters are generally used. The underscore character is also permitted in identifiers.

There are certain rules while writing identifiers. They are as follows:

o First character must be an alphabet or underscore.


o Must consist of only letters, digits or underscore.
o Only first 31 characters are significant.
Prepared by – Mr. Viral H. Panchal 12
Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

o Cannot use a keyword.


o Must not contain white space.
8. Constants
Constants are fixed values, which do not change during the execution of a
program. C supports several types of constants, which are as shown in figure 10.1.

Figure 10.1: Basic types of C constants

8.1. Integer Constants


An integer constant refers to a sequence of digits. Generally, in programs, the
number systems used are: decimal, octal and hexadecimal. Decimal integers
consist of numbers from 0 to 9, preceded by an optional + or – sign.

Some valid examples of decimal integer constants are 133, +45, -15, 0,
342332, etc. Embedded spaces and non-digit characters are cannot be used
between digits. For example, 34 983, 21,000, $500 are illegal numbers.

An octal integer consists of numbers from 0 to 7. Octal integer numbers are


always preceded by a zero. For example, if we have to represent 35 in octal
system, we must write it as 035 in the program. Some valid examples of octal
integer constants are 035, 02, 0435, +025, etc.

Prepared by – Mr. Viral H. Panchal 13


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

A hexadecimal integer consists of numbers from 0 to 9 and 10, 11, 12, 13, 14
and 15 are represented as A, B, C, D, E and F. Hexadecimal numbers are always
preceded by 0x or 0X. Some valid examples of hexadecimal integer constants
are 0x54, 0X23, +0x1F, -0X56 etc.

8.2. Real Constants


Integer numbers are not sufficient to represent quantities that vary
continuously, such as distances, height, prices etc. These quantities are represented
by numbers containing fractional parts like 25.234. Such numbers are called as
real or floating-point constants. Some valid examples of real constants are 0.067,
-12.5, +4.67, .87, 121., etc.

A real number may also be expressed in exponential (scientific) notation. For


example, 45.2344 can be written 0.452344e2. The exponential notation is:

mantissa e exponent

The mantissa is either a real number expressed in decimal notation or an


integer with an optional + or – sign. The exponent is an integer number with an
optional + or – sign. Some valid examples of real constants in exponential
notation are 0.34e2, 13e-2, -1.23e-1, etc.

8.3. Single Character Constants


A single character constant or character constant contains a single character
enclosed in between single quotes. Some valid examples of character constants
are ‘f’, ‘A’, ‘/’, ’;’, ‘ ‘, ‘4’, etc.

The character constant ‘4’ is not equal to the number 4.

Every character constant will have an associated integer value known as ASCII
code. Since each character constant has an associated integer value, we can
perform arithmetic operations on them.

Prepared by – Mr. Viral H. Panchal 14


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

8.4. String Literals or String Constants


A sequence of characters that are enclosed between double quotes is known
as a string literal or string constant. The characters in a string literal can be either
letters, digits, special symbols, or white spaces. The string literal does not have an
associated integer value like the character constants. Some valid examples of
string constants are “hai”, “hEllO”, “hi5”, “Welcome”, etc.

8.5. Backslash Character Constants/Escape Sequences


C supports some special backslash character constants that are used in output
functions like printf(). For example, to move the cursor from the current line to next
line, there is no standard way to achieve it. So, for such special cases, C provides
escape sequences.

In this case \n is used to move the cursor to next new line. Even though the
escape sequences consist of a backslash (\) and a character or symbol, it is
treated as a single character. C supports the following escape sequences.

Table 10.1: Backslash Character Constants/Escape Sequences in C


Constant Meaning
\a Alert
\b Backspace
\f Form feed
\n New line
\r Carriage Return
\t Horizontal tab
\v Vertical tab
\’ Single quote
\” Double quote
\? Question mark
\\ Backslash
\0 Null

Prepared by – Mr. Viral H. Panchal 15


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

9. Variables
In the programs, generally we need to store values in the memory and perform
operations on those values. This can be achieved in C by the concept of variables.

A variable is a data name (identifier) that may be used to store a data value.
Each variable identified by a unique identifier in a program called variable name. A
variable may take different values at different times during execution.

For using variables in our programs, there are essentially two steps:

1. Declare the variable


2. Initialize the variable

9.1. Declaring a Variable


Before using a variable in the program, we have to declare the variable. The
syntax for declaring a variable in a program is as shown below:

type variable-name;

The “type” in the above syntax represents the data type. The “variable-name”
is the identifier.

There are certain rules that must be followed while writing the variable name.
They are as follows:

o A variable name must always start with an alphabet (letter) or an


underscore ( _ ).
o The variable name must not be more than 31 characters. The suggested
length of a variable name is 8 characters.
o C is case sensitive. So, the variable name “average” is different from
“AVERAGE”.
o Keywords must not be used for declaring variables.
o White spaces are not allowed within the variable name.

Prepared by – Mr. Viral H. Panchal 16


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

9.2. Initializing a Variable


After declaring the variable, we can assign a value to the variable. This
process of assigning a value to the variable is known as initialization.

Syntax –
variable-name = value;

The value we assign to the variable depends on the data type of the variable.
Example –
int a;
a = 10;

The declaration and initialization can be combined into a single line as below:

int a = 10;

10. Data Types


A data type specifies the type of value that we use in our programs. A data type
is generally specified when declaring variables, arrays, functions, etc.

In ANSI C, the data types are divided into three categories. They are:

1. Primary or Fundamental data types


2. Derived data types
3. User-defined data types
10.1. Primary or Fundamental Data Types
The primary data types in ANSI C are as shown in the figure 12.1.
All C compilers support five fundamental data types, namely integer (int),
character (char), floating point (float), double-precision floating point (double)
and void.
Many of them also offer extended data types such as long int and long
double.

Prepared by – Mr. Viral H. Panchal 17


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

Figure 12.1: Primary data types in C

• Integer data types - Integers are whole numbers with a range of values
supported by a particular machine.
Generally, integers occupy one word of storage, and since the word sizes of
machines vary (typically, 16 or 32 bits) the size of an integer that can be stored
depends on the computer.
If we use a 16-bit word length, the size of the integer value is limited to the
range –32768 to +32767 (that is, –215 to +215–1). A signed integer uses one
bit for sign and 15 bits for the magnitude of the number. Similarly, a 32-bit word
length can store an integer ranging from -2,147,483,648 to 2,147,483,647 (that
is, –231 to +231–1).
In order to provide some control over the range of numbers and storage
space, C has three classes of integer storage, namely short int, int, and long int, in
both signed and unsigned forms.
ANSI C defines these types so that they can be organized from the smallest to
the largest. For example, short int represents fairly small integer values and
requires half the amount of storage as a regular int number uses. Unlike signed
integers, unsigned integers use all the bits for the magnitude of the number and

Prepared by – Mr. Viral H. Panchal 18


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

are always positive. Therefore, for a 16-bit machine, the range of unsigned
integer numbers will be from 0 to 65,535 (that is, 0 to 216–1).
We declare long and unsigned integers to increase the range of values. The
use of qualifier signed on integer is optional because the default declaration
assumes a signed number.

Syntax –

int variable_name;

Example –

int num1;
short int num2;
long int num3;

Table 12.1 shows all the allowed combinations of basic types and qualifiers
and their size and range on a 16-bit machine.

Table 12.1: Size and range of data types on a 16-bit machine

• Floating-point data types – Floating point (or real) numbers are stored in 32 bits
(on all 16-bit and 32-bit machines), with 6 digits of precision. Floating point
numbers are defined in C by the keyword float. When the accuracy provided by

Prepared by – Mr. Viral H. Panchal 19


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

a float number is not sufficient, the type double can be used to define the
number.
A double data type number uses 64 bits giving a precision of 14 digits. These
are known as double precision numbers. Remember that double type represents
the same data type that float represents, but with a greater precision. To extend
the precision further, we may use long double which uses 80 bits.

Syntax –

float variable_name;

Example –

float num1;
double num2;
long double num3;

• Character data type - A single character can be defined as a character (char)


type data. Characters are usually stored in 8 bits (one byte) of internal storage.
The qualifier signed or unsigned may be explicitly applied to char. While
unsigned chars have values between 0 and 255, signed chars have values from
-128 to 127.

Syntax –

char variable_name;

Example –

char ch = 'a’;

• Void type - The void type has no values. This is usually used to specify the type of
functions. The type of a function is said to be void when it does not return any
value to the calling function. It can also play the role of a generic type, meaning
that it can represent any of the other standard types.

Prepared by – Mr. Viral H. Panchal 20


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

10.2. Derived Data Types


The data types which are created using the already existing primitive or
fundamental types are known as derived data types. Examples of derived data
types in C are arrays, functions, structures, unions and pointers.

10.3. User-Defined Data Types


ANSI C allows the users to define identifiers as their own data types, based on
the already existing primitive or fundamental data types. This concept is known
as “type definition” and the data types thus created are known as user-defined
data types.
We can create user-defined data types in two ways:
1. By using the “typedef” keyword
2. By using the “enum” keyword

• typedef keyword - The “typedef” keyword can be used to declare an identifier


as a user-defined data type.

Syntax –

typedef type identifier;

Here, type represents the existing data type and identifier represents the new
name in place of type. Remember that typedef is not capable of creating any
new data type but provides only an alternative name to an existing data type.

Example –

typedef int number;


number no1, no2, no3;

typedef float price;


price silver, gold;

Prepared by – Mr. Viral H. Panchal 21


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

• enum keyword - The “enum” is used to declare identifiers as user-defined data


types. Such data types are also called as enumerations. The “enum” keyword can
be used to declare an identifier as data type which can store a limited set of
integer values.

Syntax –

enum identifier {value1, value2,…, valuen}; //definition


enum identifier v1, v2,…., vn; //declaration of variables

v1 = value3;
v4 = value1; // assigning values to variables

Example –

enum color {green, blue, red, pink}; //green, blue, red, pink
are constants or values
enum color flowers, leaves; //flowers and leaves are variables
flowers = red;
leaves = green;

11. Creating Constants in C


Constants in C are fixed values which cannot be changed during the execution of
the program.
In C, we can declare variables as constants in two ways. They are:
1. By using “const” keyword
2. By using “#define” preprocessor directive
11.1. const Keyword
We can declare a variable as a constant by using the const qualifier. A
variable that is declared using const cannot change its value once it is initialized.

Syntax –

const type variable-name = value;

Example –

const int max = 200;

Prepared by – Mr. Viral H. Panchal 22


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

11.2. #define Preprocessor Directive


We can also declare constants in a program by using the #define
preprocessor directive. Such constants declared using the #define preprocessor
directive are known as symbolic constants.

Syntax –

#define NAME value

Example –

#define PI 3.142

Take care that there is no semi-colon (;) at the end of #define statement. In the
above example we have assigned the value 3.142 to the symbol PI. Now,
whenever PI is encountered in the program, it will be replaced with the value
3.142.

Following are the rules that apply to a #define statement:


o All rules that apply to variables also apply to symbolic name.
Generally symbolic names are written in CAPTIAL LETTERS, to distinguish
them from the normal variable names.
o No blank space between # and define is allowed.
o # must be the first character in the #define statement.
o A blank space is required between #define and the symbolic name and
between symbolic name and the value.
o #define statements must not end with a semi-colon.
o After declaring a symbolic constant, we must not use it in an assignment
statement.
o Symbolic names are not declared for data types. Its data type depends
on the type of the constant value.
o #define statements may appear anywhere in the program, but before
they are referenced in the program. Generally, they are placed at the
top of the program after the #include statements.

Prepared by – Mr. Viral H. Panchal 23


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

11.3. const vs #define


The purpose of both const and #define is to declare constants in a C program.
The difference between them is - when we declare a variable as a constant using
const, it is still treated as a variable but the value will be fixed and cannot be
changed.
But, when we use #define, we are declaring symbolic constants, which are not
treated as variables. Instead, the compiler searches for the symbol throughout the
program and replaces the symbol with the value. Another difference is, const is a
keyword, whereas #define is a preprocessor directive.

11.4. volatile Keyword


ANSI standard defines another qualifier volatile that could be used to tell the
compiler that a variable’s value may be changed at any time by some external
sources (from outside the program).
Example usage of the volatile keyword is shown below –

volatile int date;

The value of date can be modified by its own program too.

If you don’t want the program to modify the value of date variable, but it can
be modified by external factors, then date can be declared as both volatile and
const as shown below –

volatile const int date = 19;

Prepared by – Mr. Viral H. Panchal 24


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

12. Basic Input and Output in C

12.1. Reading Input from Keyboard


Another way of assigning values to variables besides directly assigning the
value is reading values from the keyboard.
C provides scanf function in the stdio.h header file. Using this function, we can
read values from the keyboard and assign the values to variables.
Syntax –

scanf (“control string”, &variable1, &variable2,...);

The control string specifies the type of value to read from the keyboard and
the ampersand symbol & is an operator to specify the address of the variable(s).
Example –

scanf (“%d”, &var);

12.2. Printing onto Screen


To print or output text onto the screen, we use printf function.
Syntax –
printf (“control strings”, value1, value2, value3,...);

Example –

int a = 10;

printf (“%d”, a);

Table 14.1 shows the format specifiers or control strings available in C.


Data Type Format Specifier
int %d (or) %i
unsigned int %u
short int %hd
unsigned short int %hu
long int %ld
unsigned long int %lu
float %f (or) %e (or) %g
double %lf (or) %e (or) %g
long double %Lf
char %c
unsigned char %c
string %s

Prepared by – Mr. Viral H. Panchal 25


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

13. Operators
An operator is a symbol that tells a computer to perform certain mathematical or
logical operations. Operators are used in programs to manipulate data and
variables.
Operators are usually a part of the mathematical or logical expressions.
Generally, the usage of an operator is as shown below:

operand1 op operand2

In the above format, operand1 and operand2 can be either data or variables or
expressions. op is the operator. In C, based on the number of operands on which an
operator can operate, the operators are divided into three types namely, unary,
binary, and ternary.
Unary operators work on single operand, binary operators work on two
operands and ternary operators work on three operands.
In C, based on the functionality, operators are classified into 8 categories. They
are:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and Decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Special Operators

13.1. Arithmetic Operators


C provides all the basic arithmetic operators as shown in table 13.1. The
arithmetic operators can operate on any built-in data type in C. The unary minus
operator multiplies its single operand with -1.

Prepared by – Mr. Viral H. Panchal 26


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

Integer division truncates any fractional part. The modulo division operator (%)
produces the remainder of an integer division. The modulo operator cannot be
used on floating point values.
Table 13.1: Arithmetic operators
Operator Meaning Example
+ Addition or unary plus a+b
– Subtraction or unary minus a-b
* Multiplication a*b
/ Division (Quotient) a/b
% Modulo (Remainder) a%b
/* Program illustrating the use of arithmetic operators */

#include <stdio.h>
int main ()
{
int x = 25;
int y = 4;
printf ("%d + %d = %d\n", x, y, x + y);
printf ("%d - %d = %d\n", x, y, x - y);
printf ("%d * %d = %d\n", x, y, x * y);
printf ("%d / %d = %d\n", x, y, x / y);
printf ("Reminder when %d divided by %d = %d\n", x, y, x % y);
return 0;
}

Output –

25 + 4 = 29
25 - 4 = 21
25 * 4 = 100
25 / 4 = 6
Reminder when 25 divided by 4 = 1

13.2. Relational Operators


We often compare the two quantities and make certain decisions based on
their relationship. For example, we can compare the ages of two people or the
prices of two items and others. These comparisons can be made with the help of
relational operators.

Prepared by – Mr. Viral H. Panchal 27


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

An expression such as, 20 > 10 or x < y, containing a relational operator is


termed as a relational expression. The value of a relational expression is either
one or zero. It is one if the specified relations is true and zero if the relation is
false. For example,

20 > 10 // true
20 < 10 // false

C supports a total of six relational operators. These operators and their


meanings are displayed in the table 13.2.
Table 13.2: Relational operators
Operator Meaning Example
< Less than a<b
<= Less than or equal to a<=b
> Greater than a>b
>= Greater than or equal to a>=b
== Equal to a==b
!= Not equal to a!=b

Relational expressions are used in decision statements, such as if and while, to


determine the activity of a running program.

/* Program illustrating the use of relational operators */

#include <stdio.h>
int main ()
{
int a = 20, b = 10;
printf ("Two numbers are (a,b) = %d %d\n", a, b);
if (a > b)
printf ("a is greater than b\n");
if (a < b)
printf ("a is less than b\n");
if (a >= b)
printf ("a is greater than or equal to b\n");
if (a <= b)
printf ("a is less than or equal to b\n");
if (a == b)
printf ("a is equal to b\n");
if (a != b)
printf ("a is not equal to b\n");

Prepared by – Mr. Viral H. Panchal 28


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

return 0;
}

Output –

Two numbers are (a,b) = 20 10


a is greater than b
a is greater than or equal to b
a is not equal to b

13.3. Logical Operators


The relational operators are used to compare at most two values i.e., testing
one condition. To test more than one condition, we use logical operators along
with relational operators.
The logical operators always evaluate to either 0 or 1 like relational
operators. The logical operators available in C are shown in table 13.3.
Table 13.3: Logical operators
Operator Meaning Example
&& Logical AND (a>b) && (a>c)
|| Logical OR (a>b) || (a>c)
! Logical NOT ! (a>b)

Logical NOT is a unary operator. In an expression, we can use more than one
logical operator. If more than one operator is used, ! (NOT) is evaluated first,
then && (AND) and then || (OR). We can use the parentheses to change the
order of evaluation.
For example, if we have a = 2, b = 3 and c = 5 then,

Expression Value Remark


a < b && c == 5 true both expressions are true
5 > 3 is true and negation of true
! (5 > 3) false
is false
a < b is true which makes the
a < b || c > 10 true
expression true
(b > a) && (c != 5) false c = 5, so second condition false
(b < c || b > a) && (c == 5) true Both sub expressions are true

Prepared by – Mr. Viral H. Panchal 29


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

/* Program illustrating the use of logical AND && operator */

#include <stdio.h>
int main ()
{
int a = 2, b = 3, c = 1;
if (a > b && a > c)
printf ("a is big");
else if (b > c)
printf ("b is big");
else
printf ("c is big");
return 0;
}

Output –

b is big

13.4. Assignment Operators


The assignment operators are used to assign value of an expression to a
variable. The general assignment operator is = (equal).
In C, there are some special assignment operators known as shorthand
operators. The syntax of shorthand operators is as shown below –

var op = exp;

In the above shown syntax, var is a variable, op is an arithmetic operator and


exp can be any expression or value or a variable. The operator op= is known as
the shorthand assignment operator.
The assignment operators in C are as shown in table 13.4.
Table 13.4: Assignment operators
Statement with simple Statement with
Operator
assignment operator shorthand operator
= a=1 a=1
+= a = a +1 a+=1
-= a=a–1 a–=1
*= a = a * (n+1) a*=n+1
/= a = a / (n + 1) a/=n+1
%= a=a%b a%=b

Prepared by – Mr. Viral H. Panchal 30


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

There are three advantages to using shorthand assignment operators:


1. What will appear on the left side should not be repeated, so it becomes
easier to write.
2. The statement is more concise and easier to read.
3. The statement is more efficient.

13.5. Increment and Decrement Operators


Sometimes we need to increase or decrease a variable by one. We can do
that by using assignment operator =.
For example, the statement a = a + 1 increments the value of variable a,
same way the statement a = a – 1 decrement the value of variable a.
C language provides special operators ++ (increment operator) and – –
(decrement operator) for doing this. These operators are unary i.e., it requires
only one operand.
The operand can be written before or after the operand. If a is a variable,
then ++a is called prefix increment while a++ is called postfix increment.
Similarly, – –a is called prefix decrement while a– – is called postfix
decrement.

Table 13.5: Increment and decrement operators


Operator Meaning
++a Pre increment. It adds 1 to the operand and then
assigns the result to the variable on left.
a++ Post increment. It assigns the result to the variable on
left then adds 1 to the operand.
– –a Pre decrement. It subtracts 1 from the operand and
then assigns the result to the variable on left.
a– – Post decrement. It assigns the result to the variable
on left then subtracts 1 from the operand.

Prepared by – Mr. Viral H. Panchal 31


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

/* Program showing the use of increment ++ and decrement --


operators */

#include <stdio.h>
int main ()
{
int x = 10;
int y;
int z = 0;
x++; /* x incremented using postfix notation x=11 */
++x; /* x incremented using prefix notation x=12 */
y = ++x; /* x is incremented first and then assigned to
y. y=13 x=13 */
printf ("Value of x=%d y=%d and z=%d\n", x, y, z);
z = y--; /* y assigned to z first and then decremented.
z=13 y=12 */
printf ("Value of x=%d y=%d and z=%d\n", x, y, z);
return 0;
}

Output –
Value of x=13 y=13 and z=0
Value of x=13 y=12 and z=13

13.6. Conditional Operator (Ternary Operator)


Conditional operator is used to check conditions and depending on the result
the statement is executed else we go for another execution. Conditional operators
are used in place of if-else statement. This operator is also called as ternary
operator as it takes 3 operands.
The general form of the conditional expression is
exp1 ? exp2 : exp3
where exp1, exp2, and exp3 are expressions.
The meaning of the above expression is: if exp1 is true then expression exp2
is evaluated else exp3 is evaluated.
For example, consider the following statements.
a = 10;
b = 12;
x = (a>b) ? a : b ;
In this example, x will be assigned the value of b.

Prepared by – Mr. Viral H. Panchal 32


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

/* Write a program to find maximum and minimum of two numbers


using ternary operator */

#include <stdio.h>
#include <conio.h>
int main ()
{
int x, y, max, min;
printf ("Give two integer numbers:\n");
scanf ("%d%d", &x, &y);
max = (x > y) ? x : y;
min = (x < y) ? x : y;
printf ("maximum of %d and %d is = %d\n", x, y, max);
printf ("minimum of %d and %d is = %d\n", x, y, min);
return 0;
}

Output –

Give two integer numbers:


8 17
maximum of 8 and 17 is = 17
minimum of 8 and 17 is = 8

13.7. Bitwise Operators


These operators are used to perform bitwise operations such as testing the
bits, shifting the bits to left or right, one’s complement of bits, etc. These operators
can be applied only on int and char data types but not on float and double data
types.
The table 13.6 shows various bitwise operators available in C language.

Table 13.6: Bitwise operators


Operator Meaning
~ Bitwise 1’s complement
<< Shift left
>> Shift right
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR (XOR)

Prepared by – Mr. Viral H. Panchal 33


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

Table 13.7 below explains the basic &, | and ^ operations.

Table 13.7: &, | and ^ operations


Bit1 Bit2 Bit1 & Bit2 Bit1 | Bit2 Bit1 ^ Bit2
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

The << and >> operators are used to shift the bits in left and right directions
respectively. After the << or >> operator some integer number is written.
Let us understand with example.
char x=15;
char y=8;
char z;

• Example of << (Shift left) –


z = y << 1; will shift the bits of y one bit in left side, and 0 is inserted from
right side.

y (8) → 0 0 0 0 1 0 0 0

z = y << 1 (16) → 0 0 0 1 0 0 0 0

So, we can see that the left shift by one bit multiplies the number by 2. If we
left shift it by 2 bits, the number is multiplied by 4.

• Example of >> (Shift right) –


z = y >> 2; will shift the bits of y by 2-bit positions towards right side, and 0
is inserted from left side.

y (8) → 0 0 0 0 1 0 0 0

z = y >> 2 (2) → 0 0 0 0 0 0 1 0

Each one-bit shift on right divides the number by 2. We shifted 2 bits towards
right, so y divided by 4. Here, the answer may be truncated if the operand is not
even number.

Prepared by – Mr. Viral H. Panchal 34


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

13.8. Special Operators


C supports some special operators such as comma operator, sizeof operator,
pointer operators (& and *) and member selection operators ( . and →).
• The comma operator – The comma operator can be used to link the related
expressions together. Comma linked lists of expressions are evaluated left to
right and the value of right-most expression is the value of the combined
expression.
For example, the statement

value = (x=10, y=5, x+y);

first assigns the value 10 to x, then assigns 5 to y, and finally assigns 15 (i.e.,
10+5) to value.

• The sizeof operator – The sizeof operator is a compile time operator and
when used with an operand, it returns the size of its operand in bytes.
For example,
int i, j;
j = sizeof (i); /* it will give j = 2. Since integer
occupies 2 bytes and i is an integer */

Prepared by – Mr. Viral H. Panchal 35


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

14. Operator Precedence and Associativity


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

Prepared by – Mr. Viral H. Panchal 36


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

Example –

#include <stdio.h>
int 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;
}

Output –

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

15. Type Conversion/Type Casting


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

Prepared by – Mr. Viral H. Panchal 37


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

15.1. Implicit Type Conversion


Also known as ‘automatic type conversion’.
It is done by the compiler on its own, without any external trigger from the
user.
It generally, takes place when in an expression more than one data type is
present. In such conditions type conversion (type promotion) takes place to avoid
loss of data.
All the data types of the variables are upgraded to the data type of the
variable with the largest data type.

bool -> char -> short int -> int -> unsigned int -> long ->
unsigned -> long long -> float -> double -> long double

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

Example of Implicit Type Conversion –

#include <stdio.h>
int main ()
{
int a,b;
float c;
double d;
a = 5;
c = 5.5;
d = 4.0;
b = a * c + d / 10;
printf ("value of b = %d\n",b);
return 0;;
}

Output –

value of b = 27

Prepared by – Mr. Viral H. Panchal 38


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

Explanation –

o In the statement b = a * c + d / 10; a * c will be done first, here a will


be upgraded to float because other operand c is float. So, a * c will
evaluate to 27.5.
o Then, d / 10 will be evaluated, 10 will be converted into 10.0 (double)
because d is double. So, d / 10 will evaluate to 0.4.
o Then 27.5 + 0.4 evaluates to 27.9. This value is assigned to variable b,
which is integer, so truncated value of 27.9 will be the value of b i.e.,
27 will be assigned to b.

In the case of assignment,


o If float is assigned to integer, then fractional part is truncated as shown
in above program.
o If double is assigned to float, then rounding takes place.
o If long int is assigned to int, then additional bits are dropped, recall that
long int requires 4 bytes while int requires only 2 bytes.

15.2. Explicit Type Conversion (Type Casting)


This process is also called type casting and it is user-defined. Here the user can
typecast the result to make it of a particular data type.
The syntax in C Programming:

(typename) expression

Here, typename is the name of data type we want to convert the expression
to. The converted value is used during evaluation of expression only, it does not
change the basic data type of operand(s) of an expression.
For example, (float) 21 converts int 21 to float 21.0.

Prepared by – Mr. Viral H. Panchal 39


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

Example of Explicit Type Conversion –

#include <stdio.h>
int main ()
{
int sum = 47;
int n = 10;
float avg;
avg = sum / 10; /* avg without type cast */
printf ("avg = sum / n = %f\n",avg);
avg = (float) sum / n; /*avg with type cast on sum */
printf ("avg = (float) sum / n = %f\n",avg);
avg = (float) (sum / n); /* avg without type cast on (sum / n) */
printf ("avg = (float) (sum / n) = %f\n",avg);
return 0;
}

Output –

avg = sum / n = 4.000000


avg = (float) sum / n = 4.700000
avg = (float) (sum / n) = 4.000000

Explanation –

o In the first line of output, integer arithmetic takes place; while in second,
sum which is 47 is converted into 47.0 and 10 becomes 10.0. So,
floating point arithmetic takes place.
o While in the last line of output, float type casting takes place on sum / n
which is 4, converted into float becomes 4.0.

Prepared by – Mr. Viral H. Panchal 40


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

16. Basic C Programs


/* Write a program to print your details in following format:
Name: Xyz
College Name: CGPIT
Branch Name: Computer Engineering
Subject: Basics of Logic Development
Enrolment no.: 201204101510005 */

#include <stdio.h>
int main ()
{
printf ("Name: Viral Panchal\n");
printf ("College Name: CGPIT\n");
printf ("Branch Name: Computer Engineering\n");
printf ("Subject: Basics of Logic Development\n");
printf ("Enrolment No.: 201204101510005\n");
return 0;
}

Output –

Name: Viral Panchal


College Name: CGPIT
Branch Name: Computer Engineering
Subject: Basics of Logic Development
Enrolment No.: 201204101510005

/* Write a program that reads variables with different data


types and display their value */

#include <stdio.h>
int main ()
{
char c;
int n;
float f;
printf ("Enter a character: ");
scanf ("%c", &c); // Taking Character as input from the user
printf ("The character that you have entered is %c\n", c);
printf ("Enter integer number: ");
scanf ("%d", &n); // Taking integer as input from user
printf ("The integer number you have entered is %d", n);
printf ("\nEnter a floating-point number: ");

Prepared by – Mr. Viral H. Panchal 41


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

scanf ("%f", &f); // Taking fraction as input from the user


printf ("The float or fraction that you have entered is %f\n", f);
return 0;
}

Output –

Enter a character: v
The character that you have entered is v
Enter integer number: 19
The integer number you have entered is 19
Enter a floating-point number: 23.76
The float or fraction that you have entered is 23.760000

/* Write a program to design basic calculator */

#include<stdio.h>
int main ()
{
float no1, no2, add, sub, multi, div;
printf ("Entre number 1: ");
scanf ("%f", &no1);
printf ("Enter number 2: ");
scanf ("%f", &no2);
add = no1 + no2;
sub = no1 - no2;
multi = no1 * no2;
div = no1 / no2;
printf ("Addition = %f\n", add);
printf ("Subtraction = %f\n", sub);
printf ("Multiplication = %f\n", multi);
printf ("Division = %f\n", div);
}

Output –

Entre number 1: 5
Enter number 2: 4
Addition = 9.000000
Subtraction = 1.000000
Multiplication = 20.000000
Division = 1.250000

Prepared by – Mr. Viral H. Panchal 42


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

/* Write a program to compute Fahrenheit from Centigrade


(f=1.8*c +32) */

#include<stdio.h>
int main ()
{
float f, c;
printf ("Enter Temperature in Celsius: ");
scanf ("%f", &c);
f = 1.8 * c + 32;
printf ("Temperature in Fahrenheit = %0.2f\n", f);
return 0;
}

Output –

Enter Temperature in Celcius: 42


Temperature in Fahrenheit = 107.60

/* Write a program to swap two numbers using third variable*/

#include<stdio.h>
int main ()
{
int no1, no2, temp;
printf ("Enter No.1: ");
scanf ("%d", &no1);
printf ("Enter No.2: ");
scanf ("%d", &no2);
printf ("Before Interchange\nNo.1 = %d and No.2 = %d", no1, no2);
temp = no1;
no1 = no2;
no2 = temp;
printf ("\nAfter Interchange\nNo.1 = %d and No.2 = %d\n", no1, no2);
return 0;
}
Output –

Enter No.1: 5
Enter No.2: 8
Before Interchange
No.1 = 5 and No.2 = 8
After Interchange
No.1 = 8 and No.2 = 5

Prepared by – Mr. Viral H. Panchal 43


Basics of Logic Development Unit - 2 (Part - 1): Basics of Programming

/* Write a program to swap two numbers without using third


variable */

#include<stdio.h>
int main ()
{
int a,b;
printf ("Enter No.1: ");
scanf ("%d", &a);
printf ("Enter No.2: ");
scanf ("%d", &b);
printf ("Before Interchange\nNo.1 = %d and No.2 = %d",a,b);
a=a+b;
b=a-b;
a=a-b;
printf ("\nAfter Interchange\nNo.1 = %d and No.2 = %d\n",a,b);
return 0;
}

Output –

Enter No.1: 5
Enter No.2: 8
Before Interchange
No.1 = 5 and No.2 = 8
After Interchange
No.1 = 8 and No.2 = 5

Prepared by – Mr. Viral H. Panchal 44

You might also like