[go: up one dir, main page]

0% found this document useful (0 votes)
138 views69 pages

Unit 2

This document provides an overview of the basics of C programming, including: 1) An introduction to the C programming language, its history and applications. 2) The basic structure of a C program, including documentation, link, definition, global declaration, function prototype declaration, main function, and user defined function definition sections. 3) The steps to write C programs, including creating, compiling, and executing a program.

Uploaded by

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

Unit 2

This document provides an overview of the basics of C programming, including: 1) An introduction to the C programming language, its history and applications. 2) The basic structure of a C program, including documentation, link, definition, global declaration, function prototype declaration, main function, and user defined function definition sections. 3) The steps to write C programs, including creating, compiling, and executing a program.

Uploaded by

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

INDEX

Unit -2 CONTENT PAGE NO


Introduction to C 48
programming
fundamentals 49

Structure of a C program 51

compilation and linking 53


processes
Constants 56

Variables 59

Data Types 64

Expressions using operators 69


in ‘C’
Managing Input and Output 83
operations

Decision Making and 87


Branching
Looping statements 90

solving simple scientific and 96


statistical problems

UNIT –I

47
C PROGRAMMING BASICS

Problem formulation – Problem Solving - Introduction to ‘ C’ programming –fundamentals structure of a ‘C’


program – compilation and linking processes – Constants, Variables – Data Types –Expressions using operators
in ‘C’ – Managing Input and Output operations – Decision Making and Branching – Looping statements –
solving simple scientific and statistical problems.

INTRODUCTION TO C

C is a programming language which is developed by Dennis Ritchie between


the years 1963 and 1973.He developed this language in AT&T Bell
Labs.Actually C got it’s name as a sequence to it’s parents versions.First Dennis
Ritchie named it as A and B.After some updates he named it as C and is popular
by that name.C was originally first implemented on the DEC PDP-11 computer
in 1972.In 1978, Brian Kernighan and Dennis Ritchie produced the first
publicly available description of C, now known as the K&R standard.

The UNIX operating system, the C compiler, and essentially all UNIX
applications programs have been written in C. C has now become a widely used
professional language for various reasons.

 Easy to learn

 Structured language

 It produces efficient programs.

 It can handle low-level activities.

 It can be compiled on a variety of computer platforms.

Facts about C
 C was invented to write an operating system called UNIX.

 C is a successor of B language which was introduced around 1970.

 The language was formalized in 1988 by the American National Standard


Institute (ANSI).

 The UNIX OS was totally written in C by 1973.

 Today C is the most widely used and popular System Programming


Language.

48
 Most of the state-of-the-art softwares have been implemented using C.

 Today's most popular Linux OS and RBDMS MySQL have been written
in C.

ALGOL -> 1960 ->International group


BCPL -> 1967 ->Martin Richards
B -> 1970 ->Ken Thompson
C -> 1972 ->Dennis Ritchie
ANSI -> 1989 -> ANSI Committee
ANSI/ISOC-> 1990 -> ISO Committee

 All modern computer languages are started through the ALGOL


language in 1960.
 After the COBOL was being used for commercial applications.
 FORTAN was developed for scientific applications.
 A committee was formed to develop a new language called Combined
Programming Language (CPL) at Cambridge University.
 Basic CPL was derived by BCPL.
 BCPL was developed by Martin Richards at Cambridge University by
1967.
 At the same time a language called ‘B’ was developed by Ken Thomson
at AT & T’s Bell labs in 1970.
 Then C language is developed by Dennis Retchie in 1972 with some
additional features of BCPL and B which is very simple.
 ANSI C American National Standard Institute has began to work on a
standardized definition of the ‘C’ language that makes it still powerful.

Types of Language:

Low level Language (or) Machine Language.


Machine code or machine language is a set of instructions
executed directly by a computer's central processing unit (CPU). Each
instruction performs a very specific task, such as a load, a jump, or an
ALU operation on a unit of data in a CPU register or memory.

High Level Language normal English, human understandable language,


machine independent, C, C++, etc…

Middle Level Language

C Language is also called as Middle level Language because ‘C’ stands


in between Low level Language (nor) high level language (i.e) it
performs task of low level languages as well as high level language. We
49
can write program for operating, application programs, Assembly
language programs in ‘C’ Languages. UNIX operating system is written
in ‘C’ Language.

Features and Applications of ‘C’ Languages:

 C is a general purpose, structured programming language.


 C has built in functions and operators can be used to write any complex
program.
 C is well suited for writing system software as well as application
software.
 C is middle level language. It supports low level & high level language.
 C is a powerful, efficient, compact & flexible.
 C is highly portable. It can run in different operating systems
environment.
 C is robust language.
 C language allows reference to memory allocation with the help of the
pointers.
 C language allows dynamic memory allocation.

Steps to write C programs and get the output:

Below are the steps to be followed for any C program to create and get the
output. This is common to all C program and there is no exception whether its a
very small C program or very large C program.

Creation, Compilation and Execution of a C program:

50
 If you want to create, compile and execute C programs by your own, you
have to install C compiler in your machine. Then, you can start to execute
your own C programs in your machine.

Basic structure of C program:

Structure of C program is defined by set of rules called protocol, to be followed


by programmer while writing C program. All C programs are having
sections/parts which are mentioned below.

1. Documentation section
2. Link Section
3. Definition Section
4. Global declaration section
5. Function prototype declaration section
6. Main function
7. User defined function definition section

Example C program to compare all the sections:

compare all the sections of a C program with the below C program.

/* C basic structure program Documentation section

*/#include <stdio.h> /* Link section */


int total = 0; /* Global declaration and definition section */
int sum (int, int); /* Function declaration section */
int main () /* Main function */
{
printf (“This is a C basic program \n”);
total = sum (1, 1);
printf (“Sum of two numbers : %d \n”, total);
return 0;
}
int sum (int a, int b) /* User defined function */
{ /* definition section */
return a + b;
}.
Output:

This is a C basic program


Sum of two numbers : 2 .
51
Description for each section of a C program:

 Let us see about each section of a C basic program in detail below.


 Please note that a C program mayn’t have all below mentioned sections
except main function and link sections.
 Also, a C program structure mayn’t be in below mentioned order.

S.No Sections Description


We can give comments about the program, creation or
modified date, author name etc in this section. The
characters or words or anything which are given
Documentation between “/*” and “*/”, won’t be considered by C
1
section compiler for compilation process.These will be ignored
by C compiler during compilation.
Example : /* comment line1 comment line2 comment 3
*/
Header files that are required to execute a C program
2 Link Section
are included in this section
In this section, variables are defined and values are set
3 Definition Section
to these variables.
Global variables are defined in this section. When a
Global declaration
4 variable is to be used throughout the program, can be
section
defined in this section.
Function prototype gives many information about a
Function prototype
5 function like return type, parameter names used inside
declaration section
the function.
Every C program is started from main function and this
6 Main function function contains two major sections called declaration
section and executable section.
User can define their own functions in this section
User defined
7 which perform particular task as per the user
function section
requirement.

52
BASIC C PROGRAM

#include <stdio.h>
int main()
{
/* Our first simple C basic program */
printf(“Hello World! “);
getch();
return 0;
}.
Output:

Hello World! .
 Basic commands in C programming to write basic C Program:

Below are few commands and syntax used in C programming to write a simple C program

S.no Command Explanation


This is a preprocessor command that includes
1 #include <stdio.h> standard input output header file(stdio.h) from the
C library before compiling a C program
This is the main function from where execution of
2 int main()
any C program begins.
3 { This indicates the beginning of the main function.
whatever is given inside the command “/* */” in
4 /*_some_comments_*/ any C program, won’t be considered for
compilation and execution.
printf(“Hello_World!
5 printf command prints the output onto the screen.
“);
This command waits for any character input from
6 getch();
keyboard.
This command terminates C program (main
7 return 0;
function) and returns 0.
8 } This indicates the end of the main function.

PROGRAMMING RULES:
While writing a program, a programmer should follow the following rules.

53
1. All statements should be written in lowercase letters.
2. Uppercase letters are only used for symbolic constants.
3. Blank space may be inserted between words. But blank space is not used
while declaring a variable, keyword, constant and function.
4. The programmers can write the statement anywhere between the two braces.
5. We can write one or more statements in a same line by separating each
statement in a same line by separating each statement with semicolon (:)
6. The opening and closing braces should be balanced.

C CHARACTER SET

