0% found this document useful (0 votes)
11 views52 pages

Basics of Computer Languages Explained

The document provides an overview of computer languages, categorizing them into low-level and high-level languages, and explains their characteristics, advantages, and disadvantages. It also discusses source code vs. object code, language processors like compilers and interpreters, and includes examples of algorithms and flowcharts. Additionally, it outlines the history of the C programming language and presents various algorithms for solving mathematical problems.

Uploaded by

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

Basics of Computer Languages Explained

The document provides an overview of computer languages, categorizing them into low-level and high-level languages, and explains their characteristics, advantages, and disadvantages. It also discusses source code vs. object code, language processors like compilers and interpreters, and includes examples of algorithms and flowcharts. Additionally, it outlines the history of the C programming language and presents various algorithms for solving mathematical problems.

Uploaded by

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

A.V.

PAREKH TECHNICAL INSTITUTE , RAJKOT

COMPUTER ENGGINEERING
DEPARTMENT COMPUTER
PROGRAMMING
3310701
BASICS OF COMPUTER LANGUAGE

Q1: What is a computer language? Briefly describe the major type of the computer
languages?
Ans: Computer Language
The computer works by executing instructions. Each instruction directs one operation of the
computer system. Several instructions are written to perform one task. This set of instructions given to
the computer to perform a task is called the computer program.
The computer instructions are written in a specific manner and according to a set of rules. These
languages are divided into two main categories. These are given below.
1. Low Level Languages
2. High Level Languages

Low Level Languages:


The computer language that is close to the machine language is called low level language. There are
two types of low level language. These are machine language and assembly language.
Machine Language
The computer works with the arrangements of 0s and 1s. The arrangement of 0s and 1s is called the
binary code. This is the fundamental language of the computer. Since the computer works only with 0s and
1s, the instructions written in binary code are called the machine language.
The machine language is difficult to understand and learn. Every computer system has its own machine
language. A program written on one type of computer system cannot run on another type of computer
system.
Assembly Language
Assembly language was developed to make the programming task easier. Instead of using the binary
code, it uses symbols. The symbols are used to represent instruction. Therefore, it is also known as the
symbolic language. Since the assembly language is close to the machine language, it is called the low-level
language.
Writing a program in assembly language is easier than writing the program in machine language.
However, the assembly language is also machine-specific. It is also hard to learn.
Assembly language is usually used for writing system software and firmware.

High-Level Languages
The programming languages that are close to human language are called high-level languages. The
instructions in these languages are more like human languages.
BASIC, FORTRAN, COBOLM, PASCAL, C, etc. are examples of high level languages. Unlike low
level languages, these languages are easier to learn. These languages are used for writing application
programs. For example, a high level language may be used for writing a program for maintaining the budget
of a company.

AVPTI COMPUTER ENGINEERING DEPARTMENT 1


Q2: Distinguish between the source code and object code?

Source Code
A computer program written in a high level language is called the source code. It is also called the
source program. Since the computer works only with the binary code, the programs written in high level
languages cannot run directly on the computer. They must be converted into the binary code for execution
by the computer.
Object Code
A computer program written in the machine language is called the object code. It is also called the
object program. Since machine language is the native language of the computer, a program written in
machine language runs directly on the computer.

Q3: What are the language processors? Briefly describe their various types?

Language Processors
The computer works only with the binary code. Therefore, the programs written in high level
languages must be converted into the machine language (binary code) for execution by the computer.
Special programs are used to convert a source code into the object code. These programs are called
language processors.
Every high level programming language has its own language processor. The language processors
are divided into two categories. These are given below
1. Compilers
2. Interpreters

Compiler
The language processor that translates programs written in a high level language into the machine
language as a whole is called the compiler. The compiler translates the source program into the machine
code or object code. It saves the compiled program into another file called the object file. The computer
directly executes the object file. The program is compiled only once and can be executed a number of times
directly on the computer.
If there is any error in the source program, the compiler specifies the error at the time of compilation.
All errors must be removed before the compiler can successfully compile the source program.

Interpreter
The language processor that executes a source program by translating and executing one instruction
at a time is called interpreter. If there is any error in the instruction it indicates the error and program
execution stops.
The interpreter translates the program instructions one by one and executes them immediately. It
does not create an object program. Thus the interpreter translates the source program each time the program
is executed. This method of translating and executing a program is slow and time consuming. A BASIC
language processor is an example of Interpreter.

AVPTI COMPUTER ENGINEERING DEPARTMENT 2


Q4: What are the Characteristics of High Level Languages?

Characteristics of High Level Languages:


The features and qualities of a language are called characteristics of the language. These features
distinguish a language from other languages. Some important characteristics of high level languages are
given below:

Not Machine Dependent


The high level languag4es are not machine dependent. Unlike a machine language program that
can be run only on the computer system for which it is written, a high level program can be run on any
computer system.

Can Be Implemented On a Variety of Machines


The program written in a high level language is called the source code. This source code is first
compiled and then executed on the computer system. A source code can be compiled and executed on any
computer system for which the language compiler is available.

Well Defined Syntax and Standard


Each high level language has a standard syntax. The standard is published by several International
Organizations. An important Organization that publishes the computer programming language standards
is ANSI (American National Standards Institute). The compilers are written according to the standard
syntax of the language.

Relatively Easy to Learn


The instructions are written in English like words in high level languages. This makes learning,
understanding and writing program in high level languages easy.

Source is Understandable by another Programmer


Since the instructions are written in plain English words and according to the standard syntax of the
language, any computer programmer can understand a program written by another programmer.

Q5: Explain the Advantage of High level Languages?


Advantages of High Level Languages
High level languages have several advantages over low level languages. Some important
advantages of these languages are:
Easy to Learn
The instructions written in high level languages are similar to the plain English Instructions. This
makes the high level languages easy to learn and use.

Machine Independent
A program written in a high level language can be used on any computer system for which the
compiler of the language is available.

Shorter Programs
The High level language programs are shorter than the programs written in machine languages. A
single instruction written in a high level language translates into several machine language instructions.

Problem Oriented Languages

AVPTI COMPUTER ENGINEERING DEPARTMENT 3


The high level languages are problem oriented languages. These are designed to solve problems on
the computer system. For example, a business oriented language uses business term and the language for
scientists and engineering calculations uses scientific terms.

Easier to Understand
The program instructions in high level language are similar to the plain English statement. This
makes the program easy to understand. Anyone who is familiar with the computer language can easily
understand the logic of the program written in a high level language.

Less Time Needed for Writing Programs


Several programmers can work on one program simultaneously. Thus a program can be developed
quickly.

Standards are Available


The syntax of the high level languages is standardized. The compilers are written according to these
standards.

Programming Aids are Available


Several tools or programs are available that help the writing of programs in high level languages.
These programs provide facilities for writing source code, compiling and debugging of the programs. These
tools have increased the seed of writing programs in high level language.

Many Programmers are Available


The programming in machine languages was time consuming and difficult to learn. This
discourages people from learning these languages. On the other hand, the programming in high level
languages is easy and many people learn and use these languages.

AVPTI COMPUTER ENGINEERING DEPARTMENT 4


CHAPTER 1 – FLOW CHART AND ALGORITHMS
Que. History of Language “C”.
Ans. Language “C” was an offspring of the “Basic Combined Programming Language”(BCPL) called
B. Language B was developed in the 1960’s at Cambridge University. B Language was modified by Dennis
Ritchie and was implemented at bell Laboratories in 1972. The new language was named C. Since, it was
developed along with the Unix operating system, it is strongly associated with Unix. Unix was developed
at Bell laboratories and also coded almost entirely in C.

Year Language Developed by Remarks


1960 ALGOL International Committee Too general, too abstract.
1963 CPL Cambridge University Hard to learn, difficult to implement
1967 BCPL Martin Rechards at Too specific deal with only specific
Cambridge University problems.
1970 B Ken Thompson at AT & T Too specific deal with only specific
Bell labs. problems.
1972 C Dennis Ritchie at AT & T Lost generality of BCPL and B restored
Bell labs

Que. What is an algorithm ? Explain it with an example.


Ans. An algorithm is a stepwise solution to a problem. Each step in an algorithm represents a solution to
a small problem. So, with the help of algorithm we can solve the given problem. An algorithm itself is
division of problem into small steps, which can be very easily understandable.

Example-1: Write an algorithm to find area of circle. A=∏ R2

1. Input R
2. Compute A = 3.14 * R *R
3. Print A
4. STOP

Explanation: Here Input R (Step-1) represents that a value of R(radius) is to taken from user. The last step
is STOP which indicates end of algorithm.

Example-2: Write an algorithm to find minimum of two numbers.

1. Input n1, n2
2. if n1 < n2, goto 5
3. Print n2
4. goto 6
5. Print n1
6. STOP

Que. What is a flowchart ? Give the symbols used in flowchart with their use. Or
Draw basic flowchart symbols. [02]
Ans. A flowchart is a pictorial representation of algorithm. As it represents solution in form of picture.
It is more easier to understand and develop. A main advantage of flowchart is visibility of paths (or flows)
within solution. Each path (or logical sequence) is clearly visible as arrows are used to represent flow.
Before developing flowcharts for example problems, different flowchart symbols must be known. As
shown below…..

AVPTI COMPUTER ENGINEERING DEPARTMENT 5


Start / Stop

Arrow
Input / Output

Process / Computation
Decision Making

Subroutine

Page Break
Continue

AVPTI COMPUTER ENGINEERING DEPARTMENT 6


Example-1 Draw a flowchart to find area of circle.

Start
StatrStart
Start

Input R

A=∏ R2

Print A

STOP