Character set are the set of alphabets, letters and some special characters
that are valid in C language.
Alphabets: 
Uppercase: A B C  ....................................  X Y Z 
Lowercase: a b c  ......................................  x y z
Digits:
0 1 2 3 4 5 6  8 9
White space Characters:
blank space, new line, horizontal tab, carriage return and form feed
Special Characters in C language

< > { } ( [

* ^ | \ ) *

C TOKENS

C tokens, Identifiers and Keywords are the basics in a C program. C


tokens are the basic buildings blocks in C language which are constructed
together to write a C program.Each and every smallest individual units in a C
program are known as C tokens.

54
C tokens are of six types. They are,

1. Keywords (eg: int, while),


2. Identifiers (eg: main, total),
3. Constants (eg: 10, 20),
4. Strings (eg: “total”, “hello”),
5. Special symbols (eg: (), {}),
6. Operators (eg: +, /,-,*)
C tokens example program:

int main()
{
int x, y, total;
x = 10, y = 20;
total = x + y;
Printf (“Total = %d \n”, total);
}.

where,

 main – identifier
 {,}, (,) – delimiter
 int – keyword
 x, y, total – identifier
 main, {, }, (, ), int, x, y, total – tokens

2. Identifiers in C language:

 Each program elements in a C program are given a name called


identifiers.
 Names given to identify Variables, functions and arrays are examples for
identifiers. eg. x is a name given to integer variable in above program.

Rules for constructing identifier name in C:

1. First character should be an alphabet or underscore.


2. Succeeding characters might be digits or letter.
3. Punctuation and special characters aren’t allowed except underscore.
4. Identifiers should not be keywords.

3. Keywords in C language:

 Keywords are pre-defined words in a C compiler.


 Each keyword is meant to perform a specific function in a C program.

55
 Since keywords are referred names for compiler, they can’t be used as
variable name.
C language supports 32 keywords which are given below.

auto double int struct const float short unsigned


break else long switch continue for signed void
case enum register typedef default goto sizeof volatile
char extern return union do if static while

C CONSTANT:

 C Constants are also like normal variables. Constant is an entity whose


value remains the same throughout the execution of a program.

 But, only difference is, their values can not be modified by the program
once they are defined.
 Constants refer to fixed values. They are also called as literals.
 Constants may be belonging to any of the data type.

TYPES OF C CONSTANT

1. Integer constants
2. Real or Floating point constants
3. Octal constants
4. Hexadecimal constants
5. Character constants
6. String constants

S.no Constant type data type Example


int 53, 762, -478 etc
unsigned int 5000u, 1000U etc
1 Integer constants
long int 483,647
long long int 2,147,483,680
float 10.456789
2 Real or Floating point constants
doule 600.123456789

56
3 Octal constant int 013 /* starts with 0 */
4 Hexadecimal constant int 0×90 /* starts with 0x */
5 character constants char ‘A’ , ‘B’, ‘C’
6 string constants char “ABCD” , “Hai”

Rules for constructing C constant:

1. Integer Constants in C:

 An integer constant must have at least one digit.


 It must not have a decimal point.
 It can either be positive or negative.
 No commas or blanks are allowed within an integer constant.
 If no sign precedes an integer constant, it is assumed to be positive.
 The allowable range for integer constants is -32768 to +32767.

2. Real constants in C:

 A real constant must have at least one digit.


 It must have a decimal point.
 It could be either positive or negative.
 If no sign precedes an integer constant, it is assumed to be positive.
 No commas or blanks are allowed within a real constant.

3. Character and string constants in C:

 A character constant is a single alphabet, a single digit or a single special


symbol enclosed within single quotes.

Example: ‘a’, ‘m’, (character constant)

 The maximum length of a character constant is 1 character.


 String constants are enclosed within double quotes.letters ,number,special
character are allowed.

Example: ’’madhus” “pani” “990”

4. Backslash Character Constants in C:

 There are some characters which have special meaning in C language.


 They should be preceded by backslash symbol to make use of special
function of them.
 Given below is the list of special characters and their purpose.

Backslash_character Meaning
57
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\” Double quote
\’ Single quote
\\ Backslash
\v Vertical tab
\a Alert or bell
\? Question mark
\N Octal constant (N is an octal constant)
\XN Hexadecimal constant (N – hex.dcml cnst)

How to use constants in a C program?

 We can define constants in a C program in the following ways.

1. By “const” keyword
2. By “#define” preprocessor directive

 Please note that when you try to change constant values after defining in
C program, it will through error.

1. Example program using const keyword in C:

#include <stdio.h>
void main()
{
const int height = 100; /*int constant*/
const float number = 3.14; /*Real constant*/
const char letter = ‘A’; /*char constant*/
const char letter_sequence[10] = “ABC”; /*string constant*/

58
const char backslash_char = ‘\?’; /*special char cnst*/
printf(“value of height :%d \n”, height );
printf(“value of number : %f \n”, number );
printf(“value of letter : %c \n”, letter );
printf(“value of letter_sequence : %s \n”, letter_sequence);
printf(“value of backslash_char : %c \n”, backslash_char);
}
Output:

value of height : 100


value of number : 3.140000
value of letter : A
value of letter_sequence : ABC
value of backslash_char : ?

variable
 C variable is a named location in a memory where a program can
manipulate the data. This location is used to hold the value of the
variable.
 The value of the C variable may get change in the program.
 C variable might be belonging to any of the data type like int, float, char
etc.

Rules for naming C variable:

1. Variable name must begin with letter or underscore.


2. Variables are case sensitive
3. They can be constructed with digits, letters.
4. No special symbols are allowed other than underscore.
5. sum, height, _value are some examples for variable name

Declaring & initializing C variable:

 Variables should be declared in the C program before to use.


 Memory space is not allocated for a variable while declaration. It happens
only on variable definition.
 Variable initialization means assigning a value to the variable.

S.No Type Syntax Example


Variable
1 data_type variable_name; int x, y, z; char flat, ch;
declaration

59
Variable data_type variable_name int x = 50, y = 30; char flag
2
initialization = value; = ‘x’, ch=’l’;

There are three types of variables in C program They are,

1. Local variable
2. Global variable
3. Environment variable

Local variable:
The local variable are defined within the body of the function.these
variables are defined local to that function only or block only,other
function cannot access these variables.
Eg:
Value(int a,int b)
{
int e,f;
}

e and f local variables.

EXAMPLE PROGRAM FOR LOCAL VARIABLE

#include<stdio.h>
void test();
int main()
{
int m = 22, n = 44;
printf(“\nvalues : m = %d and n = %d”, m, n);
test();
}
void test()
{
int a = 50, b = 80;
// a, b are local variables of test function
/*a and b variables are having scope
within this test function only.
These are not visible to main function.*/
/* If you try to access m and n in this function,
you will get ‘m’ undeclared and ‘n’ undeclared
error */printf(“\nvalues : a = %d and b = %d”, a, b);
}
60
 The scope of local variables will be within the function only.
 These variables are declared within the function and can’t be accessed
outside the function.
 In the below example, m and n variables are having scope within the
main function only. These are not visible to test function.
 Like wise, a and b variables are having scope within the test function
only. These are not visible to main function.

Global variables
are defined outside the main() function.multiple function can use these
variables.

Eg:
int m=5,n=10;
main()
{
int a,b;
}
m and n are global variables.

Example program for global variable in C:

 The scope of global variables will be throughout the program. These


variables can be accessed from anywhere in the program.
 This variable is defined outside the main function. So that, this variable is
visible to main function and all other sub functions.

#include<stdio.h>
void test();
int m = 22, n = 44;
int a = 50, b = 80;
int main()
{
printf(“All variables are accessed from main function”);
printf(“\nvalues: m=%d:n=%d:a=%d:b=%d”, m,n,a,b);
test();
}
void test()
{
printf(“\n\nAll variables are accessed from” \
” test function”);
printf(“\nvalues: m=%d:n=%d:a=%d:b=%d”, m,n,a,b);
}

61
Output:

All variables are accessed from main function


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

3. Environment variables in C:

 Environment variable is a variable that will be available for all C


applications and C programs.
 We can access these variables from anywhere in a C program without
declaring and initializing in an application or C program.
 The inbuilt functions which are used to access, modify and set these
environment variables are called environment functions.

 There are 3 functions which are used to access, modify and assign an
environment variable in C. They are,

1. setenv()
2. getenv()
3. putenv()
Difference between variable declaration & definition in C:

S.no Variable declaration Variable definition


Declaration tells the compiler about data Definition allocates memory for
1
type and size of the variable. the variable.
Variable can be declared many times in It can happen only one time for a
2
a program. variable in a program.
The assignment of properties and Assignments of storage space to a
3
identification to a variable. variable.

QUALIFIERS:

C – type qualifiers : The keywords which are used to modify the properties
of a variable are called type qualifiers.

There are two types of qualifiers available in C language. They are,

1. const
2. volatile

1. const keyword:

62
 Constants are also like normal variables. But, only difference is, their
values can’t be modified by the program once they are defined.
 They refer to fixed values. They are also called as literals.
 They may be belonging to any of the data type.

 Syntax:

const data_type variable_name; (or) const data_type *variable_name;

2. volatile keyword:

 When a variable is defined as volatile, the program may not change the
value of the variable explicitly.
 But, these variable values might keep on changing without any explicit
assignment by the program. These types of qualifiers are called volatile.
 For example, if global variable’s address is passed to clock routine of the
operating system to store the system time, the value in this address keep
on changing without any assignment by the program. These variables are
named as volatile variable.

 Syntax:

volatile data_type variable_name;


(or)
volatile data_type *variable_name;

C – DATA TYPES:

 Most important attribute of an identifier


 It determines the possible values that an identifier can have and valid
operations that can be applied on it

 Size of variable, constant and array are determined by data types.


There are four data types in C language. They are,

S.no Types Data Types


1 Basic data types int, char, float, double

63
2 Enumeration data type enum
3 Derived data type pointer, array, structure, union
4 Void data type void

BASIC DATA TYPES IN C:

Integer data type:

 Integer data type allows a variable to store numeric values.


 “int” keyword is used to refer integer data type.
 The storage size of int data type is 2 or 4 or 8 byte.
 It varies depend upon the processor in the CPU that we use. If we are
using 16 bit processor, 2 byte (16 bit) of memory will be allocated for int
data type.
 Like wise, 4 byte (32 bit) of memory for 32 bit processor and 8 byte (64
bit) of memory for 64 bit processor is allocated for int datatype.
 int (2 byte) can store values from -32,768 to +32,767
 int (4 byte) can store values from -2,147,483,648 to +2,147,483,647.
 If you want to use the integer value that crosses the above limit, you can
go for “long int” and “long long int” for which the limits are very high.

Note:

 We can’t store decimal values using int data type.


 If we use int data type to store decimal values, decimal values will be
truncated and we will get only whole number.
 In this case, float data type can be used to store decimal values in a
variable.

CHARACTER DATA TYPE:

 Character data type allows a variable to store only one character.


 Storage size of character data type is 1. We can store only one character
using character data type.
 “char” keyword is used to refer character data type.
 For example, ‘A’ can be stored using char datatype. You can’t store more
than one character using char data type.
 Please refer C – Strings topic to know how to store more than one
characters in a variable.

FLOATING POINT DATA TYPE:

Floating point data type consists of 2 types. They are,


64
1. float
2. double

FLOAT:

 Float data type allows a variable to store decimal values.


 Storage size of float data type is 4. This also varies depend upon the
processor in the CPU as “int” data type.
 We can use up-to 6 digits after decimal using float data type.
 For example, 10.456789 can be stored in a variable using float data type.

DOUBLE:

 Double data type is also same as float data type which allows up-to 10
digits after decimal.
 The range for double datatype is from 1E–37 to 1E+37.

sizeof() function in C:

sizeof() function is used to find the memory space allocated for each C data
types.

#include <stdio.h>
#include <limits.h>
int main()
{
int a;
char b;
float c;
double d;
printf(“Storage size for int data type:%d \n”,sizeof(a));
printf(“Storage size for char data type:%d \n”,sizeof(b));
printf(“Storage size for float data type:%d \n”,sizeof(c));
printf(“Storage size for double data type:%d\n”,sizeof(d));
return 0;
}.
Output:
Storage size for int data type:4
Storage size for char data type:1
Storage size for float data type:4
Storage size for double data type:8 .

65
Modifiers in C:

 The amount of memory space to be allocated for a variable is derived by


modifiers.
 Modifiers are prefixed with basic data types to modify (either increase or
decrease) the amount of storage space allocated to a variable.
 For example, storage space for int data type is 4 byte for 32 bit processor.
We can increase the range by using long int which is 8 byte. We can
decrease the range by using short int which is 2 byte.

 There are 5 modifiers available in C language. They are,

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

 Below table gives the detail about the storage size of each C basic data
type in 16 bit processor.Please keep in mind that storage size and range
for int and float datatype will vary depend on the CPU processor (8,16,
32 and 64 bit)

storage
S.No C Data types Range
Size
1 char 1 –127 to 127
2 int 2 –32,767 to 32,767
1E–37 to 1E+37 with six digits of
3 float 4
precision
1E–37 to 1E+37 with ten digits of
4 double 8
precision
1E–37 to 1E+37 with ten digits of
5 long double 10
precision
6 long int 4 –2,147,483,647 to 2,147,483,647
7 short int 2 –32,767 to 32,767
8 unsigned short int 2 0 to 65,535
9 signed short int 2 –32,767 to 32,767
10 long long int 8 –(2power(63) –1) to 2(power)63 –1
11 signed long int 4 –2,147,483,647 to 2,147,483,647
12 unsigned long int 4 0 to 4,294,967,295
13 unsigned long long 8 2(power)64 –1
66
int

2. Enumeration data type in C:

 Enumeration data type consists of named integer constants as a list.


 It start with 0 (zero) by default and value is incremented by 1 for the
sequential identifiers in the list.
 Enum syntax in C:

enum identifier [optional{ enumerator-list }];

Enum example in C:
enum month { Jan, Feb, Mar }; Jan, Feb and
Mar variables
will be assigned
to 0,1,2
respectively
default
enum month { Jan = 1, Feb, Mar }; Feb and Mar
variables will be
assigned to 2 and
3 respectively by
default
enum month { Jan = 20, Feb, Mar }; Jan is assigned to
20. Feb and Mar
variables will be
assigned to 21
and 22
respectively by
default

 The above enum functionality can also be implemented by “#define”


preprocessor directive as given below. Above enum example is same as
given below.

#define Jan 20;


#define Feb 21;
#define Mar 22;

67
C – enum example program:

#include <stdio.h>
int main()
{
enum MONTH { Jan = 0, Feb, Mar };
enum MONTH month = Mar;
if(month == 0)
printf(“Value of Jan”);
else if(month == 1)
printf(“Month is Feb”);
if(month == 2)
printf(“Month is Mar”);
}.
Output:
Month is Mar .

3. Derived data type in C:

 Array, pointer, structure and union are called derived data type in C
language.
 To know more about derived data types, please visit “C – Array“ , “C –
Pointer” , “C – Structure” and “C – Union” topics in upcoming chapters.

4. Void data type in C:

 Void is an empty data type that has no value.


 This can be used in functions and pointers.
 Please see “C – Function” topic to know how to use void data type in
function with simple call by value and call by reference example
programs.

EXPRESSIONS AND OPEARATORS

 The symbols which are used to perform logical and mathematical


operations in a C program are called C operators.
 These C operators join individual constants and variables to form
expressions.
 Operators, functions, constants and variables are combined together to
form expressions.
 Consider the expression A + B * 5.
68
where, +, * are operators,

A, B are variables, 5 is constant

A + B * 5 is an expression.

Expressions and statements

An expression represents a single data item usually a number. The expression


may consist of a single entity, such as a constant or variable, or it may consist of
some combination of such entities, interconnected by one or more operators.
Expressions can also represent logical conditions which are either true or false.
However, in C, the conditions true and false are represented by the integer
values 1 and 0, respectively. Several simple expressions are given below:

a+b
x=y
t=u+v
x <= y++j
The first expression, which employs the addition operator (+), represents the
sum of the values assigned to variables a and b.
The second expression involves the assignment operator (=), and causes the
value represented by y to be assigned to x.
In the third expression, the value of the expression (u + v) is assigned to t.
The increment (by unity) operator ++ is called a unary operator, because it only
possesses one operand.

A statement causes the computer to carry out some definite action. There are
three different classes of statements in C: expression statements, compound
statements, and control statements.

An expression statement consists of an expression followed by a semicolon. The


execution of such a statement causes the associated expression to be evaluated.

For example:

a = 6;
c = a + b;
++j;
The first two expression statements both cause the value of the expression on
the right of the equal sign to be assigned to the variable on the left. The third
expression statement causes the value of j to be incremented by 1. Again, there
is no restriction on the length of an expression statement: such a statement can
even be split over many lines, so long as its end is signaled by a semicolon.
69
A compound statement consists of several individual statements enclosed within
a pair of braces { }. The individual statements may themselves be expression
statements, compound statements, or control statements. Unlike expression
statements, compound statements do not end with semicolons. A typical
compound statement is shown below:

{
pi = 3.141593;
circumference = 2. * pi * radius;
area = pi * radius * radius;
}
This particular compound statement consists of three expression statements, but
acts like a single entity in the program in which it appears.

A symbolic constant is a name that substitutes for a sequence of characters. The


characters may represent either a number or a string. When a program is
compiled, each occurrence of a symbolic constant is replaced by its
corresponding character sequence. Symbolic constants are usually defined at the
beginning of a program, by writing

#define NAME text


where NAME represents a symbolic name, typically written in upper-case
letters, and text represents the sequence of characters that is associated with that
name. Note that text does not end with a semicolon, since a symbolic constant
definition is not a true C statement. In fact, during compilation, the resolution of
symbolic names is performed (by the C preprocessor) before the start of true
compilation. For instance, suppose that a C program contains the following
symbolic constant definition:
#define PI 3.141593
Suppose, further, that the program contains the statement
area = PI * radius * radius;
During the compilation process, the preprocessor replaces each occurrence of
the symbolic constant PI by its corresponding text. Hence, the above statement
becomes
area = 3.141593 * radius * radius;

Symbolic constants are particularly useful in scientific programs for


representing constants of nature, such as the mass of an electron, the
speed of light, etc. Since these quantities are fixed, there is little point in
assigning variables in which to store them.

Types of C operators:

70
C language offers many types of operators. They are,

1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators

Continue on types of C operators:

S.no Types of Operators Description


These are used to perform
mathematical calculations like
1 Arithmetic_operators addition, subtraction,
multiplication, division and
modulus
These are used to assign the
2 Assignment_operators values for the variables in C
programs.
These operators are used to
3 Relational operators compare the value of two
variables.
These operators are used to
4 Logical operators perform logical operations on
the given two variables.
These operators are used to
5 Bit wise operators perform bit operations on given
two variables.
Conditional operators return one
Conditional (ternary) value if condition is true and
6
operators returns another value is
condition is false.
7 Increment/decrement These operators are used to
71
either increase or decrease the
operators
value of the variable by one.
&, *, sizeof( ) and ternary
8 Special operators
operators.

Arithmetic Operators in C:
 C Arithmetic operators are used to perform mathematical calculations like addition, subtraction,
multiplication, division and modulus in C programs.

S.no Arithmetic Operators Operation Example


1 + Addition A+B
2 - Subtraction A-B
3 * multiplication A*B
4 / Division A/B
5 % Modulus A%B

Example program for C arithmetic operators:

 In this example program, two values “40″ and “20″ are used to perform
arithmetic operations such as addition, subtraction, multiplication,
division, modulus and output is displayed for each operation.

#include <stdio.h>
int main()
{
int a=40,b=20, add,sub,mul,div,mod;
add = a+b;
sub = a-b;
mul = a*b;
div = a/b;
mod = a%b;
printf(“Addition of a, b is : %d\n”, add);
printf(“Subtraction of a, b is : %d\n”, sub);

72
printf(“Multiplication of a, b is : %d\n”, mul);
printf(“Division of a, b is : %d\n”, div);
printf(“Modulus of a, b is : %d\n”, mod);
}
Output:

Addition of a, b is : 60
Subtraction of a, b is : 20
Multiplication of a, b is : 800
Division of a, b is : 2
Modulus of a, b is : 0

Assignment operators in C:

 In C programs, values for the variables are assigned using assignment


operators.
 For example, if the value “10″ is to be assigned for the variable “sum”, it
can be assigned as “sum = 10;”
 Other assignment operators in C language are given below.

Operators Example Explanation


Simple assignment 10 is assigned to
= sum = 10
operator variable sum
This is same as sum =
+= sum += 10
sum + 10
This is same as sum =
-= sum -= 10
sum – 10
This is same as sum =
*= sum *= 10
sum * 10
Compound assignment This is same as sum =
/+ sum /= 10
operators sum / 10
sum %= This is same as sum =
%=
10 sum % 10
This is same as sum =
&= sum&=10
sum & 10
This is same as sum =
^= sum ^= 10
sum ^ 10

Example program for C assignment operators:

 In this program, values from 0 – 9 are summed up and total “45″ is


displayed as output.
73
 Assignment operators such as “=” and “+=” are used in this program to
assign the values and to sum up the values.

# include <stdio.h>
int main()
{
int Total=0,i;
for(i=0;i<10;i++)
{
Total+=i; // This is same as Total = Toatal+i
}
printf(“Total = %d”, Total);
}
Output:

Total = 45

RELATIONAL OPERATORS IN C:
 Relational operators are used to find the relation between two variables. i.e. to compare the values of
two variables in a C program.

S.no Operators Example Description


1 > x>y x is greater than y
2 < x<y x is less than y
3 >= x >= y x is greater than or equal to y
4 <= x <= y x is less than or equal to y
5 == x == y x is equal to y
6 != x != y x is not equal to y

Example program for relational operators in C:

 In this program, relational operator (==) is used to compare 2 values


whether they are equal are not.
 If both values are equal, output is displayed as ” values are equal”. Else,
output is displayed as “values are not equal”.
 Note : double equal sign (==) should be used to compare 2 values. We
should not single equal sign (=).

#include <stdio.h>
int main()
{

74
int m=40,n=20;
if (m == n)
{
printf(“m and n are equal”);
}
else
{
printf(“m and n are not equal”);
}
}
Output:

m and n are not equal

LOGICAL OPERATORS IN C:

 These operators are used to perform logical operations on the given


expressions.
 There are 3 logical operators in C language. They are, logical AND (&&), logical OR (||) and logical NOT
(!).

S.no Operators Name Example Description


logical It returns true when both conditions
1 && (x>5)&&(y<5)
AND are true
logical It returns true when at-least one of
2 || (x>=10)||(y>=10)
OR the condition is true
It reverses the state of the operand
“((x>5) && (y<5))”
logical
3 ! !((x>5)&&(y<5)) If “((x>5) && (y<5))” is true,
NOT
logical NOT operator makes it
false

Example program for logical operators in C:

#include <stdio.h>
int main()
{
int m=40,n=20;
int o=20,p=30;
if (m>n && m !=0)
{
printf(“&& Operator : Both conditions are true\n”);

75
}
if (o>p || p!=20)
{
printf(“|| Operator : Only one condition is true\n”);
}
if (!(m>n && m !=0))
{
printf(“! Operator : Both conditions are true\n”);
}
else
{
printf(“! Operator : Both conditions are true. ” \
“But, status is inverted as false\n”);
}
} output:
&& Operator : Both conditions are true
|| Operator : Only one condition is true
! Operator : Both conditions are true. But, status is inverted as false
 In this program, operators (&&, || and !) are used to perform logical
operations on the given expressions.
 && operator – “if clause” becomes true only when both conditions
(m>n and m! =0) is true. Else, it becomes false.
 || Operator – “if clause” becomes true when any one of the condition
(o>p || p!=20) is true. It becomes false when none of the condition is true.
 ! Operator – It is used to reverses the state of the operand.
 If the conditions (m>n && m!=0) is true, true (1) is returned. This value
is inverted by “!” operator.
 So, “! (m>n and m! =0)” returns false (0).

Bit wise operators in C:

 These operators are used to perform bit operations. Decimal values are
converted into binary values which are the sequence of bits and bit wise
operators work on these bits.
 Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~
(bitwise OR), ^ (XOR), << (left shift) and >> (right shift).
Truth table for bit wise operation Bit wise operators

x y x|y x&y x ^ y Operator_symbol Operator_name


0 0 0 0 0 & Bitwise_AND
0 1 1 0 1 | Bitwise OR
1 0 1 0 1 ~ Bitwise_NOT
1 1 1 1 0 ^ XOR
76
<< Left Shift
>> Right Shift

Example program for bit wise operators in C:

 In this example program, bit wise operations are performed as shown


above and output is displayed in decimal format.

#include <stdio.h>
int main()
{
int m = 40,n = 80,AND_opr,OR_opr,XOR_opr,NOT_opr ;
AND_opr = (m&n);
OR_opr = (m|n);
NOT_opr = (~m);
XOR_opr = (m^n);
printf(“AND_opr value = %d\n”,AND_opr );
printf(“OR_opr value = %d\n”,OR_opr );
printf(“NOT_opr value = %d\n”,NOT_opr );
printf(“XOR_opr value = %d\n”,XOR_opr );
printf(“left_shift value = %d\n”, m << 1);
printf(“right_shift value = %d\n”, m >> 1);
}
Output:

AND_opr value = 0
OR_opr value = 120
NOT_opr value = -41
XOR_opr value = 120
left_shift value = 80
right_shift value = 20

CONDITIONAL OR TERNARY OPERATORS IN C:

 Conditional operators return one value if condition is true and returns


another value is condition is false.
 This operator is also called as ternary operator.

Syntax : (Condition? true_value: false_value);


Example : (A > 100 ? 0 : 1);

77
.
 In above example, if A is greater than 100, 0 is returned else 1 is returned.
This is equal to if else conditional statements.

Example program for conditional/ternary operators in C:

#include <stdio.h>
int main()
{
int x=1, y ;
y = ( x ==1 ? 2 : 0 ) ;
printf(“x value is %d\n”, x);
printf(“y value is %d”, y);
}
Output:

x value is 1
y value is 2

Example program for pre – increment operators in C:

//Example for increment operators

#include <stdio.h>
int main()
{
int i=0;
while(++i < 5 )
{
printf("%d ",i);
}
return 0;
}
Output:

1234
 Step 1 : In above program, value of “i” is incremented from 0 to 1 using
pre-increment operator.
 Step 2 : This incremented value “1″ is compared with 5 in while
expression.
 Step 3 : Then, this incremented value “1″ is assigned to the variable “i”.

78
 Above 3 steps are continued until while expression becomes false and
output is displayed as “1 2 3 4″.

Example program for post – increment operators in C:

#include <stdio.h>
int main()
{
int i=0;
while(i++ < 5 )
{
printf("%d ",i);
}
return 0;
}
Output:

12345
 Step 1 : In this program, value of i ”0″ is compared with 5 in while
expression.
 Step 2 : Then, value of “i” is incremented from 0 to 1 using post-
increment operator.
 Step 3 : Then, this incremented value “1″ is assigned to the variable “i”.
 Above 3 steps are continued until while expression becomes false and
output is displayed as “1 2 3 4 5″.

Example program for pre - decrement operators in C:

#include <stdio.h>
int main()
{
int i=10;
while(--i > 5 )
{
printf("%d ",i);
}
return 0;
}
Output:

9876
 Step 1 : In above program, value of “i” is decremented from 10 to 9 using
pre-decrement operator.

79
 Step 2 : This decremented value “9″ is compared with 5 in while
expression.
 Step 3 : Then, this decremented value “9″ is assigned to the variable “i”.
 Above 3 steps are continued until while expression becomes false and
output is displayed as “9 8 7 6″.

Example program for post - decrement operators in C:

#include <stdio.h>
int main()
{
int i=10;
while(i-- > 5 )
{
printf("%d ",i);
}
return 0;
}
Output:

98765
 Step 1 : In this program, value of i ”10″ is compared with 5 in while
expression.
 Step 2 : Then, value of “i” is decremented from 10 to 9 using post-
decrement operator.
 Step 3 : Then, this decremented value “9″ is assigned to the variable “i”.
 Above 3 steps are continued until while expression becomes false and
output is displayed as “9 8 7 6 5″.

Special Operators in C:

 Below are some of special operators that C language offers.

S.no Operators Description


This is used to get the address of the variable.
1 &
Example : &a will give address of a.
This is used as pointer to a variable.
2 * Example : * a where, * is pointer to the
variable a.
This gives the size of the variable.
3 Sizeof ()
Example : size of (char) will give us 1.

Example program for & and * operators in C:

80
 In this program, “&” symbol is used to get the address of the variable and
“*” symbol is used to get the value of the variable that the pointer is
pointing to. Please refer C – pointer topic to know more about pointers.

#include <stdio.h>
int main()
{
int *ptr, q;
q = 50;
/* address of q is assigned to ptr */
ptr = &q;
/* display q’s value using ptr variable */
printf(“%d”, *ptr);
return 0;
}
Output:

50

Example program for sizeof() operator in C:

 sizeof() operator is used to find the memory space allocated for each C
data types.

#include <stdio.h>
#include <limits.h>
int main()
{
int a;
char b;
float c;
double d;
printf(“Storage size for int data type:%d \n”,sizeof(a));
printf(“Storage size for char data type:%d \n”,sizeof(b));
printf(“Storage size for float data type:%d \n”,sizeof(c));
printf(“Storage size for double data type:%d\n”,sizeof(d));
return 0;
}
Output:

Storage size for int data type:4


Storage size for char data type:1
Storage size for float data type:4

81
Storage size for double data type:8

DATA INPUT AND OUTPUT

Data input and output operations in C are carried out by the standard
input/output library (header file: stdio.h) via the functions scanf, printf, fscanf,
and fprintf, which read and write data from/to the terminal, and from/to a data
file, respectively.

Input : In any programming language input means to feed some data into
program. This can be given in the form of file or from command line. C
programming language provides a set of built-in functions to read given input
and feed it to the program as per requirement.

Output : In any programming language output means to display some data on


screen, printer or in any file. C programming language provides a set of built-in
functions to output required data.

Here we will discuss only one input function and one putput function just to
understand the meaning of input and output. Rest of the functions are given into
C - Built-in Functions

printf() function

This is one of the most frequently used functions in C for output.

Try following program to understand printf() function.

#include <stdio.h>

main()
{
int dec = 5;
char str[] = "abc";
char ch = 's';
float pi = 3.14;

printf("%d %s %f %c\n", dec, str, pi, ch);


}

The output of the above would be:


82
5 abc 3.140000 c

Here %d is being used to print an integer, %s is being usedto print a string, %f


is being used to print a float and %c is being used to print a character.

A complete syntax of printf() function is given in C - Built-in Functions

scanf() function

This is the function which can be used to to read an input from the command
line.

program to understand scanf() function.

#include <stdio.h>

main()
{
int x;
int args;

printf("Enter an integer: ");


if (( args = scanf("%d", &x)) == 0) {
printf("Error: not an integer\n");
} else {
printf("Read in %d\n", x);
}
}

Here %d is being used to read an integer value and we are passing &x to store
the vale read input. Here &indicates the address of variavle x.

This program will prompt you to enter a value. Whatever value you will enter at
command prompt that will be output at the screen using printf() function. If you
eneter a non-integer value then it will display an error message.

Enter an integer: 20
Read in 20

 Scanf(). All characters in printf() and scanf() functions must be in lower


case.

83
Example program for C printf() function:

#include <stdio.h>
int main()
{
char ch = ‘A’;
char str[20] = “fresh2refresh.com”;
float flt = 10.234;
int no = 150;
double dbl = 20.123456;
printf(“Character is %c \n”, ch);
printf(“String is %s \n” , str);
printf(“Float value is %f \n”, flt);
printf(“Integer value is %d\n” , no);
printf(“Double value is %lf \n”, dbl);
printf(“Octal value is %o \n”, no);
printf(“Hexadecimal value is %x \n”, no);
return 0;
}.

Output:

Character is A
String is fresh2refresh.com
Float value is 10.234000
Integer value is 150
Double value is 20.123456
Octal value is 226
Hexadecimal value is 96 .

You can see the output with the same data which are placed within the double
quotes of printf statement in the program except

 %d got replaced by value of an integer variable (no),

 %c got replaced by value of a character variable (ch),

 %f got replaced by value of a float variable (flt),

 %lf got replaced by value of a double variable (dbl),

 %s got replaced by value of a string variable (str),

84
 %o got replaced by a octal value corresponding to integer variable (no),

 %x got replaced by a hexadecimal value corresponding to integer variable

 \n got replaced by a newline.

2. C scanf() function:

 scanf() function is used to read character, string, numeric data from


keyboard
 Consider below example program where user enters a character. This
value is assigned to the variable “ch” and then displayed.

 Then, user enters a string and this value is assigned to the variable ”str”
and then displayed.

Example program for printf() and scanf() functions in C:

#include <stdio.h>
int main()
{
char ch;
char str[100];
printf(“Enter any character \n”);
scanf(“%c”, &ch);
printf(“Entered character is %c \n”, ch);
printf(“Enter any string ( upto 100 character ) \n”);
scanf(“%s”, &str);
printf(“Entered string is %s \n”, str);
}.
Output:
Enter any character
a
Entered character is a
Enter any string ( upto 100 character )
hai
Entered string is hai

85
C – Decision Control statement
 In decision control statements (C if else and nested if), group of
statements are executed when condition is true. If condition is false, then
else part statements are executed.
 There are 3 types of decision making control statements in C language.
They are,

1. if statements
2. if else statements
3. nested if statements

“If”, “else” and “nested if” decision control statements in C:

 Syntax for each C decision control statements are given in below table
with description.

Decision
control Syntax Description
statements
In these type of statements, if
if (condition)
if condition is true, then respective block
{ Statements; }
of code is executed.
if (condition)
{ Statement1; In these type of statements, group of
Statement2; } statements are executed when
if…else
else condition is true. If condition is false,
{ Statement3; then else part statements are executed.
Statement4; }
if (condition1)
If condition 1 is false, then condition 2
{ Statement1; }
is checked and statements are executed
nested if else_if(condition2)
if it is true. If condition 2 also gets
{ Statement2; }
failure, then else part is executed.
else Statement 3;

Example program for if statement in C:

86
In “if” control statement, respective block of code is executed when condition is
true.

int main()
{
int m=40,n=40;
if (m == n)
{
printf("m and n are equal");
}
}
Output:

m and n are equal

Example program for if else statement in C:

In C if else control statement, group of statements are executed when condition


is true. If condition is false, then else part statements are executed.

#include <stdio.h>
int main()
{
int m=40,n=20;
if (m == n)
{
printf("m and n are equal");
}
else
{
printf("m and n are not equal");
}

}
Output:

m and n are not equal

Example program for nested if statement in C:

87
 In “nested if” control statement, if condition 1 is false, then condition 2 is
checked and statements are executed if it is true.
 If condition 2 also gets failure, then else part is executed.

#include <stdio.h>
int main()
{
int m=40,n=20;
if (m>n) {
printf("m is greater than n");
}
else if(m<n) {
printf("m is less than n");
}
else {
printf("m is equal to n");
}
}
Output:

m is greater than n

loop control statements in C:

Loop control statements in C are used to perform looping operations until the
given condition is true. Control comes out of the loop statements once condition
becomes false.

Types of loop control statements in C:

There are 3 types of loop control statements in C language. They are,

1. for
2. while
3. do-while
 Syntax for each C loop control statements are given in below table with description.

Loop
S.no Syntax Description
Name
1 for for (exp1; exp2; Where,
expr3) exp1 – variable
{ statements; } initialization

88
( Example: i=0, j=2, k=3 )
exp2 – condition checking
( Example: i>5, j<3, k=3 )
exp3 –
increment/decrement
( Example: ++i, j–, ++k )
where,
while (condition)
2 while condition might be a>5,
{ statements; }
i<10
where,
do { statements; }
3 do while condition might be a>5,
while (condition);
i<10

Example program (for loop) in C:

In for loop control statement, loop is executed until condition becomes false.

#include <stdio.h>

int main()
{
int i;

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

}
Output:

0123456789

Example program (while loop) in C:

In while loop control statement, loop is executed until condition becomes false.

#include <stdio.h>

int main()
{
int i=3;

89
while(i<10)
{
printf("%d\n",i);
i++;
}

}
Output:

3456789

Example program (do while loop) in C:

In do..while loop control statement, while loop is executed irrespective of the


condition for first time. Then 2nd time onwards, loop is executed until condition
becomes false.

#include <stdio.h>

int main()
{
int i=1;

do
{
printf("Value of i is %d\n",i);
i++;
}while(i<=4 && i>=2);

}
Output:

Value of i is 1
Value of i is 2
Value of i is 3
Value of i is 4

Difference between while & do while loops in C:

S.no while do while


1 Loop is Loop is executed for first
executed only time irrespective of the
when condition. After executing
90
condition is while loop for first time,
true. then condition is checked.

statements which are used to execute only specific block of statements in a


series of blocks are called case control statements.

There are 4 types of case control statements in C language. They are,

1. switch
2. break
3. continue
4. goto

1. switch case statement in C:

 Switch case statements are used to execute only specific case statements
based on the switch expression.
 Below is the syntax for switch case statement.

switch (expression)
{
case label1: statements;
break;
case label2: statements;
break;
default: statements;
break;
}

Example program for switch..case statement in C:

#include <stdio.h>
int main ()
{
int value = 3;
switch(value)
{
case 1:
printf(“Value is 1 \n” );
break;

91
case 2:
printf(“Value is 2 \n” );
break;
case 3:
printf(“Value is 3 \n” );
break;
case 4:
printf(“Value is 4 \n” );
break;
default :
printf(“Value is other than 1,2,3,4 \n” );
}
return 0;
}
Output:

Value is 3

2. break statement in C:

 Break statement is used to terminate the while loops, switch case loops
and for loops from the subsequent execution.
 Syntax: break;

Example program for break statement in C:

#include <stdio.h>
int main()
{
int i;

for(i=0;i<10;i++)
{
if(i==5)
{
printf(“\nComing out of for loop when i = 5″);
break;
}
printf(“%d “,i);

92
}
}
Output:

01234
Coming out of for loop when i = 5

3. Continue statement in C:

 Continue statement is used to continue the next iteration of for loop,


while loop and do-while loops. So, the remaining statements are skipped
within the loop for that particular iteration.
 Syntax : continue;

Example program for continue statement in C:

#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5 || i==6)
{
printf(“\nSkipping %d from display using ” \
“continue statement \n”,i);
continue;
}
printf(“%d “,i);
}
}
Output:

01234
Skipping 5 from display using continue statement
Skipping 6 from display using continue statement
789

4. goto statement in C:

 goto statements is used to transfer the normal flow of a program to the


specified label in the program.
 Below is the syntax for goto statement in C.

93
{
…….
go to label;
…….
…….
LABEL:
statements;
}

Example program for goto statement in C:

#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5)
{
printf(“\nWe are using goto statement when i = 5″);
goto HAI;
}
printf(“%d “,i);
}
HAI : printf(“\nNow, we are inside label name \”hai\” \n”);
}
Output:

01234
We are using goto statement when i = 5
Now, we are inside label name “hai”

SCIENTIFIC AND STATISTICAL PROBLEMS

Random numbers

A large class of scientific calculations (e.g., so-called Monte Carlo calculations)


require the use of random variables. A call to the rand() function (header file
stdlib.h), with no arguments, returns a fairly good approximation to a random
integer in the range 0 to RAND_MAX (defined in stdlib.h). The srand()
function sets its argument, which is of type int, as the seed for a new sequence
of numbers to be returned by rand(). These sequences are repeatable by calling

94
srand() with the same seed value. If no seed value is provided, the rand()
function is automatically seeded with the value 1. It is common practice in C
programming to seed the random number generator with the number of seconds
elapsed since 00:00:00 UTC, January 1st, 1970. This number is returned, as an
integer, via a call to the time (NULL) function (header file: <time.h>). Seeding
the generator in this manner ensures that a different set of random numbers is
generated automatically each time the program is run.