AVPTI COMPUTER ENGINEERING DEPARTMENT 7


Example-2: Draw a flowchart to find minimum of two numbers.

Start

Input N1, N2

Yes No
N1 < N2 ?

Print N1 Print N2

Stop

AVPTI COMPUTER ENGINEERING DEPARTMENT 8


QUE : DEFINE ALGORITHM. EXPLAIN ADVANTAGES AND
DISADVANTAGES OF ALGORITHM. AND CHARACTERISTICS OF
ALGORITHM.

Standard Defination : “ An algorithm is a procedure or formula for solving a problem, based on conductiong a
sequence of specified actions. A computer program can be viewed as an elaborate algorithm”.

Advantages of Algorithms:

1. It is a step-wise representation of a solution to a given problem, which makes it easy to understand.


2. An algorithm uses a definite procedure.
3. It is not dependent on any programming language, so it is easy to understand for anyone even without
programming knowledge.
4. Every step in an algorithm has its own logical sequence so it is easy to debug.
5. By using algorithm, the problem is broken down into smaller pieces or steps hence, it is easier for
programmer to convert it into an actual program.

Disdvantages of Algorithms:

1. Alogorithms is Time consuming.


2. Difficult to show Branching and Looping in Algorithms.
3. Big tasks are difficult to put in Algorithms.

Characteristics of Algorithms:

Precision – the steps are precisely stated(defined).

Uniqueness – results of each step are uniquely definedand only depend on the input and the result of the
precedingsteps.

Finiteness – the algorithm stops after a finite number ofinstructions are executed.

Input – the algorithm receives input.

Output – the algorithm produces output.

Generality – the algorithm applies to a set of inputs.

QUES : EXPLAIN ADVANTAGES AND DISADVANTAGES OF FLOWCHART.


Flowchart Advantages

 Flowcharts are easier to understand compare to Algorithms and Pseudo code.


 It helps us to understand Logic of given problem.
 It is very easy to draw flowchart in any word processing software like MS Word.
 Using only very few symbol, complex problem can be represented in flowchart.
 Software like RAPTOR can be used to check correctness of flowchart drawn in computers.
 Flowcharts are one of the good way of documenting programs.
 It helps us in debugging process.

AVPTI COMPUTER ENGINEERING DEPARTMENT 9


Flowchart Disadvantages
 Manual tracing is needed to check correctness of flowchart drawn on paper.
 Simple modification in problem logic may leads to complete redraw of flowchart.
 Showing many branches and looping in flowchart is difficult.
 In case of complex program/algorithm, flowchart becomes very complex and clumsy.
 Modification of flowchart is sometimes time consuming.

Algorithm to add two numbers entered by the user

Step 1: Start

Step 2: Declare variables num1, num2 and sum.

Step 3: Read values num1 and num2.

Step 4: Add num1 and num2 and assign the result to sum.

sum←num1+num2

Step 5: Display sum

Step 6: Stop

Find the largest number among three different numbers

Step 1: Start

Step 2: Declare variables a,b and c.

Step 3: Read variables a,b and c.

Step 4: If a > b

If a > c

Display a is the largest number.

Else

Display c is the largest number.

Else

If b > c

Display b is the largest number.

Else

AVPTI COMPUTER ENGINEERING DEPARTMENT 10


Display c is the greatest number.

Step 5: Stop

Roots of a quadratic equation ax2 + bx + c = 0

Step 1: Start

Step 2: Declare variables a, b, c, D, x1, x2, rp and ip;

Step 3: Calculate discriminant

D ← b2-4ac

Step 4: If D ≥ 0

r1 ← (-b+√D)/2a

r2 ← (-b-√D)/2a

Display r1 and r2 as roots.

Else

Calculate real part and imaginary part

rp ← -b/2a

ip ← √(-D)/2a

Display rp+j(ip) and rp-j(ip) as roots

Step 5: Stop

Factorial of a number entered by the user.

Step 1: Start

Step 2: Declare variables n, factorial and i.

AVPTI COMPUTER ENGINEERING DEPARTMENT 11


Step 3: Initialize variables

factorial ← 1

i←1

Step 4: Read value of n

Step 5: Repeat the steps until i = n

5.1: factorial ← factorial*i

5.2: i ← i+1

Step 6: Display factorial

Step 7: Stop

Check whether a number is a prime number or not

Step 1: Start

Step 2: Declare variables n, i, flag.

Step 3: Initialize variables

flag ← 1

i←2

Step 4: Read n from the user.

Step 5: Repeat the steps until i=(n/2)

5.1 If remainder of n÷i equals 0

flag ← 0

Go to step 6

5.2 i ← i+1

Step 6: If flag = 0

Display n is not prime

AVPTI COMPUTER ENGINEERING DEPARTMENT 12


else

Display n is prime

Step 7: Stop

Find the Fibonacci series till term ≤ 1000.

Step 1: Start

Step 2: Declare variables first_term,second_term and temp.

Step 3: Initialize variables first_term ← 0 second_term ← 1

Step 4: Display first_term and second_term

Step 5: Repeat the steps until second_term ≤ 1000

5.1: temp ← second_term

5.2: second_term ← second_term + first_term

5.3: first_term ← temp

5.4: Display second_term

Step 6: Stop

Que. Importance of “C” or Features of “C”


Ans. Language C is very popular due to its many desirable qualities or features. Following are some
features of C.
AVPTI COMPUTER ENGINEERING DEPARTMENT 13
 It is very robust language . It has rich set of built in functions and operators , which can be
used to write any complex program.
 C compiler combines the capabilities of an assemble language with the features of a high
level language and therefore it is well suited for writing both system software and business
packages. Many of C compilers available in market are written in C. That’s why C is also
known as middle level language.
 Programs written in C are efficient and fast. This is due to its variety of data types and
powerful operators. It is many times faster than BASIC(Beginners All Purpose Symbolic
Instruction Code) language. As BASIC uses interpreter , a program to increment a variable
from 0 to 15000 takes more than 50 seconds in BASIC while only one second in C.
 Language C’s main strength is in its built in functions. There are only 32 keywords.
Several standard functions are available to develop a program.
 C is highly portable. It means , C programs written for one computer can be run on another
with little or no modification. Portability is important when we plan to use a new computer
with a different operating system.
 C language is well suited for structured programming, it requires the user to think of a
problem in terms of function modules or blocks. A proper collection of these modules would
make a complete program. The modular structure makes program debugging, testing and
maintenance easier.
 The most Important feature of C is the ability to extend itself. A “C” Program is basically
a collection of functions that are supported by the “C” library. We can continuosly add our
own functions to the C library. With the availability of a large number of functions, the
programming task becomes simple.

Que. Explain the Basic Structure of C Program. Or


Write S.N. on Structure of C programs. Or
Why “C” is called structured language? May-02 [03] or
Write steps of basic structure of a “C” program. [03]

Ans. Every C program is a group of building blocks that are called functions. A function is subroutine
that may include one or more statements designed to perform a specific task. C Program is divided in
following sections….

Documentation Section
Link Section
Definition Section
Global Declaration Section
Main() Function Section
{

Declaration Part
Executable Part

AVPTI COMPUTER ENGINEERING DEPARTMENT 14


Sub Program Section

Function 1
Function 2 User - defined
: Functions

Function n

Fig. Structure of a C Program

Documentation Section: It consists of a set of comment lines giving the name of the program, the
author and other details , which the programmer would like to use later.
For Example: // this is the prog. To find area of a circle.

Link Section: The link section provides instructions to the compiler to link functions from the
system library.
For Example: #include<stdio.h>
#include<conio.h>

Definition Section: The Definition section defines all symbolic constants.


For Example: #define PI 3.14 here PI is the symbolic constant.

Global Declaration Section: There are some variables that are used in more than
one function. These variables are called global
variables and are declared in the global declaration section
that is outside of all the functions. It means, if a variable is used in
more than one function than it is possible to declare it as global
variable. Generally it is declared above the Main()
function.

Main() Function Section: Every C program must have one main() section. This section contain two
parts, declaration part and executable part. The declaration part declares all the variables , which
are to be used in the executable part. There is at least one statement in executable part. These two parts
must be in between opening and closing braces. The program execution begins at the opening brace and
ends at the closing brace. The closing brace of the main function is the logical end of the program.
Note: (1) Remember that you should always declare all the types of variables before any
executable statement.
2) All statements in the declaration and executable parts end with a semicolon.

Subprogram Section: The subprogram section contains all the user defined functions that are called
in the main function. User defined functions are generally placed immediately after the end of main
function.

Note: All the sections, except main function may be absent when they are not required. Main
is the unique section of the program i.e more than one main() is illegal.

AVPTI COMPUTER ENGINEERING DEPARTMENT 15


Que: Write the steps to Execute a “C” Program.
Ans: To Execute a “C” Program following steps are required:

1. Creating a program
2. Compiling a program
3. Linking the program with functions that are needed from the C
library
4. Executing a program

Que: Differentiate between Compilers and interpreter.