The program listed below illustrates the use of the rand() function to construct a
pseudo-random variable, x, which is uniformly distributed in the range 0 to 1.
The program calculates 107values of x, and then evaluates the mean and
variance of these values.

/* random.c */
/*
Program to test operation of rand() function
*/

#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define N_MAX 10000000

int main()
{
int i, seed;
double sum_0, sum_1, mean, var, x;

/* Seed random number generator */


seed = time(NULL);
srand(seed);

/* Calculate mean and variance of x: random number uniformly


distributed in range 0 to 1 */
for (i = 1, sum_0 = 0., sum_1 = 0.; i <= N_MAX; i++)
{
x = (double) rand() / (double) RAND_MAX;

sum_0 += x;
sum_1 += (x - 0.5) * (x - 0.5);
}
mean = sum_0 / (double) N_MAX;
var = sum_1 / (double) N_MAX;

95
printf("mean(x) = %12.10f var(x) = %12.10f\n", mean, var);

return 0;
}
The typical output from this program is as follows:

mean(x) = 0.5000335261 var(x) = 0.0833193874


%

As is easily demonstrated, the theoretical mean and variance of x are and

, respectively. It can be seen that the values returned by the program agree
with these theoretical values to five decimal places, which is all that can be
expected with only 107calls.

Timing

The header file time.h defines a number of library functions which can be used
to assess how much CPU time a C program consumes during execution. The
simplest such function is called clock(). A call to this function, with no
argument, will return the amount of CPU time used so far by the calling
program. The time is returned in a special data type, clock_t, defined in time.h.
This time must be divided by CLOCKS_PER_SEC, also defined in time.h, in
order to covert it into seconds. The ability to measure how much CPU time a
given code consumes is useful in scientific programming: e.g., because it allows
the effectiveness of the various available compiler optimization flags to be
determined. Optimization usually (but not always!) speeds up the execution of a
program. However, over aggressive optimization can often slow a program
down again.

The program listed below illustrates the simple use of the clock() function. The
program compares the CPU time required to raise a double to the fourth power
via a direct calculation and via a call to the pow() function. Actually, both
operations are performed a million times and the elapsed CPU time is then
divided by a million.

96
/* timing.c */
/*
Program to test operation of clock() function
*/

#include <time.h>
#include <math.h>
#define N_LOOP 1000000

int main()
{
int i;
double a = 11234567890123456.0, b;
clock_t time_1, time_2;

time_1 = clock();
for (i = 0; i < N_LOOP; i++) b = a * a * a * a;
time_2 = clock();
printf ("CPU time needed to evaluate a*a*a*a: %f microsecs\n",
(double) (time_2 - time_1) / (double) CLOCKS_PER_SEC);

time_1 = clock();
for (i = 0; i < N_LOOP; i++) b = pow(a, 4.);
time_2 = clock();
printf ("CPU time needed to evaluate pow(a, 4.): %f microsecs\n",
(double) (time_2 - time_1) / (double) CLOCKS_PER_SEC);

return 0;
}
The typical output from this program is as follows:

CPU time needed to evaluate a*a*a*a: 0.190000 microsecs


CPU time needed to evaluate pow(a, 4.): 1.150000 microsecs
%
Clearly, evaluating a fourth power using the pow() function is a lot more
expensive than the direct calculation. Hence, as has already been mentioned, the
pow() function should not be used to raise floating point quantities to small
integer powers.

Complex numbers

As we have already mentioned, the C language definition does not include


complex arithmetic--presumably because the square root of minus one is not a

97
concept which crops up very often in systems programming! Fortunately, this
rather serious deficiency--at least, as far as the scientific programmer is
concerned--is remedied in C++. The program listed below illustrates the use of
the C++ complex class (header file complex.h) to perform complex arithmetic
using doubles:
/* complex.cpp */
/*
Program to test out C++ complex class
*/

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

/* Define complex double data type */


typedef complex<double> dcomp;

int main()
{
dcomp i, a, b, c, d, e, p, q, r; // Declare complex double variables
double x, y;

/* Set complex double variable equal to complex double constant */


i = dcomp (0., 1.);
printf("\ni = (%6.4f, %6.4f)\n", i);

/* Test arithmetic operations with complex double variables */


a = i * i;
b = 1. / i;
printf("\ni*i = (%6.4f, %6.4f)\n", a);
printf("1/i = (%6.4f, %6.4f)\n", b);

/* Test mathematical functions using complex double variables */


c = sqrt(i);
d = sin(i);
e = pow(i, 0.25);
printf("\nsqrt(i) = (%6.4f, %6.4f)\n", c);
printf("sin(i) = (%6.4f, %6.4f)\n", d);
printf("i^0.25 = (%6.4f, %6.4f)\n", e);

/* Test complex operations */


p = conj(i);
q = real(i);
r = imag(i);
printf("\nconj(i) = (%6.4f, %6.4f)\n", p);
98
printf("real(i) = %6.4f\n", q);
printf("imag(i) = %6.4f\n", r);

return 0;
}
The typical output from this program is as follows:

i = (0.0000, 1.0000)

i*i = (-1.0000, 0.0000)


1/i = (0.0000, -1.0000)

sqrt(i) = (0.7071, 0.7071)


sin(i) = (0.0000, 1.1752)
i^0.25 = (0.9239, 0.3827)

conj(i) = (0.0000, -1.0000)


real(i) = 0.0000
imag(i) = 1.0000
%
The program first of all defines the complex double type dcomp. Variables of
this type are then declared, set equal to complex constants, employed in
arithmetic expressions, used as the arguments of mathematical functions, etc., in
much the same manner that we would perform similar operations in C with
variables of type double. Note the special functions conj(), real(), and imag(),
which take the complex conjugate of, find the real part of, and find the
imaginary part of a complex variable, respectively.

C PROGRAM code for Calculator Application:

// Calculator example using C code


#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<stdlib.h>

#define KEY "Enter the calculator Operation you want to do:"

// Function prototype declaration


void addition();

99
void subtraction();
void multiplication();
void division();
void modulus();
void power();
int factorial();
void calculator_operations();

// Start of Main Program


int main()
{
int X=1;
char Calc_oprn;

// Function call
calculator_operations();

while(X)
{
printf("\n");
printf("%s : ", KEY);

Calc_oprn=getche();

switch(Calc_oprn)
{
case '+': addition();
break;

case '-': subtraction();


break;

case '*': multiplication();


break;

case '/': division();


break;

case '?': modulus();


break;

case '!': factorial();


break;

100
case '^': power();
break;

case 'H':
case 'h': calculator_operations();
break;

case 'Q':
case 'q': exit(0);
break;
case 'c':
case 'C': system("cls");
calculator_operations();
break;

default : system("cls");

printf("\n**********You have entered unavailable option");


printf("***********\n");
printf("\n*****Please Enter any one of below available ");
printf("options****\n");
calculator_operations();
}
}
}

//Function Definitions

void calculator_operations()
{
//system("cls"); use system function to clear
//screen instead of clrscr();
printf("\n Welcome to C calculator \n\n");

printf("******* Press 'Q' or 'q' to quit ");


printf("the program ********\n");
printf("***** Press 'H' or 'h' to display ");
printf("below options *****\n\n");
printf("Enter 'C' or 'c' to clear the screen and");
printf(" display available option \n\n");

printf("Enter + symbol for Addition \n");


printf("Enter - symbol for Subtraction \n");
printf("Enter * symbol for Multiplication \n");
101
printf("Enter / symbol for Division \n");
printf("Enter ? symbol for Modulus\n");
printf("Enter ^ symbol for Power \n");
printf("Enter ! symbol for Factorial \n\n");
}

void addition()
{
int n, total=0, k=0, number;
printf("\nEnter the number of elements you want to add:");
scanf("%d",&n);
printf("Please enter %d numbers one by one: \n",n);
while(k<n)
{
scanf("%d",&number);
total=total+number;
k=k+1;
}
printf("Sum of %d numbers = %d \n",n,total);
}

void subtraction()
{
int a, b, c = 0;
printf("\nPlease enter first number : ");
scanf("%d", &a);
printf("Please enter second number : ");
scanf("%d", &b);
c = a - b;
printf("\n%d - %d = %d\n", a, b, c);
}

void multiplication()
{
int a, b, mul=0;
printf("\nPlease enter first numb : ");
scanf("%d", &a);
printf("Please enter second number: ");
scanf("%d", &b);
mul=a*b;
printf("\nMultiplication of entered numbers = %d\n",mul);
}

void division()
102
{
int a, b, d=0;
printf("\nPlease enter first number : ");
scanf("%d", &a);
printf("Please enter second number : ");
scanf("%d", &b);
d=a/b;
printf("\nDivision of entered numbers=%d\n",d);
}

void modulus()
{
int a, b, d=0;
printf("\nPlease enter first number : ");
scanf("%d", &a);
printf("Please enter second number : ");
scanf("%d", &b);
d=a%b;
printf("\nModulus of entered numbers = %d\n",d);
}

void power()
{
double a,num, p;
printf("\nEnter two numbers to find the power \n");
printf("number: ");
scanf("%lf",&a);

printf("power : ");
scanf("%lf",&num);

p=pow(a,num);

printf("\n%lf to the power %lf = %lf \n",a,num,p);


}

int factorial()
{
int i,fact=1,num;

printf("\nEnter a number to find factorial : ");


scanf("%d",&num);

if (num<0)
103
{
printf("\nPlease enter a positive number to");
printf(" find factorial and try again. \n");
printf("\nFactorial can't be found for negative");
printf(" values. It can be only positive or 0 \n");
return 1;
}

for(i=1;i<=num;i++)
fact=fact*i;
printf("\n");
printf("Factorial of entered number %d is:%d\n",num,fact);
return 0;
}

Calculator C code Output :

104
2 marks question
1.what are steps to write c program and get output.

105
2. what is the basic structure of c program:

 Documentation section
 Link Section
 Definition Section
 Global declaration section
 Function prototype declaration section
 Main function
 User defined function definition section

3.what are the data types in c language.

S.no Types Data Types


1 Basic data types int, char, float, double
2 Enumeration data type enum
3 Derived data type pointer, array, structure, union
4 Void data type void