Ans:
A compiler checks the entire user written program (known as the source program and, if
error free, produces a complete program in machine language (known as the object program). The source
program is retained for possible modifications and corrections and the object program is loaded into the
computer’s memory for execution.
An interpreter does a similar job but in a different style. The interpreter (as the name
implies) translates one statement at a time and, if error-free, executes the instruction. This continues till the
last statement in the program has been translated and executed. Thus, the interpreter translates and executes
the first instruction before it goes to the second, while a compiler translates the whole program before
execution begin.
The major differences between them are:
a. Error correction (called debugging) is much simpler in the case
of an interpreter because it is done in stages. As against the
compiler produces an error list for the entire program before
execution of even the first instruction can begin.
b. Interpreters take more time for the execution of a program
compared to compilers because a statement has to be translated
every time the program is executed.

Que: Explain Programming Techniques/Methodology:


Ans:
There are three programming techniques commonly used. These are :
a. Top-down design
b. Bottom-Up design
c. Modular design.
Description:
a. In the top-down design the overall task of the program is broken down into several smaller
logics and then they are interlaced by calling these logics whenever necessary.

b. As against this in bottom-up design programming begins with the smallest of logics and
from this the next bigger logic is built and so on further up till the entire problem is
programmed.

c. Modular programming is a term used to describe dividing a program into areas of code or
modules that perform specific tasks. The programmer designs the program in levels, where
a level consists of one or more modules.

AVPTI COMPUTER ENGINEERING DEPARTMENT 16


CHAPTER – 2 BASICS OF C
Q6: Briefly describe the history of development of C language?

Brief History of C:
C is a general purpose programming language. It was developed at AT & T Bell Laboratories in
1972. it was designed and written by Dennis Ritche. It was written as a part of the UNIX operating system.
The UNIX system and its tools were written in C. As the UNIX system spread, the C language also became
popular. Because of its capabilities as a medium level language, C language was used to develop system
software. It was also widely used to write software to control industrial processes.

Q7: What is ANSI C Standard?

ANSI-C Standard:
The standard for a language specifies the form of the program written in that language. It also
specifies how programs are to be interpreted. The purpose of a standard is to specify the syntax of the
language and make it portable across various computer systems
The standard for C language was first proposed by the American National Standards Institute
(ANSI) in late 1980s. In 1990, the International Standards Organization als9o adopted the ANSI standard
for C language. This is known as ANSI/ISO C standard. This standard is now an internationally recognized
standard and almost all C compilers now follow the ANSI C standard.

Q7: What are the Advantages of C language?

Advantages of C language
Following are the advantages of C language:

Native Language of UNIX


C is the native language of UNIX. UNIX is a major operating system on workstations, servers and
mainframes. Also, many window based packages, database programs, graphic libraries and other large
application programs are written in C language.

Medium Level Language


C is a medium level language. C has the characteristics of both a low level language and a high
level language. It allows direct manipulation of memory addresses and data. It also has all the capabilities
of a high level language and allows the writing of programs independent of the computer system.

Portable Language
The C –programs written on one type of computer system can be easily used on another computer
system.

Small but Powerful Language

AVPTI COMPUTER ENGINEERING DEPARTMENT 17


C is a small but very powerful language. It has fewer commands and statements. This makes it easy
to learn. It has very powerful operators and can directly access the hardware of the computer system. This
makes C a powerful language.

Case Sensitive Language


C is a case sensitive language. This means that a character written in lower case is different from
the same letter written in uppercase. All keywords of C language are 9in lowercase. Much of the source
program in C language is also written in lowercase.

Efficient Language
Since C can directly access the hardware of the computer system and uses fewer commands, the
compiled C programs run more efficiently on the computer than that of other languages.

Basis for C++


C is the basis for C++. The statements, commands and methodologies used in C are also available
in C++. Thus learning C is a first step towards learning C++.

Q8: What is the Structure of a C program?

Structure of C programs
The format according to which a program is written is called the structure of the program. The
structure of a C program consists of three main parts. These are given below:

Preprocessor Directives
The main() function
C Statements

A program example is given below. The first statement of the program is a preprocessor directive. This
preprocessor directive has been written to include the stdio.h header file. The second statement indicated
the main function. The C statements are written in the main function within curly braces.

#include <stdio.h>
main ()
{
printf ("This is my first Program");
}

AVPTI COMPUTER ENGINEERING DEPARTMENT 18


Q9: what is the Purpose of Preprocessor directive?

Preprocessor Directives
The Instruction that are given to the compiler before the beginning of the actual program are
called preprocessor directives. These are also known as compiler directives. These are written at the
beginning of the source code.
These preprocessor directives start with a number sign (#) and the keyword "include" or "define".
They are the instructions or directives that tell the compiler to take action(s) before compiling the source
code. The program that handles the preprocessor directives is called the preprocessor because it does some
processing before the compilation process starts.
For example, preprocessor directives are used to include header files in the program. The
preprocessor includes the specified header file into the source code before compiling.

Q10: what are Header files and what are they used for?

Header Files
Header files are part of the C compiler and contain definitions of standard library functions. There
are several header files. Each header file contains definitions of one type of functions only. For example,
the math.h header file contains definitions of mathematical functions available in C language.
Each header file has an extension .h. The preprocessor directive "include" is used to add a header
file into the program. The name of the file is written in angle brackets (<>) after "#include" directive. The
syntax to include a header file is:

#include <name of the header file>

Giving the name of the header file in angle brackets specifies that the header file is located in the
include directory of the compiler program.
The name of the header file can also be written in double quotes. When the name of the file is
written in double quotes. It specifies that the file is to be loaded from the current directory. The syntax to
include a header file is:

#include "name of the header file"

A header file is added if the functions defined in it are to be used in the program. For example, the
header file stdio.h had definitions of various built-in input and output functions. This file is included in a
program if any of its functions is used in the program.

AVPTI COMPUTER ENGINEERING DEPARTMENT 19


Q11: what is the main function in a C program?

The Main() Function


The "main()" function indicates the beginning of a C program. The "main()" must be included in
every C program. When a C program is executed, the control goes directly to the main() function.
The statements within this function are the main body of the C program. If main() function is not
included, the program is not compiles and error message is generated.
The syntax of the main() function is:

main()
{
program statements…
}

Q12: what are C statements?

C Statements
The statements of the program are written under the main() function between curly braces
{}. These statements are the body of the program. Each statement in C ends with a semicolon(;).
C is a case sensitive language. The C statements are normally written in lowercase letters
but, in some cases, these can also be written in uppercase.

Q13: What are C keywords?

Keywords:
The words that are used by the language for special purposes are called keywords. These are also
called reserved words. These have predefined uses and cannot be used for any other purpose in a C program.
These are always written in lower case
For example, in a C program, the keyword main is used to indicate the starting of the program,
include is used to add header files, int is used to declare an integer type variable. All these words are
keywords of C.
There are 32 words defined as keywords in C. Following is the completer list of C keywords:

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

AVPTI COMPUTER ENGINEERING DEPARTMENT 20


Q14: What are Token?

Tokens
A program statement consist of variable names, keywords, constants, punctuation marks, operators,
etc. In C, these elements of a statement are called tokens. In the following program segment:

main()
{
int a, b;
}

main, {, }, int, a, b and punctuation marks (,) and (;) are tokens of the program.

Q15: What are Comments and what are they used for?

The Comment Statement


The comment statement is a non-executable statement. It is used to add remarks or comments in a
program. The comments are usually given to explain logic of the program. The compiler ignores the
comments given in the program.

In C, a slash asterisk (/*) combination is used to specify the beginning and asterisk slash (*/) is used
to mark the end of the comment statement. For example

/* this is my first program in C */


/* Java Language is similar to C */

In the above example, two lines indicate the comment statements. The comments can be given at any place
in the source program. For example, the comments can also be given after a C statement as shown below:

Sum = a + c++; /*An example of Postfix operator*/


Sum = a + ++c; /*An example of Prefix Operator*/

Q16: Explain the Process of Creating a C program?

Creating C program:
There are four fundamental stages or steps in creating a C program. These steps are Editing,
Compiling, Linking and Executing a program. A brief description of these steps is given below:

Editing
Writing, Changing and revising the source code is called editing. In this step the source code of the
program is written and edited. The source code is written in any text editor. It is saved on the disk in an
ASCII text file.
Most C compilers come with an editor for writing the source code. This editor is specially designed
for writing the source code of C programs. It provides features that make the writing of the C source code

AVPTI COMPUTER ENGINEERING DEPARTMENT 21


easier. They highlight various parts of the program in different colors. This makes the source code more
readable.
However, any text editor can be used for writing the source code. The source code is saved on the
disk as an ASCII text file with an extension c.

Compiling
The converting of the source code into the machine code is called compiling. The program that is
used to convert the source code into the machine code is called the compiler.
The compiler takes the source code file of the C program stored on the disk. It converts it into the
machine code or the object code. Object code is the intermediate form of the program. In the first step, the
compiler creates object code and saves it in a new file on the disk. The file has an extension obj.
Before creating the object code, the compiler scans the source code for errors. If there are errors in
the source code, it does not compile the source code and indicates the errors. All errors must be removed
from the source code before creating the object code of the program.

Linking
In this step the necessary libraries are linked to the object code. After linking the libraries, the
executable file of the program is created.
A C program may contain predefined routines and functions. These functions are contained in
separate files. These files are part of the C compiler and are called library files or runtime libraries.
The linker can also detect errors. For example, if the source code uses a library function that does
not exist, the linker generates an error. Of there are errors, the linker does not create the executable file.
These are removed in the source code and a new object file is created. The new object file is then linked to
the libraries to create executable file. The executable file is created with the .exe extension. This file is
directly run on the computer system.

Executing
In this step, the program is actually run on the computer system. The executable file is run by giving
it to the system loader. For example, In Windows Operating System, when the name of an executable file
is double clicked, the system loader loads the file into the computer memory and executes it.
The executable file of the program may also contain certain errors. These errors can produce wrong
output or they may halt the system. These errors are located and removed in the source code and the source
code is again compiled to create a new executable file.

Q17: What is a C Preprocessor?

Preprocessor
Every C source code contains certain preprocessor directives at the beginning of the code. These
directives are instructions for the C preprocessor.
Preprocessor is the part of the C compiler. Before translating the program into the object code, the
preprocessor carries out the preprocessor directives. These directives start with the number sign (#). The
most commonly used preprocessor directives are #include and #define.
Usually preprocessor directives a meant to include a header file into the source code. Before
compiling the program, preprocessor includes the required header file into the source code. The new source
code is called the expanded source code. The compiler then translates the expanded source code into the
object code.

AVPTI COMPUTER ENGINEERING DEPARTMENT 22


Q18: What is Debugging? What are different types of errors in a program?

Debugging
Errors in a program are called "bugs" and tracking and removing these errors is called debugging.
There can be two main types of errors in a program. There are given below.

Syntax Errors
The rules for writing statements of a computer programming language are called syntax of the
language. The program statements are written strictly according to these rules. A single mistake in these
rules causes an error. This error is called syntax error. The compiler detects these errors. It does not compile
a program that contains syntax errors. These errors are easy to locate and remove.

Logical Errors
The errors in the logic of a program are called logical errors. The compile cannot detect these errors.
A program with logical errors runs correctly but it gives wrong result.
The logical errors may occur due to the following reasons.
 The input data may be incorrect because the out put of the program depends upon
the input data
 The sequence of instructions used in a program may be correct
 A mathematical formula used in program instructions may be incorrect. For example
using a division operator (/) in a formula when the multiplication operator (*) should
have been used causes wrong output.

These errors are most difficult to locate and remove. To track logical errors, all units of the program are
examined one by one.

Q1: Distinguish between constants and variables?

Constants:
The quantity whose value cannot change during the execution of the program is called constant. It
may be a numeric or a non numeric quantity.

Variables
A quantity whose value may change during execution of the program is called variable. It may be
a numeric or a non-numeric quantity. It is represented by a symbol called variable name. The variable name
consists of alphabets and digits.
A variable represents a storage or memory location in the computer memory. Data is stored into the
memory location. The name of the memory location, i.e. the variable name, remains fixed during execution
of the program but the data stored in that location may change from time to time.

Q2: Describe the rules for writing names of variables?

Rules for writing Variable Names:


The following are the rules for writing a variable name in a program in C:
 The first character of variable name may be an alphabetic character or an underscore (_).
 The first character of variable name cannot be a digit.

AVPTI COMPUTER ENGINEERING DEPARTMENT 23


 Blank spaces are not allowed in a variable name.
 Special characters, such as arithmetic operators, #, ^, cannot be used in a variable name.
 Reserved C words cannot be used as variable names.
 The maximum length of a variable name is up to 31 characters. However, the maximum length
depends upon the compiler.
 A variable name declared for one data type cannot be used to declare another data type.
C is a case sensitive language. Thus variable names with same spelling but different cases are treated as
different variable names. For example, variables 'Pay' and 'pay' are two different variables.
Following are some examples of the valid and invalid variable names.

Variable Name Valid / Invalid Remarks


Ahmed Valid
Perform Valid
double Invalid C reserved word
foxpro Valid
switch Invalid C reserved word
_large Valid
Float Valid The keyword float is in
lower case
Marriam Valid
int Invalid C reserved word
3taq Invalid Starts with a numeral
unsigned Invalid C reserved word
x-y Invalid Special character is not
allowed
Taq Ahd Invalid Space is not allowed

Q3: Describe various types of data in C?

Data Types in C:
The actual values used in a program are called data. There are four basic types of data in C. these are:

int Integer
float Real Values
double Large real values
char Characters

The following table shows various data types in C.

Data Types
Type Size in Bytes Data storage Range
int 16 bits (2 bytes) -32768 to 32767
short int 16 bits (2 bytes) -32768 to 32767
long int 32 bits (4 bytes) -2147483648 to
2147483647
unsigned int 16 bits (2 bytes) 0 to 65635

AVPTI COMPUTER ENGINEERING DEPARTMENT 24


unsigned long int 32 bits (4 bytes) 0 to 4294967295
float 32 bits (4 bytes) 1.1x10-38 to 3.4x10+38
long float 64 bits (8 bytes) 2.2x10-308 to 1.7x10+308
double 64 bits (8 bytes) 2.2x10-308 to 1.7x10+308
long double 80 bits (10 bytes) 3.4x10-4932 to 1.1x10-4932
char 8 bits (1 bytes) In case of strings, storage
capacity is from 1 byte to
65535 bytes.

Q4: Describe Integer type data?

The Integer Type Data:


An integer is a whole number, i.e. a number without a fraction or decimal point. It may have a
positive or a negative value. For example, 601, 250, -6 and 501 are integers.
Depending upon the maximum and minimum values, there are four types of integer type data in C.
these are:

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

The int:
The range of values of int data type depends upon the computer system being used and it takes two
to four bytes. In MS DOS, an integer type variable takes two bytes in the memory and the range of values
stored is from -32768 to 32767.
The maximum and minimum values for integer data types are specified in integer.h header file. The
minimum integer value is defined by INT_MIN and maximum integer value is defined by INT_MAX.

The short int:


A short int type data takes two bytes in memory. It can store integer values from -32768 to 32767.
The minimum integer value is defined by SHER_MIN and maximum integer value is defined by
SHRT_MAX.

The long int:


A long int type data takes four bytes in memory. It can store integer values from -2147483648 to
2147483647.
The minimum integer value is defined by LONG_MIN and maximum integer value is defined by
LONG_MAX.

The unsigned int:


The unsigned int can store only positive whole numbers. It takes two bytes in memory. It can store
integer values from 0 to 65,535.
The minimum unsigned integer value is 0 and maximum unsigned integer value is defined by
UNIT_MAX.

AVPTI COMPUTER ENGINEERING DEPARTMENT 25


Q5: Describe Real Type Data?
The real numbers consists of an integer and a non integer part. These are also called floating point
numbers. The data consisting of real numbers is called float type data.
Depending upon the maximum and minimum values, there are two types of real type data in C.
these are:

1. float
2. double

The float Type Data:


The float data is represented in decimal or exponential form. It may be signed or unsigned. For
example, 23.26, 16.21, -10.5 are floating type data.
The float type data takes four bytes in the memory and it can store real values from 1.1 x 10-38 to
3.4 x 10+38. it is accurate up to 6 decimal places.
The maximum and minimum values for float data types are specified in float.h header file. The
minimum float value is defined by FLT_MIN and maximum float value is defined by FLT_MAX.

The double Type Data:


The double data type is also a real type data. It is used to store large real values. A double type
variable takes 8 bytes in the memory and it can store real values from 1.7 x 10-308 to 1.7 x 10+308. It is
accurate up to 12 decimal places. The minimum double value is defined by DBL_MIN and maximum
double value is define by DBL_MAX.

The long double Type Data:


The long double type data are used to store very large real data values. A long double variable takes
ten bytes in the memory. A long double variable can store real values from 3.4 x 10-4932 to 1.1 x 10+4932. It
is accurate up to 18 decimal places.

Q6: Explain how real numbers are expressed in scientific or exponential notation?

The Exponential Notation


The general form of a real number is:
±n . m
where
n represents the integer part of real number.
m represents the fractional part of real number

A real type data can also be represented in exponential form. In this form, a real number is divided into
two parts i.e. a mantissa and an exponent. The general form of a real number in exponential form is:
±mE ±n or ±me ±n

where
m represent the mantissa. It has an absolute value greater than or equal to 1.0 and less than
10.0
n represents the value of exponent. It is a real number.

AVPTI COMPUTER ENGINEERING DEPARTMENT 26


For example, the real number 15000000.0 can be written in scientific form as: 1.5 x 106. In exponential
form it can be written as +1.5e+6 or 1.5e6
Where 1.5 represents mantissa (m) and 6 shows the value of exponent (n).
The following table gives a real number and its equivalent scientific and exponential forms.

Real Number Scientific Form Exponential Form


0.00005 5.0x10-5 5.0e-5
50000000.0 5.0x107 5.0E7
-0.00000162 -1.62x10-6 -1.620E-6
550.0 5.5x102 5.5e2
-3.66 -3.66x100 -3.66e0
578.9 5.789x102 5.759e2
-66.607 -6.6607x101 -6.6607e1

The following exponential forms of real numbers are invalid:

6E6.2 Exponent must be an integer value


7762 It is an integer value
2.31-e2 Sign is in wrong place
e6 Mantissa does not exist
0.87e9 *mantissa is less than 1
1.0e Exponent value missing
22.2e15 Mantissa is more than 10

Q7: Distinguish between precision and range of a real numbers?


Precision & Range:
The number of digits used by the computer for the decimal portion of the mantissa specify the
precision or accuracy of the real value. For example the speed of light is 299792000 m/s. It is represented
in the computer memory as 2.99792e8. Thus it requires a precision of at least 5 digits in the decimal portion
of the mantissa to accurately represent this quantity. Similarly, the number of digits allowed for the
exponent specify the exponent range of the real value. For example the exponent range of a float value is
from -38 to 38. any real value that requires a precision of 6 or less digits and the exponent range is from -
38 to 38, can be declared as of float type. If a value requires a precision of more than 6 digits, it may be
declared as double or long double type.

Q8: Describe Character type Data?


The char Type Data:
Character type data consists of alphabetic characters, numeric digits and special characters. A single
character takes 8 bits or one byte in the memory. The maximum and minimum values for character data
type are specified in integer.h header file. The minimum char value is defined by CHAR_MIN and
maximum char value is defined by CHAR_MAX. Arithmetic operations can also be performed on char
type variables.

AVPTI COMPUTER ENGINEERING DEPARTMENT 27


Q9: What are different types of constants in C?
Constants
A quantity that cannot change its value during execution of the program is called constant. There
are four types of constants in C. these are:
integer constants
floating point constants
string constants
character constants

Integer Constants
A numerical value without a decimal is called integer constant. The minus (-) sign is used to indicate
a negative integer constant. The use of (+) sign with a positive integer constant is optional.
Integer constants are used in expressions for calculations. The Integer constants are written without
".", "e", or "f". For example:
1000 -87
The long integer constants are written with L appended. For example:
8000000L -86316L

Floating Point Constants


Numeric values that have an integer as well as a decimal part are called floating point values. These
values can also be written in exponential notation. The floating point constants are written with "f" or "F"
appended. If f or F is not appended, the constant is treated as double. For example:
1000.f -9.87f 7.86F
The double constants are written with "." or "e". For example:
8000000.0 -8.63165e12
The long double constants are written with "." or "e" and L appended. For example:
8000000.L -8.631650e12L

Character Constants
A single character enclosed in single quotation marks is called character constant. For example 'a',
'/', and '+' represent character constants.

String Constants
A sequence of characters consisting of alphabets, digits and/or special characters enclosed in double
quotation marks is called string constants. For example, "Pakistan" and "Lahore" are examples of string
constants.

AVPTI COMPUTER ENGINEERING DEPARTMENT 28


Q10: What is meant by declaration of variables?
Declaration of Variables
Specifying the name of a variable and the data type it can hold is called declaration of the variable.
All variables that are used in a program are declared using variable declaration statement.
When a variable is declared, a certain number of bytes in the memory are allocated to the variable
name. The amount of the memory is allocated according to the type of variable. The value of the variable
is stored in this memory space. The syntax to declare a variable in C is:

type list of variable


where
type specifies data type of variables. For example, int is used to declare an integer
type variable and float is used to declare a float type variable.
List of Variables specifies a list of variables separated by commas. In a single statement more
than one variables, separated by commas, of same data type can be declared.
Different statements are used to declare variables of different data types. The integer type variables are
declared using the int keyword. For example, to declare a variable "abc" of integer type, the statement is
written as:
int abc;
The short integer type variables are declared using the short int keyword or simple short keyword. For
example, to declare a variable "marks" of short integer type, the statement is written as:
short int marks;
or short marks;

The long integer type variables are declared using the long int keyword. For example, to declare a variable
"length" of long integer type, the statement is written as:
long int length;
The float type variables are declared using the float keyword. For example, to declare a variable "length"
of float type, the statement is written as:
float height;
The double type variables are declared using the double keyword. For example, to declare a variable
"distance" of double type, the statement is written as:
double distance;
The long double type variables are declared using the long double keyword. For example, to declare a
variable "huge" of long double type, the statement is written as:
long double huge;
The character type variables are declared using the char keyword. For example, to declare a variable "nm"
of char type, the statement is written as:
Char nm;
More than one variable of the same data type can also be declared in one statement. In this case, the names
of the variables are written after the keyword separated by commas. For example, to declare three variables
"xyz", "d" and "s" of integer type, the statement is written as:
Int xyz, d, s;
To declare different types of variables, different statements are used. For example, to declare variables a
and xy as int types, b as float type, nm as character type and sum as double type, the statement are written
as:
int a, xy;
float b;
char nm;
double sum;

AVPTI COMPUTER ENGINEERING DEPARTMENT 29


Q11: What is meant by initialization of Variables?
Initialization of Variables:
When a variable is declared, a memory location is assigned to it. A value can also be assigned to it
at the time of its declaration. Assigning a known value to a variable at the time of its declaration is called
initializing of the variable. For example, to declare variables a, b, and c of integer type and assigning values
a = 110 and b = 60, the statements are written as:
int a=100, b=60, c;
float num=67.3f;
Q12: What are symbolic constants? How are they defined in a C program?
A symbolic constant is an identifier that represents a constant value. For example, the value of Л
(pi) is frequently used in engineering calculations. It represents a constant value and is approximately equal
to 3.141593. Instead of typing the numerical value each time it is to be used, this value is assigned to an
identifier and that identifier is written whenever the value of pi is to be used. This identifier represents a
constant value and is called the symbolic constant.
There are two way to define a symbolic constant. These are given below with detail.
 Using the "define" Directive
 Using the "const" Directive

The "define" Directive


It is a preprocessor directive. It is used to assign a constant quantity to an identifier. This directive
can be used anywhere in the program. Its syntax is given below.
#define identifier constant
where
identifier specifies the identifier name to which the constant value is to be assigned.
constant specifies the constant value that is to be assigned to the identifier.
The #define statement does not end with a semicolon. The identifier specified in the define directive is not
a variable it does not have any data type. The preprocessor simply replaces all occurrences of the identifier
with its value in the statements that follow the directive. For example, in the following statement, PI has
been defined to represent 3.141593f.
#define PI 3.141593f
It is a convention in C to write identifiers that appear in a #define statement in capital letters. This is done
to distinguish then from variables. A variable of the name of the identifier cannot be declared in the
program.

The "const" Qualifier


The "const" qualifier is used to define a variable with a value that is fixed. The value is assigned to
the variable at the time of its declaration. In the following statement, PI has been declared as floating point
variable and a fixed value 3.141593f has been assigned to it.
const float Pi=3.141593f;

AVPTI COMPUTER ENGINEERING DEPARTMENT 30


CHAPTER 3 – OPERATORS AND EXPRESSIONS

Que. Define an operator. List all the operators and explain any two of them.
Ans. An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations. They are used in programs to manipulate data and variables. They are used
generally a part of the mathematical or logical expression.
There are following categories of operators.
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.

The simple form to remember the operator is “L A R A S C B I”.

Arithmetic operators:The operators +,-,* and / all work the same way as they are used in other languages.
These can operate on any built in data type allowed in “C”. The unary minus operator multiplies its single
operand by –1, a number preceded by a munus sign changes its sign. As the arithmetic operators perform
mathematical functions the meaning is also same in language “C”. + means Addition, - means Subtraction,
* means Multiply, / means Division and % means Modulo division. It is subdivided into three categories
as follows.
Integer Arithmatic: When both the operands are integers the expression is called Integer
Arithmetic. Integer Arithmetic always have integer [Link] largest integer value depends on the
machine. For example a=14, b=3…
a+b=17 a-b=11 a*b=42 a/b=4(decimal part truncated)
a%b=2(remainder of division)
During the integer division, if both the operands are of the same sign, the result is truncated towards
zero. If one of them is negative, the direction of truncation is implementation dependent. i.e 6/7=0 and –
6/-7=0 but –6/7 may be zero or –1.
Similarly during modular division, the sign of the result is always the sign of the first
operand(the dividend). i.e –14%3= -2 -14 % -3 = -2 14 % -3 = 2 and also remember that
%(modulo operator) can not be used with real(floating) values.
Real Arithmetic: An arithmetic operation involving only real operands is called “real arithmatic”.
A real operand may assume values either in decimal or exponential notation. If x,y,z are floats, then,….
x= 6.0 / 7.0 = 0.857143
y= 1.0 / 3.0 = 0.333333
z= -2.0 / 3.0= -0.666667
Mixed Mode Arithmetic: When one of the operand is real and other is integer, the expression is
called mixed mode arithmetic expression. If either operand is of real(float) type, then only the real operation
is performed and the result is always a real number. i.e 15 / 10.0 = 1.5 where as 15 / 10 = 1

Relational Operators: The relational operators are generally used to compare two values, which is
necessary to take certain decisions. An expression such as A > B or 1 < 20 containing relational operators
is known as relational expression. The value of relational expression is either one or zero. The value is

AVPTI COMPUTER ENGINEERING DEPARTMENT 31


one if the specified relation is true and zero if it is false. Followings are some relational operators with their
meanings.

Opeator Meaning
< Is less than
> Is greater than
<= Is less than or equal to
>= Is greater than or equal to
== Is equal to
!= Not equal to
Relational expressions are used in decision making statements such as if and while to decide something.
Each relational operator needs two operands for comparison of their values. Hence, these operators are
binary operators. Following examples shows the expressions involving relational operators.

1. a<b
2. a==b+3
3. d>=5.66
4. alphabet !=’t’
5. (p+q)<=(t+r-5)
The expression a<b means “is a less than b?” The result of comparing a with b may be either ‘true’ or
‘false’. If it is false, the value of the expression is treated as 0, and if true as 1.

Example:

Program Output
main() 0
{ 1
int a=10,b=20,c=30,d,e;

d=a>b;
e=b<=c;
printf(“%d \n %d”, d,e);
}

Logical Operators: The logical operators are used when we want to test more than one condition and
make decisions. “C” has following three logical operators.

&& meaning logical AND


(expression1) && (expression2)

|| meaning logical OR
(expression1) || (expression2)

! meaning logical NOT


!(expression)

Operands Results
Exp1 Exp2 Exp1 && Exp2 Exp1 || Exp2

AVPTI COMPUTER ENGINEERING DEPARTMENT 32


0 0 0 0
0 Non-zero 0 1
Non-zero 0 0 1
Non-zero Non-zero 1 1

An example is :
a>b && a>c
An expression of this kind which combines two or more relational expressions is termed as a logical
expression or compound logical expression. It works similarly as an electronic gate works. For above
example, if a>b and a>c when both the conditions are true (1) then only the expression value is true
(1). If one of the conditions is false (0) then the whole expression value is false (0).
Similarly for a>b || a>c if only one of the conditions is true (1) then the whole expression value is true
(1) and if both the conditions are false (0) only then the whole expression value is false (0).
The third logical operator is the not operator, written as !. This operator reverses the value of the expression
it operates on; it makes true expression false and a false expression true.
y=9
!(y<10)
Will give false as result because we negate the condition with not operator.

Assignment Operator: Assignment operators are used to assign the result of an expression to a variable.
The assignment operator is ‘= ‘also used a ‘shorthand’ assignment operators.

Vop= exp; The operator op is known as the shorthand assignment operator.

Statement with simple assignment Statement with shorthand operator


operator
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
There are three advantages of shorthand operators:
1. What appears on the left-hand side need not be repeated and therefore it becomes easier to write.
2. The statement is more concise and easier to read.
3. The statement is more efficient.

Increment and Decrement Operators: These are unary operator since they operate only on one operand.
The operand has to be a variable and not a constant. Thus, the expression a++ is valid whereas 6++ is
invalid. The increment (++) and decrement (--) are very useful operators in “C”. The operator ++ adds 1 to
the operand while – subtracts 1 from the operand. They may have following forms…

These operators can be used either before or after their operand (i.e. in either ‘prefix’ or ‘postfix’ position),
so we can have a++ (postfix) as well as ++a (prefix), and a-- as well as --a. Prefix and postfix operators
have same effect if they are used in a different statements.
For example, the effect of the following two statements would be same.
a++
++a
However, prefix and postfix operators have different effects when used in association with some other
operators in C statements. For example;

AVPTI COMPUTER ENGINEERING DEPARTMENT 33


a=5
b=++a; will first increase the value of a to 6 and then assign that new value to b. This is exactly
same as if following statements have been executed.

a=5
a=a+1
b=a

On the other hand execution of the statement


b=a++; will first set the value of b to 5 and then increase the value of a to 6. The effect is now same
as if the following two statements had been executed:
b=a;
a=a+1;
The decrement operators are used in similar way, except, of course, the values of a and b are decremented
b=--a (prefix version) same as

a=a-1;
b=a;

b=a-- (postfix version) same as

b=a;
a=a-1;

Example program:
Program Output
main() 10
{ 11
int a=10,b=10;
printf(“%d”, a++);
printf(“%d”, ++b);
}

These operators are generally used in loops.

Conditional Operator (Ternary Operator): A ternary operator pair “ ?: ” is used in c to construct


conditional expression of the form.

exp1 ? exp2 : exp3;


here exp1, exp2 and exp3 are expressions. The ? : operator works as follows: exp1 is evaluated first , if it
is true then the expression exp2 is evaluated and becomes the value of the expression. If exp1 is false, exp3
is evaluated and becomes the value of expression.
In other words it works similary to if else. See the following example.

A=10; if(A>B)
B=20; X=A;
X=(A>B)?A:B; else
X=B;
For the above example the value of X=20.
Example program:
Program Output

AVPTI COMPUTER ENGINEERING DEPARTMENT 34


main() Input : 2
{ b=4
int a,b; Input : 6
scanf(“%d”,&a) b=3
b=(a>5 ? 3:4)
printf(“b=%d”,b);
}

Bitwise Operators:
Normally the higher level languages don’t support the bit-wise operators as they denotes the lower level
operations which are common in assembly / machines languages. But “C” language is exception. It supports
the bit-wise operators. Two operands are compared on a bit-by-bit basis. Hence both the operands must be
of the same type( either char or int)
Throughout the discussion of bitwise operators we are going to use a function called showbits(). The task
of showbits() is to display the binary representation of any integer or character value. For example;
Assume n=4
Then the output of showbits(n)=0100
Following operators are used as bit-wise operator with their meaning….

Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR
<< Left Shift
>> Right Shift
~ 1’s complement

X= 0101 0101 0101 0101 0101


Y= 0111 0111 0111
Z= X&Y=5=0101 X^Y=2=0010 X|Y=7=0111 X<<2=20=10100 X>>1=2=0010

From above table it is clear how the bitwise operator works.

Special Operators: C supports some special operators such as Comma operator and sizeof operator.
Comma Operator: The comma operator can be used to link the related expressions together. A
comma linked-list 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. Since comma operator has the
lowest precedence of all operators the parentheses are necessary. We can also use it in for loop as follows:
for(n=1, m=10; n<=m; n++,m++)

Sizeof Operator: The sizeof is a compile time operator and, when used with an operand, it returns
the number of bytes the operand occupies. The operand may be a variable, a constant or a data-type
qualifier.
For Example: m = sizeof(sum); k = sizeof(235L);
n = sizeof(long int);
the sizeof operator normally used to determine the lengths of arrays and structutes when their sizes
are know to the programmer.

AVPTI COMPUTER ENGINEERING DEPARTMENT 35


Que. What is precedence and associativity of operators ?
Ans. To evaluate an arithmetic expression properly, we have to use the precedence and associativity of
the operators involved in expression. Precedence means which operator is operated first and Associativity
means the direction of the operator is operated. Follwing is given the Operators and Associativity in the
decreasing order.

Operators Associativity
( ) , [ ], -> Left to right
! ~ ++ -- +(unary plus) – (unary minus) * &(Address) sizeof Right to left
* / % Left to right
+ - Left to right
<< >> (bitwise operators) Left to right
< <= > >= (relational operators) Left to right
== != Left to right
& (bitwise AND) Left to right
^ (bitwise EX-OR) Left to right
| (bitwise OR) Left to right
&& (Logical AND) Left to right
| | (logical OR) Left to right
? : (conditional operator) Right to left
= *= /= %= += - = &= ^= |= <<= >>= (assignment) Right to left
, (comma operator) Left to right

Que. What is Type Conversion & Type Casting?


Ans. Type Conversion: We know that an expression involves the constants and variables of different
types. In this case, the evaluation of the expression is done strictly with the use of the type conversion rules
of the “C” language. While evaluating an expression, at a time only one operator is taken into consideration.
If both the operands of the operator under consideration are not same, then the operand with the lower type
is lifted to the higher type and the operation is performed. This is true for all the operators in whole
expression. It is clear from following example…

int a,e;
float b,d;
double c;

e = a * b + c / d

(float) (double)

(float) (double)

(int) (double)

The rules applied during the evaluation are as follows:


1. First all the short and char types in exp. are converted to int.
2. if one of the operand is long double then the other operand is converted to long double
AVPTI COMPUTER ENGINEERING DEPARTMENT 36
3. Otherwise if one of the operand is double, then other operand is converted to double and answer
is double.
4. Otherwise if one of the operand is float then other operand is converted to float and answer is float.
5. Otherwise if one of the operand is unsigned long int, then other operand is converted to unsigned
long int and answer is unsigned long int.
6. Otherwise if one of the operand is long int and other operand is unsigend int then (A) if unsigned
int can be converted to long int, then it is converted to long int and the answer is long int. (B) else
both are converted to unsigned long int and the result is unsigned long int.
7. Otherwise if one of the operand is long int, then other operand is converted to long int and answer
is long int.
8. Otherwise if one of the operand is unsigned int, then other operand is converted to unsigned int
and answer is unsigned int.
9. After performing above process, the answer of the expression is assigned to the variable on the left
side after converting it to the type of the variable on left side. The following points to be noted for
this conversion and assignment.
 If float is assigned to int, the fractional part is truncated.
 If double is assigned to float, rounding occurs.
 If long int is assigned to int, additional bits are dropped.

Conversion rules are shown as tabular form as follows:

Operand 1 Operand 2 Result Operand 1 Operand 2 Result


Char Char Char Int Char Int
Char Int Int Int Int Int
Char Long int Long int Int Long int Long int
Char Float Float Int Float Float
Char Double Double Int Double Double

AVPTI COMPUTER ENGINEERING DEPARTMENT 37


Operand 1 Operand 2 Result Operand 1 Operand 2 Result
Long int Char Long int Float Char Float
Long int Int Long int Float Int Float
Long int Long int Long int Float Long int Float
Long int Float Float Float Float Float
Long int Double Double Float Double Double

Operand 1 Operand 2 Result


Double Char Double
Double Int Double
Double Long int Double
Double Float Double
Double Double Double

Few Practical examples are shown below:

Operation Result Operation Result


5/2 2 2/5 0
5.0/2 2.5 2.0/5 0.4
5/2.0 2.5 2/5.0 0.4
5.0/2.0 2.5 2.0/5.0 0.4

Type Casting: Some times user needs explicit type conversion. For example, int/int is always int, but if
we need the answer in float then explicit type casting is useful. Consider the following statements.

float average;
int sum= 25;
int n = 10;
average = (float)sum / n;
where sum/n results into 2.5 rather than 2 because the division is performed after converting the sum into
float and the result of float/int is always float. The conversion does not change the value. It only changes
the fype for evaluation process only.

This type of conversion is known as type casting . It is written in following form.

(type_name)expression;
where, type_name is type to which the expression value is casted. It can be any valid data type of “C”.

Extra Questions:
1. Explain the following operators. May-05[04]
1. ?.
2. Size of.
3. ++ and -- . [09]
4. Conditional (?:)
5. Bit wise
6. Cast

AVPTI COMPUTER ENGINEERING DEPARTMENT 38


CHAPTER 4 – DECISION MAKING STATEMENTS
Branching and Looping:
Control statements enable us to specify the order in which the various instructions in a program are
to be executed by the computer. In other words, the control statements determine the ‘flow of control’ in a
program. There are four types of control statements in C. They are:
a. Sequence control statement
b. Selection or Decision control statement
c. Case control statement
d. Repetition control statement
The sequence control statement ensures that the instructions in the program are executed in the same order
in which they appear in the program.
Decision and Case control statements allow the computer to take a decision as to which statement to be
executed next.
The loop control statement helps computer to execute a group of statement repeatedly till condition is
satisfied.
Que: Explain simple if-else, nested if-else and ladder if-else statements.
Ans: The if-else statement is a decision making statement. It is generally used to check certain conditions.
Depending on the result the execution control is transferred to particular statement.
Simple if-else: This is the simplest decision making statement. The format is:
if (this condition is true)
Execute this statement;
else
Execute this statement;

Here, the condition is represented by relational or logical expression. If condition is true then
statement 1 is executed and if condition is false, then statement 2 is executed. The statement 1 and/or
statement 2 can be either single statement or compound statement i.e group of statements. A compound
statement must be enclosed in pair of braces { }. Enclosing a single statement in braces { } is not
compulsory. Note that this conditional statement doesn’t require a semicolon.

The else part in if-else is optional. The if statement without else looks like:
if(condition)
statement;
For example
main()
{
int num;
printf(“Enter a number greater than 5”);
scanf(“%d”,&num);
if(num>5)
printf(“What an obedient servant you are!”);
}
In this case, if condition is true, then statement is executes, otherwise control transferred to the
statement that follows the if structure. The fig. shows the above explanation…

Nested if-else: Generally the nested if else is used in multiple condition checking. Here any one condition
is taken as main condition. The format is given below:

AVPTI COMPUTER ENGINEERING DEPARTMENT 39


if(condition1)
{
if(condition2)
statement1;
else
statement2;
}
else
statement3;
statementX;

Here if the condition1 is true only then control is transferred to the condition2 and if it is true then only
statement1 is executed. If condition1 is true and condition2 is false then statement2 is executed. If
condition1 is false then statement3 is executed after that the control will be transferred to the next statement
after the if-else structure.
For example:
main()
{
int i;
printf(“Enter either 1 or 2”);
scanf(“%d”,&i);
if(i==1)
printf(“You would go to heaven!);
else
{
if(i==2)
printf(“Hell was created with you in mind”);
else
printf(“how about mother earth”);
}
}
Ladder if-else: The ladder if-else is very useful to allow multiple choice. It means to select one alternative
from many. The format is given below:

if(condition1)
statement1;
else if(condition2)
statement2;
else if(condition3)
statement3;
.
.
.
else if(conditionN)
statementN;
else
default_statement;

In above multiple if-else, compound statement must be enclosed in pair of braces { }. The last else is
optional. Here the condition1 is evaluated first and if it is true then statement1 is executed otherwise
condition2 is evaluated and if it is true then statement2 will be executed and so on. If all the conditions
become false then default_statement is executed.
AVPTI COMPUTER ENGINEERING DEPARTMENT 40
For example:
Que: The marks obtained by a student in 5 different subjects are input through the keyboard. The student
gets a division as per the following rules:
% >= 60 :First division
% >50 but %<60 :Second division
% >40 but <50 :Third division
% < 40 :Fail
Program:
main()
{
int m1,m2,m3,m4,m5;
float per;
printf(“Enter the marks in 5 subjects”);
scanf(“%d %d %d %d %d “, &m1, &m2, &m3, &m4, &m5,);
per=(m1+ m2+ m3+ m4+ m5)/5;

if(per >=60)
printf(“First Division”);
else
{
if(per >=50 && per <60)
printf(“Second Division”);

else
{
if(per >=50 && per <60);
printf(“Second Division”);

else
{
if(per >=40 && per <50);
printf(“Third Division”);
else
printf(“Fail”);
}
}
}
}
Ultimately collectively the various form of if constructs can be organized as:

Sr Form of if Example
no
1. If(expression) If(i==1)
Statement1; Printf(“%d”,i);
2. If(expression) If(marks>40)
{ {
statement 1; Printf(“You have passed”);
statement 2; Printf(“You can get prize”);
……….. }
statement n;

AVPTI COMPUTER ENGINEERING DEPARTMENT 41


}
3. If(expression) If(age>=18)
Statement 1; Printf(“You can vote”);
Else Else
Statement 2; Printf(“ You need to wait!);

4. If(expression) If(sub1marks>40 && sub2marks>40)


{ {
Statement 1; average= (sub1marks+ sub2marks)/2;
Statement 2; printf(“Average = %d”, average);
…………... }
statement n; else
} printf(“You need to work hard”);
Else
{
Statement 1;
Statement 2;
……………
statement n;
}
5. If(expression) If(i==2)
{ Printf(“You would go to heaven”);
statement 1; Else
statement 2; {
………….. if(i==2)
statement n; Printf(“Hell was created with you in mind”);
} Else
else if(expression) Printf(“Hell was created with you in mind”);
{ }
statement 1;
statement 2;
…………..
statement n;
}
else if(expression)
{
statement 1;
statement 2;
…………..
statement n;
}
……………
……………
else
{
statement 1;
statement 2;
…………..
statement n;
}

AVPTI COMPUTER ENGINEERING DEPARTMENT 42


}

6. If(expression) If(per>=60)
{ Printf(“First Division”);
Statement 1; Else
Statement 2; {
………….; if(per>=50)
statement n; Printf(“Second Division”);
} Else
else {
{ if(per>=40)
if(expression) Printf(“Third Division”);
{ Else
Statement 1; Printf(“Fail”);
Statement 2; }
………….; }
statement n;
}
else
{
if(expression)
{
Statement 1;
Statement 2;
………….;
statement n;
}
else
{
Statement 1;
Statement 2;
………….;
statement n;
}
}
}

Que: Explain switch-case statement with example.


Ans: The switch in c is a multi-choice statement. It provides one choice for each value of variable or
expression. The block of statements associated with the choice whose value is same as the value of variable
or expression is executed. The format of the switch statement is given below.
switch(variable or integer expression)
{
case label1 : statement_block1;
break;
case label2 : statement_block2;
break;
case label3 : statement_block3;
break;

AVPTI COMPUTER ENGINEERING DEPARTMENT 43


case label4 : statement_block4;
break;
.
.
default : default block;
}
Here label1, label2… Show the possible values of the variable or expression. For each value of variable or
expression, one statement block is provided. For example statement_block1 is associated with the label1.
The statement block consists of one or more statements. After every statement block, there is break which
sends control to the next statement after switch statement. The last choice is default which is chosen when
value of variable or expression does not match to any of the labels. In this case, the statement block called
default block is executed. But the default is optional and hence if it is not there and value does not match
to any label, no statement block executes. The control moves to next statement after switch immediately
after executing the block of statements associated with the label whose value matches the value of variable
or expression. If value does not match to any label and default is present, then only default block executes.
The switch-case and ladder if-else both are multi-choice statements, but they are different. The major
difference is that in if-else, there is a separate expression or condition for each choice and the statements
associated with the first condition or expression whose value is true are executed. While in switch, there is
only one expression and the choice whose label value is same as value of this expression, is chosen.
The integer expression following the keyword switch is any C expression that will yield an integer value.
It could be an integer constant like 1,2,3, or an expression that evaluates to an integer.
The keyword case is followed by an integer or a character constant. Each constant in each case must be
different from all the others.
Consider the following example.
….
a = 10; b = 5;
switch(x)
{
case 1: printf(“%d\n”,a+b);
break;
case 2: printf(“%d\n”,a-b);
break;
case 3: printf(“%d\n”,a*b);
break;
case 4: printf(“%d\n”,a/b);
break;
default : printf(“No operation\n”);
} ….. ……
Here for x=1 then output is 15. for x=2 then output is 5, x=3 then output is 50and x=4 output is 2. For any
value of x other than x=1,2,3,4, the message “No operation” is printed.

Tips and Traps:


1. We can put cases in any order we please.
2. We are also allowed to use char values in case and switch.
3. We can mix integer and character constants in different cases of a switch
main()
{
int c=3;

switch(c)
{
AVPTI COMPUTER ENGINEERING DEPARTMENT 44
case ‘v’ :
printf(“I am in case v\n”);
break;
case ‘3:
printf(“I am in case 3n”);
break;
case ‘12’ :
printf(“I am in case 12\n”);
break;
}
}
4. Sometimes there may not be any statement in some of the cases in switch.
main()
{
char ch;
printf(“Enter any of the alphabet a or b”);
scanf(“%c”,&ch);

switch(ch)
{
case ‘a’:
case ‘A’:
printf(“a as in ashar”);
break;
case ‘b’:
case ‘B’:
printf(“b as in brain”);
break;
case ‘c’:
case ‘C’:
printf(“c as in cookie”);
break;
default:
printf(“ Wish you knew what are alphabets”);
}
}

5. Even if there are multiple statements to be executed in each case there is no need to enclose
these within a pair of braces.
6. Switch offers a better way to writing as compared to if.
7. A switch can occur within another.
The disadvantage of switch statement is that we must have character or integer constant after case.

Que: Explain the goto statement.


Ans: The goto statement in “C” programming is used to transfer the control unconditionally from one
part of program to other part. The “C” is structured programming language where use of the goto statement
is dangerous because it can easily violate the rules of structured programming. For example, one may use
goto to transfer control from outside of loop to middle of the body of the loop. This is the violation of the
rule that there must be only one entry in the loop structure. Hence, it is recommended to avoid the use of
goto as far as possible or should be used very carefully, but there are some situations in which use of goto
is advised. The format of goto statement is as follows.
goto label;
AVPTI COMPUTER ENGINEERING DEPARTMENT 45
Here, label is the label to the statement to which goto transfers control. The meaning is that the
execution begins from this labeled or target statement.

goto label; label :


… statement;
… …
label : …
statement; goto label;

(A) forward jump (B) backward jump


Here two possible use of goto statement : forward and backward. In forward, the target statement
comes after the goto, while in backward, target statement comes before goto. Note that the label must be
followed by colon (:) at the target statement. The label name can be formed using the rules of the forming
the identifier names. That means a label is a valid identifier.

Que: What is the importance of looping ? explain entry controlled loop(any one) and exit controlled
loop.
Ans: If you want to execute some specific part of program (body of loop) repeatedly then looping is very
useful. It generally checks the condition, and executes the specific part (body of loop) if the condition is
true. This process is repeated until the condition becomes false. So, it works like a counter.

Entry controlled loops: In entry controlled loop, the condition is checked first and then body of
loop is executed. It means, first it checks the condition and if it is true then the body of loop will be executed.
After that it again checks the condition, and if it is true then body of loop will be executed again. This will
be repeated until the condition become false. If the condition is false very first time, then control is
transferred to the next statement outside of the loop.
while and for are examples of entry controlled loops.

while loop:
The structure of while loop is as given below.
while (test condition)
{
Body ;
}
statementX;
Here, condition is evaluated first and if it is true, then the statements in the body of the loop are
executed. After executing body, the condition is evaluated again and if it is true body is executed again.
This process is repeated again as long as the condition is true. The control moves out, once the condition
is false. It is not necessary to enclose body of loop in pair of braces { } if body contains only one statement.
The flow chart is given as below.
For example, the while loop can be written as follows to print 1 to 10.


i=1;
while (i <= 10)
{
printf(“%d\n”,i);
i++;
}

AVPTI COMPUTER ENGINEERING DEPARTMENT 46


Here, first i is initialized to 1. the value of i is printed and then i is incremented. This process is
repeated as long as I is less than or equal to 10. Once i is 11, the condition in while is false and control
comes out of loop.
for loop:
The for loop is another entry controlled loop that provides a more concise loop control structure.
The general form of the for loop is

for(initialization; test-condition; increment or decrement)


{
body of the loop;
}
The execution of the for is as follows:
1. Initialization of the control variables is done first,using assignment statements such as i = 1 and
b=0. The variables I and count are known as loop-control variables.
2. The value of the control variable is tested using the test-condition. The test-condition is a
relational expression, such as i<10 that determines when the loop will exit. If the condition is
true, the body of the loop is executed; otherwise the loop is terminated and the execution
continues with the statement that immediately follows the loop.
3. When the body of the loop is executed, the control is transferred back to the for statement after
evaluating the last statement in the loop. Now, the control variable is incremented using an
assignment statement such as i=i+1and the new value of the control variable is again tested to
see whether it satisfies the loop condition. If the condition is satisfied, the body of the loop is
again executed. This process continues till the value of the control variable fails to satisfy the
test condition.
The for statement also allows negative increment. The examples are given below.



for(x=0;x<=9;x++)
{
printf(“%d”,x);
}
printf(“\n”);

In above example the for loop is executed 10 times and prints the digits 0 to 9 in one column.

for(x=9;x>=9;x--)
{
printf(“%d”,x);
}
printf(“\n”);

In above example the for loop is executed 10 times and prints the digits 9 to 0 in one column.
Exit controlled loop: On some occasions it might be necessary to execute the body of the loop
before the test is performed. Such situations can be handled with the help of the do statement. The syntax
is as follows.

do
{
body of the loop;
}
while(test-condition);
AVPTI COMPUTER ENGINEERING DEPARTMENT 47
On reaching the do statement, the program proceed to evaluate the body of the loop first. At the end
of the loop, the test-condition in the while statement is evaluated. If the condition is true, the program
continues to evaluate the body of the loop once again. This process continues as long as the condition is
true. When the condition becomes false, the loop will be terminated and the control goes to the statement
that appears immediately after the while statement. Since the test-condition is evaluated at the bottom of
the loop, the do…while construct provides an exit-controlled loop and therefore the body of the loop is
always executed at least once. For example,


i=1;
sum=0;
do
{
sum= sum + i;
i=i+2;
}
while(sum<40 || i<10);
printf(“%d %d\n”, i, sum);
….
The loop will be executed as long as one of the two relations is true.
The flow chart of exit controlled loop is as given below.
Extra Questions:

1. Differentiate between: For loop and While Loop May-05 [04]


2. Explain switch-case statement with example. May-05 [04],[05]
3. Attempt any two of the following Nov-01 [10]
i. Giving suitable example explain nested if statement
ii. Give the syntax of while and explain giving example.
iii. Explain the use of break and continue statement with example.
The break statement:
We often come across a situation where we want to jump out of a loop instantly, without waiting
to get back to the conditional test. The keyword break allows us to do this. When break is encountered
inside any C loop, control automatically passes to the first statement after the loop.
A break is usually associated with an if. For example:
main()
{
int num,i;
printf(“ Enter a number “);
scanf(“%d,&num);
i=2;
while(i<=num-1)
{
if(num % i==0)
{
printf(“Not a prime number”);
break;
}
}
if(i==num)
printf(“Prime number”);
}
The keyword break, breaks the control only from the inner while loop in which it is placed.
AVPTI COMPUTER ENGINEERING DEPARTMENT 48
The Continue statement:
In some situations we want to take the control to the beginning of the loop, bypassing the statement inside
the loop which have not yet been executed. The keyword continue allow us to this. When the keyword
continue is encountered inside any loop, control automatically passes to the beginning of the loop.
A continue is usually associated with an if. As an example, let’s consider the following program.
main()
{
int i,j;
for(i=1;i<=2;i++)
{
for(j=1;j<=2;j++)
{
if(i==j)
continue;
else
printf(“%d %d\n”,I,j);
}
}
}
The output of the above program would be:
12
21
Note that when the value of I equals that of j, the continue statement takes the control to the for loop (inner)
bypassing rest of the statements pending execution in the for loop (inner).
3. Attempt any two of the following May-02 [10]
i. Give the syntax of do-while statement giving suitable example
ii. Give the syntax of switch statement and giving suitable example.
iii. Give the use of exit and continue statements with example.
The exit() function:
Exit() is a standard library function (stdlib.h) that cones ready-made with the C compiler. Its purpose is to
terminate the execution of the program. It works quite different than the break statement. For example:
main() main()
{ {
int i; int i;
for(i=1;i<=100;i++) for(i=1;i<=100;i++)
{ {
if (i==3) if (i==3)
break; exit(0);
} }
printf(“Out of loop”); printf(“Control never comes to here”);
} }
Break:Breaks the loop Exit():Terminate the program execution

4. Explain for control structure with suitable example. [06]


5. Differentiate between: Do While and While Loop May-05 [04]

AVPTI COMPUTER ENGINEERING DEPARTMENT 49


CHAPTER – 5 – ARRAY ONE DIMENSIONAL

Que: Define array. Explain the declaration and initialization of 1-D array.
Ans: An array is a group of related data items that share a common name. For example if we define an
array name price to represent a set of prices of a group of items. A particular value is indicated by writing
a number called index number or subscript in brackets after the array name. For example, price[10]
represents the price of 10th item. While the complete set of values is referred to as an array, the individual
values are called elements. Array can be of any variable type.

A list of items can be given one variable name using only one subscript and such a variable is called
a single-subscripted variable or a one-dimensional array.
For ex., int num[5]; and the computer reserves five storage locations as below:

num[0] 10
num[1] 20
num[2] 30
num[3] 40
num[4] 15

These elements may be used in programs just like any other C variable.
For ex, a=num[0]+100;
num[2]=num[3] + num[4]; etc.

The general format of declaration of an array is : data_type variable-name[size];


The data type specifies the type of an element that will be contained in the array, such as int, float etc. and
the size indicates the maximum number of elements that can be stored inside the array.

We also can initialize the elements of arrays in the same way as the ordinary variables when they are
declared. The general form of initialization of arrays is:
static data_type variable-name[size] = { list of values };
The values in the list are separated by commas. For example,
static int number[3]= { 5,5,5};
will declare the variable number as an array of size-3 and will assign 5 to each element. If the number of
values in the list is less than the number of elements, then only that many elements will be initialized.
The remaining elements will be set to zero automatically.
The size may be omitted. In such case the compiler allocates enough space for all initialized elements. For
ex. static int counter[] = {1,1,1,1};
Will declare the counter array to contain four elements with initial values 1.

Que: Explain the declaration and initialization of 2-D array.


Ans: In mathematics we represent a particular value in a matrix by using two subscripts such as Vij. Here
V denotes the entire matrix and Vij refers to the value in the ith row and jth column. C allows us such
tables of items by using tow dimensional arrays..
Two dimensional arrays are declared as follows:
data_type arr_name[row_size][column_size];

For example, int v[4][3];


two dimensional arrays can be stored in memory as shown in fig.

AVPTI COMPUTER ENGINEERING DEPARTMENT 50


Column 0 Column 1 Column 2
[0][0] [0][1] [0][2]
Row 0 100 200 300
[1][0] [1][1] [1][2]
Row 1 110 210 310
[2][0] [2][1] [2][2]
Row 2 300 310 320
[3][0] [3][1] [3][2]
Row 3 410 400 420

As an ordinary variable we can use the elements of two dimensional arrays for arithmetic operations.
Like the one dimensional arrays , two dimensional arrays may be initialized by following their declaration
with a list of initial values enclosed in braces, for example:

static int table[2][3] = {0,0,0,1,1,1};


initializes the elements of the first row to zero and the second row to one. The initialization is done
row by row.
The above statement can be written as : static int table[2][3] ={ {0,0,0},{1,1,1} };
Or static int table[2][3] = {
{0,0,0},
{1,1,1}
}; as a matrix form. In above syntax commas are required after each brace that
closes off a row, except in the case of the last row. If the values are missing an initializer, they are
automatically set to zero.

AVPTI COMPUTER ENGINEERING DEPARTMENT 51

You might also like