4.what are Keywords in C language:

 Keywords are pre-defined words in a C compiler.


 Each keyword is meant to perform a specific function in a C
program.
 Since keywords are referred names for compiler, they can’t be used
as variable name.

5. How to use constants in a C program?

106
We can define constants in a C program in the following ways.

 By “const” keyword
 By “#define” preprocessor directive

6.what are three types of variables in C program ?

 Local variable
 Global variable
 Environment variable

7.what are different types of C operators:

C language offers many types of operators. They are,

 Arithmetic operators
 Assignment operators
 Relational operators
 Logical operators
 Bit wise operators
 Conditional operators (ternary operators)
 Increment/decrement operators
 Special operators

8.what is Relational operators in C


 Relational operators are used to find the relation between two variables. i.e. to compare the values of
two variables in a C program.

S.no Operators Example Description


1 > x>y x is greater than y
2 < x<y x is less than y
3 >= x >= y x is greater than or equal to y
4 <= x <= y x is less than or equal to y
5 == x == y x is equal to y
6 != x != y x is not equal to y

9.specify Special Operators available in C language:

107
 Below are some of special operators that C language offers.

S.no Operators Description


This is used to get the address of the
1 & variable.
Example : &a will give address of a.
This is used as pointer to a variable.
2 * Example : * a where, * is pointer to the
variable a.
This gives the size of the variable.
3 Sizeof ()
Example : size of (char) will give us 1.

10.Example program for sizeof() operator in C:

 sizeof() operator is used to find the memory space allocated for each
C data types.

#include <stdio.h>
#include <limits.h>
int main()
{
int a;
char b;
float c;
double d;
printf(“Storage size for int data type:%d \n”,sizeof(a));
printf(“Storage size for char data type:%d \n”,sizeof(b));
printf(“Storage size for float data type:%d \n”,sizeof(c));
printf(“Storage size for double data type:%d\n”,sizeof(d));
return 0;
}
Output:

Storage size for int data type:4


Storage size for char data type:1
Storage size for float data type:4
Storage size for double data type:8

11.Define QUALIFIERS:

108
C – type qualifiers : The keywords which are used to modify the properties
of a variable are called type qualifiers.

There are two types of qualifiers available in C language. They are,

 const
 volatile

12. Define logical and data errors?


Logical error: These are the errors in which conditional and
control statements cannot end there match after some sequential execution.
Data errors: These are the errors in which the input data given is not
in proper syntax as specified in input statements.
13. What is meant C tokens?
The programs are usually referred as individual text and
punctuation in a passage of text. The C language program can contain the
individual units called C tokens
C tokens are of six types: Keywords,
Identifiers ,Constants , Strings , Special symbols, Operators       .
14. What is an Operator and Operand?
An operator is a symbol that specifies an operation to be performed on
operands.
Example: * , +, -, / are called arithmetic operators.
The data items that operators act upon are called operands.
Example: a+b; In this statement a and b are called operands.

15.What are the Bitwise operators available in ‘C’?


& - Bitwise AND,
| - Bitwise OR,
~ - One’s Complement,
>> - Right shift,
<< - Leftshift,
^ - Bitwise XOR are called bit field operators.

16. What is the difference between ‘=’ and ‘==’ operator?


Where = is an assignment operator and == is a relational operator.

109
Example : while (i=7) is an infinite loop because it is a non zero value and
while (i==7) is
true only when i=7.
17. What is type casting?
Type casting is the process of converting the value of an expression to a
particular data type.
Example: int x, y; c = (float) x/y; where a and y are defined as integers.
Then The result of x/y is converted into float.

18. What is a Modulo Operator?


‘%’ is modulo operator. It gives the remainder of an integer division
Example : a=17, b=6. Then c=%b gives 5.

19. What is the difference between ++a and a++?


++a means do the increment before the operation (pre increment)
a++ means do the increment after the operation (post increment)

20. What is a global variable?


The global variable is a variable that is declared outside of all the functions.
The global variable is stored in memory, the default value is zero. Scope of
this variable
21. What are the types of I/O statements available in ‘C’?
There are two types of I/O statements available in ‘C’.
Formatted I/O Statements, Unformatted I/O Statements
22.Define scanf ( ) statement.
The scanf ( ) function is used to read information from the
standard input device ( key board ). Scanf ( ) function starts with the string
argument and may contain additional argument.
Syntax: scanf(“control string”,&var1,&var2,…..,&varn);

23. Define printf ( ).


Output data or result of an operation can be displayed from the
computer to a standard output device using the library function printf ( ).
This function is used to output any combination of data.
Syntax: printf(“control string”,var1,var2,…..,varn);
24. What is meant by looping?

110
The loop is defined as the block of statements which are repeatedly
executed for certain number of times.

25.W HAT IS MEANT BY ENUMERATED DATA TYPE.

Enumerateddata isa userdefineddatatype in Clanguage.


Enumerated data type variablescanonlyassumevalueswhich have
beenpreviouslydeclared.
Example :

enum month {jan= 1,feb,mar, apr, may, jun,jul,aug, sep, oct,nov, dec };

25.Define for loop?


The for loop is another repetitive control structure and is used to
execute set of instructions repeatedly until the condition becomes false.

for(initialization ; test condition; increment/decrement counter)


{
Body of the loop;
}
26.What is the difference between if and while statement?

If while
It is a conditional statement It is a loop control statement
If the condition is true, it executes Executes the statements within the
some statements. while block if the condition istrue.
(iii) If the condition is false then it (iii) If the condition is false the control
stops is
the execution the statements. transferred to the next statement of the
loop.

27.What is the difference between while loop and do…while loop?


In the while loop the condition is first executed. If the condition is true then
it executes the body of the loop. When the condition is false it comes of the
loop. In the do-while loop first the statement is executed and then the
111
condition is checked. The do-while loop will execute atleast one time even
though the condition is false at the very first time.

WHILE DO WHILE
This is the top tested loop This is the bottom tested

The condition is first tested, if the It executes the body once after it
condition is true, then the block is checks the condition, if it is true the
executed until the condition becomes body is executed until the condition
false. become false.

Loop is executed at least once even


Loop will not be executed if the through condition is false.
condition is false

PART A

1. Why header files are included in ‘C’ programming?

2. What is a global variable AND local variables?

3. List the different data types available in ‘C’?

4. What are keywords?

5. What do you mean by variables in ‘C’ and define typecasting?

6. What is ternary operator?

7. What is the difference between Logical AND and Bitwise AND?

8. What is the difference between ‘=’ and ‘==’ operator?

9. What is the use of sizeof( ) operator and write a program

for sizeof( ) operator ?

10. What are the escape sequences present in ‘C’ .


11.What is the difference between while loop and do…while loop?
12. What are the types of I/O statements available in ‘C’?

13. What is the difference between ++a and a++


112
PART – B
1. Explain in detail the structure of a C program with an
example.

2. Explain in detail about the constants, expressions and


statements in ‘C’.

3. Discuss about the various data types in ‘C’.


4. Describe the various types of operators in ‘C’ language along
with its priority.
5. Explain about the various decision making and branching
statements.

6. Write a program for the following :


 To check whether a given year is leap or not.
 To find the roots of a quadratic equation.
 To find the area and circumference of a circle with radius r.
 To convert the temperature given in Fahrenheit to Celsius.
 To calculate simple interest and the maturity amount.
 To find area of a triangle whose sides are a, b and c.
 To find the sum of first 100 integers.
 To find the sum of all odd / even numbers between 1 and 100.
 To check whether a number is prime or not.
 To find the digits of a number. (123 => 1+2+3=6)
 To reverse the digits of a number. (123 => 321)
 To check whether a given number is a palindrome or not. (232)
 To check whether a given number is perfect. (6=>1+2+3,
28=>1+2+4+7+14)
 To print the integers between 1 and n which are divisible by 7.
 To generate the first n numbers in a Fibonacci series.
 To find the factorial of a given number.
 To generate Armstrong number between 100 and 999.
 To find the average of n numbers.
 To find the sum of series :
 1+(1+2)+(1+2+3)+(1+2+3+4)……n terms
 12 +22+32+42+……..n terms
 1+1/2+1/3+1/4+…..n terms
 Sin(x) = x - x3/3! + x5/5!- x7/7!+…..+ xn/n!
 Cox(x) = 1 – x2/2! + x4/4!- x6/6!+…..+ xn/n!
113
114
7. Write short notes on the following:
a. ‘for’ loop
b. ‘while’ loop
c. ‘do..while’ loop

8. Explain briefly about the input and output functions in ‘C’.

115

You might also like