UNIT 4
Programming Language
THE HISTORY OF C
The C language was developed at Bell Laboratories (now
AT& T’: American Telegraph & Telephone) in the early 1970’s by a system
programmer named Dennis Ritchie. It was written originally for programming
under an operating system called UNIX, which itself was later rewritten almost
entirely in C.
Its name encrypted as C, derives from the fact that it is
based on an earlier version written by Ken Thompson, another Bell Laboratories
systems engineer. He adapted it from a language that was known by the initials
BCPL (Basic Combined Programming Language). Thompson derived his programming
language name as B, the first of the initials BCPL.
When the language was modified and improved to its
present state, the second letter of BCPL, C was given to it. The C language is
often described as a middle-level language. It permits programs to be written
in much the same style as that of most of the high-level programming languages.
It also interacts with the inner workings of the computer.
The American National Standards Institute has established certain standards for
C, which are known as ANSI C in addition to the original version of C developed
by Dennis Ritchie. Another popular version of C is Turbo C.
Merits of C Programming Language
In computer programming, different high-level programming
languages are used. There are some programming languages specially designed to
write programs for special kind of solutions such as simulations, games, space
research, etc. Here are some merits of using C programming language.
1. C is general purpose programming language. You can
generate different kind of software such as billing system, games, utilities,
word processor, etc.
2. C is the structured programming language. It uses
structured statements such as while, for, etc.
3. C is a standardized programming language. For example
ANSI (American National Standards Institute) C is a standard programming
language.
4. The C language can run in any computer system. It is
system independent.
5. It has the small range of data types of detailed data
manipulation statements with power data definition methods.
6. It is a language of few words such that the programmer
can remember them easily.
7. It is a highly efficient programming language since C
compilers are generally able to translate source code into efficient machine
instructions.
Structured programming
In 1965, a Dutch Professor E. W Dijkstra suggested the
elimination of the GO TO statement. In 1966, a paper presented in Italian (and
later translated into English by C. Bohm and G. Jacopini) defined the
theoretical framework for structured programming. The paper stated that any
program solution can be expressed in three fundamental control blocks: a
processing box, a decision symbol of the IF… THEN… ELSE type and some form of
looping procedure.
These three components are the basis for structured
programming solutions. The identification of these three structures, namely (a)
used to follow a sequence of steps (b) select alternative paths and (c)
establish program loops formulated the foundation of structured programming.
Some advantages of structured programming are:
1. Complex programs may be divided into simpler and more
manageable elements.
2. Simultaneous coding of modules by several programmers is
possible.
3. A library of modules may be created and these modules can
be used in other programs.
4. Reduced testing and debugging time
5. Increased programmer productivity.
6. Less complexity in programs that are essentially
maintained and modified.
7. Increased clarity by reducing complexity.
Features of C Programming Language
The C language was successful in developing UNIX
operating systems. It has special reasons to become very popular in the
programming world.
·
Portability: This refers to the ability of a program to run in
different environments. Some programming language compilers such as FORTRAN and
Pascal could be used in those computers containing the same compilers. Since, C
languages have different compilers almost in all systems, a C is termed as the
most portable language.
·
Flexibility: The C language combines the convenience and portable
nature of high-level language with the flexible nature.
·
Wide acceptability: The C language is known to the entire world. The
language is suitable for projects at the system level and at the application level.
Program Characteristics
Although many programs are written by many programmers,
some common characteristics of program which makes it readable and portable
are:
1. The program should maintain its integrity. It should be
accurate in calculations.
2. The program should be clear in reading. It should be
accurate in calculations and enhance the readability of the program for future
reference.
3. The program should be designed in a simple logic. Simple
logic is easy to understand.
4. It should be executed very fast and utilize the memory
efficiently.
5. The program should be broken down into pieces or modules.
A modular program is easy to handle and read.
6. The program should be general with reasonable limits.
Elements of C
Before we begin about different aspects of C programming
language, let us discuss on some of the important elements of C. Every C
program consists of one or more modules. These modules are called functions.
One of the functions must be called main ().
The program will always begin by executing the main function.
This function may access other functions. There can be many functions. Each
function should be defined separately. The user defined functions are either
defined ahead of the main function or within the main function. Each function
must contain the following:
1. A function heading, which consists of the function name
(including the arguments if present)?
2. A list of argument declarations if the arguments are
included in the heading.
3. A compound statement, which comprises the remainder of
the function.
The arguments are also called the parameters. Each
compound statement is enclosed within a pair of braces i.e. { }. The Comments
or remarks may appear within the program anywhere within the delimits /* and
*/. The comments help to read the program and make convenient during debugging
the program errors.
Example 1:
#include <stdio.h> #include <conio.h> Void main () { Printf (“\n Hello Learner.\n”); Printf (:\n Bye”); Getch(); |
Explanation
#include directive: This is an essential directive. A directive is linked to a header file.
The header file make full use of the I/O functions of the standard C library.
Here, stdio.h is a header file and # sign is known as processing directive.
Void main() function: This is the main function that must appear in every C program. Main
without void is used when where there are no arguments main() without any
parameters has an argument.
Printf () function: The letter f in print function stands for formatted. This function is used
to print out the messages, either on screen or paper.
{} braces surround the body of the function used to group
statements together.
\n represents new line sequence or new line start. This
is also known as the escape sequence and every line is terminated with a
semicolon (;) in C programming language. Without \n, the characters are printed
on the same line without any spaces.
Return 0 makes the compiler happy.
get () function holds from screen scrolling. It is
defined in stdio.h header file.
C language users small letter or lowercase letters. No
capital letters are used unless it is specified as in define statement.
The above program
is rewritten to understand the function of void and return statements.
#include <stdio.h> main () { Printf (“\n Hello C”); Printf (“\n Bye”); Return 0; } |
In this case, the
compiler is happy to execute the program. The above program is rewritten in a
different way. It gives the same output as we did with previous programs.
………………………………………………………………………………………………………………………………………………………….
Character Set of C Programming Language
Character Set
The C character set consists of upper and lowercase alphabets, digits, special characters and white spaces. The alphabets and digits are altogether called as the alphanumeric character.
1. Alphabets
A B C D E F ………..Z
a b c d e f ………….z
2.
Digits
0 1 2 3 4 5 6 7 8 9
3.
Special Characters
, comma |
. period |
; semicolon |
: colon |
# number sign |
‘ apostrophe |
“ quotation mark |
! exclamation mark |
| vertical bar (pipe) |
~ tilde |
< opening angle bracket |
> closing angle bracket |
_ under score |
$ dollar sign |
( left parenthesis |
) right parenthesis |
% percent sign |
? question mark |
& ampersand |
^ caret |
* asterisk |
- minus |
+ plus sign |
[ left bracket |
] right bracket |
{ left brace |
} right brace |
/ slash |
\backslash |
4.
White space characters
Blank space newline carriage return
Form feed horizontal tab vertical tab
Escape Sequence: The escape sequence is
used in C programming language. The escape sequence helps in managing the
programs. These are also known as backslash character constants
Character |
Escape Sequence |
ASCII Value |
bell (alert backspace horizontal tab the new line (line feed) vertical tab form feed carriage return a quotation mark (“) apostrophe (‘) a question mark (?) backslash (\b) null octal number hexadecimal number |
\a \b \t \n \v \f \r \” \’ \? \\ \0 \o0 \xhh |
007 008 009 010 011 012 013 034 039 063 092 000 Eg., \5, \005, \123, \177 Eg., \x5,\x53, \x7f |
Identifiers and Keywords
Every word in C programming language is classified either
as identifier or keyword. Identifiers are used to name the variables, symbolic
constants, function, etc. Keywords are reserved words and they have predefined
meanings and cannot be changed by the user. Identifier names have particular
rules, such as:
1. Identifier name must begin with a letter and must be a
sequence of letters and digits.
2. The underscore character (‘_’) is considered as the
letter.
3. All the keyword must be in small letters. They have
reserved works and they cannot be treated as a variable in the program. They
use specified syntax.
4. The C language is case sensitive. For example, rate, Rate
and RATE are treated as three different types of data.
5. For any internal identifier name, at least 31 characters
are significant.
The keywords are:
·
Auto double int struct
·
Break else long switch
·
Case enum registers
typedef
·
Char extern return union
·
Const float short
unsigned
·
Continue for
signed-unsigned
·
Default go to size of
volatile
·
Do if static while
Variables
A variable is an entity that has a value and is known to
the program by name. The value of the variable changes during each execution.
The variable definition associated with memory location is with the variable
name. A variable can have only one value assigned to it in every time of
execution of the program. Its value can change in different executions.
Example
F= 1.8 * c +32
The above example tells that f and c are the variables.
Their values will be changed while the program executes.
Naming a Variable
Since, a variable has a name, let us give some example of
valid variables.
I, rank, max, min, class_mark, stud_name,emp_no, Mark,
StudName, etc. are valid variables names.
Here are some invalid variables names.
·
Sun’s illegal character
(‘)
·
Fine doubled blank space
not allowed
·
5square first character
should be letter
·
teacher, sal comma not
allowed
The variable described above can be put into two
categories, namely, globally variable and local variable. The variables defined
before the main () are considered as the global variable and the variables
within the function or program modules are local variables.
The global variable can be accessed from any subprogram
or module or function whereas the local variables are confined within the same
module or function.
Example:
#include <stdio.h> #include <conio.h> Int a; Void main() { Program codes } |
In the above example, int a is the declaration of a
variable. The variable “an” is considered as a global variable which has effect
throughout the program and it can be used anywhere in the program.
Same Data Types
The C language uses various data types. Some of the most
important and common data types are listed below:
·
Char a single byte that
can hold one character
·
Int an integer
·
Float a single precision
floating point number
·
Double a double
precision floating point number
Note: Precision refers to the number of significant
digits after the decimal point. In another sense, it is the accuracy to a
certain decimal number.
Qualifier
A qualifier alters the characteristics of the data types
such as size or sign. The qualifier that alters the size is short and long.
They are applicable to the integers.
Example of Size Qualifier
·
Short int integer
represented by a lesser number of bits (usually 16)
·
Long int integer
represented by a greater number of bits (usually 32)
·
The qualifier long can
be used along with the double precision floating point type.
·
Long double an extended
precision floating point number
Examples of Sign Qualifier
The sign qualifiers are signed and unsigned. The sign
qualifiers combine the inter-data types (int, short int, and long int)
resulting in six more type of data.
·
signed chart int
·
unsigned short int
·
signed int
·
unsigned int
·
signed long int
·
unsigned long int
·
The sign qualifier can
be used with the character also.
·
signed char
·
unsigned char
Note: The size qualifier short and long cannot be applied
to the data types char and float, and sing qualifies signed and unsigned cannot
be applied to float, double and long double.
The following
table gives us the idea of the total numbers of bits and number range that can
be used in all IBM PC.
Data Type |
Bits Used |
Range of Numbers |
int short int long int unsigned int unsigned short t int unsigned long int |
16 16 32 16 16 32 |
-32, 768 to 32, 767 Same as above -2, 147, 483, 684, to 2, 147, 483,
647 0 to 65,535 0 to 65,535 0 to 4, 294, 967, 295 |
Declaration of Variables
The variables are necessarily defined before they are
used. For this purpose, we use the following conventions.
data type v1,v2, …… vn;
Here, data type refers to the type of the data and v1,v2,
etc.., respectively represent different data in single line.
Example: The following way declaring variables are more appropriate.
int count; int number, total; double ratio; int no=10; |
The last example, int no=10, represents the assignment of
10 to a variable no which is integer type of data. This is an assignment
operation. Similarly, the other assignments are:
int filament =100;
char no = ‘x’;
double balance = 25. 28;
The process of giving the initial value to variables is
called initialization. C allows the initialization of more than one variable in
one statement using multiple assignment operators.
Example of Multiple Assignments
P = q = r = 0;
a = b =c = min;
Example of Assignments
Float x, p;
double y, q;
unsigned k;
Example of Declarations
int m = 5444;
long int n = 12345678;
Example of Assignments
x = 1.23456;
y = 9.887654;
k = 54321;
P = q = 100;
Example of Printing
printf(“\nm = %d”,m);
printf(“\nmn= ”,n);
printf(“\nx = %f”,x);
printf(“\ny = %2.12f”,y);
printf(“\nk = %u”
p = %f q = % 1.21f”, k,p,q);
Displaying Variables
The output of the program is 10. The variable num is
defined before it is used. A value 10 is assigned to the variable num and
finally %d tells that the value is in integer format. The %d is the format
string. It tells the printf that the output is an int. The second parameter num
provides the actual value to be output.
Example:
#include <stdio.h> void main () { int num; num = 10; printf (“\n %d”, num); } |
Reading Variables
The scanf function reads the values of variables from the
keyboard and stores them in variables.
Example: Reading values from the keyboard
#include <stdio.h> void main () { Float years, seconds; Printf (“\n Input your age in years:
“); Scanf (“%f”,& years); Printf(“\n You have Lived for %f
seconds. “, seconds); } |
The output will be:
Input your age in years: 12
You have Lived for 378432000.000000 seconds.
Value Initialization Variables
We can declare an integer variable i by the statement:
int i;
This can be initialized in two other methods.
int i;
i = 10;
Or,
int i = 5;
If you want more than one variable to be initialized at
the same time, use the following convention.
int i = 100, j = 15;
Now, i and j both are a same (int) type of data which
have already assigned values.
Characters and Character String
A character variable %c can hold only one character which
can be alphabet or symbol. Let use examine the following example.
Example:
#include <stdio.h> main () { /* declare a character */ Char c; /* assigning a character to the
variable c*/ c =” # “; printf( “\n This is the hash symbol:
%c “,c); } |
Example: Printing ASCII code.
#include <stdio.h> void main () { int code; char symbol; printf (“\n Input an ASCII code (0
to 127) : “); scanf (“%d”,& code); symbol = code; printf ( “\n The symbol
corresponding to %d is %c”, code, symbol ); } |
In the above example, we have seen the single character that can be input to
the computer and that can be displayed. Let us examine how the strings are
accessed from the keyboard and displayed. A string in C is a sequence of
consecutive characters in the memory, the last one being the null character. A
null character has an ASCII code 0 and is called the end of string marker in C.
Example: Using String
#include <stdio.h> void main () { char mystring [20] =”My Nepal My
pride”; printf (“\n The string is : %s”,
mystring); } |
In the above
example, mystring [20] defines the number of characters that can be stored in
the string variable. The %s sign is used for string formatted output. The
characters of above string placed in sequence as follows
String |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
Char |
M |
y |
|
N |
e |
p |
a |
1 |
|
M |
y |
|
P |
r |
I |
d |
e |
\0 |
ASCII Code |
77 |
121 |
32 |
78 |
101 |
112 |
97 |
108 |
32 |
77 |
121 |
32 |
112 |
114 |
105 |
100 |
101 |
0 |
Now, let us examine how the string is scanned from the
keyboard with the help of the following example.
Example:
#include <stdio.h>
void main ()
{
char mystring [20];
scanf (“%s”, & mystring);
printf (“\n The string is: %s”, mystring);
}
In this example, if you enter a string with spaces, the
string before the first space only will be the output. This is suitable when a
long string without blank spaces is used. All the characters after the first
blank (space bar) will be truncated.
To print the entire sentence with more characters and
blank spaces, we use gets () and puts (). This is illustrated with the
following example.
Example:
#include <stdio.h> void main () { char mystring [20]; printf (“\n Enter a string: “); gets (mystring); printf(“\n The string is :”); puts (mystring); } |
While running above program, as you enter a string within
20 characters long, it is accepted by gets () function prints the string on the
screen.
Qualifiers
Qualifiers modify the behavior of the variable type to
which they are applied. Some examples of qualifiers we discussed earlier are:
int i;
signed int i;
unsigned int i;
There are two size qualifiers that can be applied to
integers: short and long. In any ANSI C complier, the size of short int, int
and long int follow the restrictions given below:
1. The maximum size of a short int is 16 bits.
2. The size of an int must be greater than or equal to that
of a short int.
3. The size of a long int must be greater than or equal to
that of an int.
4. The maximum size of a long int is 32 bits.
The size of each type on your compiler can be tested by
using size of operator. It gives the size of any data type in bytes.
Example:
#include <stdio.h> void main () { printf (“size of a short int is %d
bytes\n”, size of (short int)); printf(“size of a long int is %d
bytes\n”, size of (long int)); } |
The output of the program is:
size of a short int is 2 bytes
size of an int is 2 bytes
size of a long int is 4 bytes
The following format specifies are used for displaying
short and long integers.
Example:
#include <stdio.h> Void main () { short int shorti; long int longi; printf (“\n Input short int: “); scanf (%hd”, &shorti); printf (“\n Input long int: “); scanf (“%d”, &long); printf (“ shorti = %hd and longi =
”, shorti, longi); } |
A sample run output is given below:
input short int: 45
input long int: 600000000
shorti =45 longi = 600000000
The typedef Statement
The typedef statement is used to give new names to
exiting types. For example,
Typedef unsigned long ulong;
This statement declares ulong a new type, equivalent to
unsigned long. It can e used just any other type in program. Eg., ulong u;
Similarly, typef int integer;
Creates integer as a synonym for int. Then, you can use
integer to define variables of type int, as;
integer count;
typedef Example typedef int age;
In this example, the declaration age is a user-defined
data type, which is equivalent to type int. Hence, the varaiable declaration,
age male, female
Is equivalent to writing int male, female;
In other words, male and female are regarded as variables
of type age, though they are actually integer-type variables.
The typedef feature is particularly convenient when
defining structures, as it eliminates the need to repeatedly write struct tag
whenever a structure is referred.
Promotion and Typecasting
Promotion is the type of data conversion when the
variable of lower type is converted to a higher type i.e. the variable that
holds lower range of values or has lower precision is converted to a variable
that holds higher range of values or higher precision.
Example:
int i;
float f;
i = 5;
f = i;
Here, the last statement assigns i to f. Since, i is an
integer, while f is floating point variable, the integer i is converted to
float automatically. This is data type promotion. Another type of promotion is
the conversion of a character to an integer. This particular type of promotion
is called internal promotion.
Example:
int i;
char c;
c = ‘a’;
i = c;
The value present in the character c, i.e., the ASCII
code of the character a is assigned to the integer i.
Assignments of variables of higher types to those of
lower types result in truncation.
Example:
f = 7.8;
i = f;
Results in the fractional part (0.8) discarded. The value
7 is assigned to the integer i.
When we explicitly convert integer value i to floating
point number, the explicit type of conversions are called typecasting.
Example:
int i;
Float f;
i = 12;
j =5;
f = i/j;
Printf(“%f\n”,f);
To obtain the floating point division, we have to convert
either i or j into floating point of data. This can be done by using the
following relation.
f = float (i/j);
Constant
INTRODUCTION
A constant is fixed entity. It does not change its value
during the entire program execution. Constants can be classified as:
1. Integer constants
2. Floating point constants
3. Character constants
4. Enumeration constants
5. String literals
1. Integer Constant
An integer constant is an integer-valued number. It
consists of a sequence of digits. Integer constants can be expressed in three
ways. They are:
A Decimal Integer: A decimal integer constant can consist
of any combination of digits which is taken from the set of 0 to 9 digits.
Example: 0 1 234 5654 etc.
An Octal Integer: An octal integer constant can consist of any combination of digits which is
taken from the set of 0 to 7 digits. However, the first digit must be 0, in
order to identify the constant as an octal number.
Example: 0 01 077
Hexadecimal Integer: A hexadecimal integer constant must begin with either 0x or 0X. It can
then be followed by any combination of digits taken from 0 to 9 and also
through f (uppercase or lowercase).
Example: 0x 0x1 0x7ABC 0xabc
Unsigned and Long Constants: Unsigned integer constants exceed the magnitude of ordinary integer
constants by approximately a factor of 2 and they should not be negative. Long
integer constants need more memory. The letter appending L to the end of the
constant can create long integer constant.
Example: 5000u decimal
unsigned
1234567L decimal long
01234L octal long
0xffful hexadecimal unsigned long
2. Floating-Point Constants
A floating point constant is a base 10 number (decimal
number) that contains either a decimal point or an exponent or both.
Example: 0.00 1.00 12.56
876.567
2E-8 0.006e-3 1.66e+8 .121e12
3. Character Constants
A character constant is a single character enclosed in
single quotes (single quotation mark).
Example: ‘a’ ‘A’ ‘?’
4. Enumerated Constants
An enumeration is a user defined type with values ranging
over a finite set of identifiers called enumeration constants. For example,
Defines color as a new type having three values red, blue
and green. Each of these is an enumeration constant. Let us examine how it
works.
color c; declares c to be of type color
c = blue;
printf (“As an int, C has the value %d\n”,c);
Will print,
As an int, c has the value 1
Similarly, we can define enum type of data as follows:
enum daysofweek { sun, Mon,Tue, Wed, Thu, Fri, Sat} ;
5. String Literals (String Constants): A string literal is a sequence of characters enclosed in
double quotes. The characters may consist of letters, numbers, escape sequences
and spaces.
Example:
“C is hard for learning” string literal
“ C” is hard for learning” string literal
Symbolic Constant
A symbolic constant is a name that substitutes for a
sequence of characters. The characters may represent a numeric constant, a
character constant or a string constant. Hence, a symbolic constant allows a
name to appear in place of a numeric constant, a character constant or a
string.
Symbolic constants are generally defined at the beginning
of the program. The symbolic constant can appear after this, in place of
numeric constants, character constants,etc.
#define name text
Example:
#define PI 3.1416
#define TRUE 1
#define friend “Bhimsen”
The const Qualifier
The const qualifier defines the constant such that the
compiler uses its value and it cannot be modified anywhere in the program. This
can be achieved either by using #define preprocessor directive or using the
const qualifier.
Example:
#include <stdio.h> void main () { const float tax_rate=0.05; float sal, tax; printf (“Salary: “); scanf (“%f”, &sal); tax = sal*tax_rate; printf (“\ntax =%f\n”, tax); } |
Now, let us to
examine the same program using #define directive.
#include <stdio.h> #define tax_rate 0.05 void main () { float sal, tax; printf (“Salary: “); scanf (“%f”, &sal); tax = sal*tax_rate; printf (“\ntax =%f\n”, tax); } |
While executing the both programs, you will get the same
result.
Operators and Expressions
Every expression evaluates to a value. Every expression
results in some value of a certain type that can be assigned to a variable. The
data items that operators act upon are called operands. An operator is a symbol
that operates on a certain data type. The operator generally remains between
the two operands. An expression is a combination of variables, constants, and
operators written according to the syntax of the language.
Based on their utility, the operators are classified into
different categories in C. Some of the most common operators are listed below.
1. Arithmetic Operator
2. Relational Operator
3. Logical Operator
4. Assignment Operator
5. Increment and Decrement Operators
6. Conditional Operator
7. Bitwise Operator
8. Comma Operator
9. Other Operator
1. Arithmetic Operator
The arithmetic
operators perform arithmetic operations and can be classified into unary and
binary arithmetic operations. The arithmetic operators can operate on any
built-in data type. A list of arithmetic operators and their meanings are given
below:
Operator |
Meaning |
+ - * / % |
additional or unary plus subtraction or unary minus multiplication division modulo division (returns remainder
after division) |
Note: for writing the power, there is no special
operator. However, the function pow(x,y) exists in math.h which return x^x.
2. Relational Operator
The relational
operators help to compare two similar quantities and depending on their
relation, take some decisions. If the condition is true, it evaluates to an
integer 1 and zero if the condition is false. The basic types of relational
operator are:
Operator |
Meaning |
< > <= >= == != |
less than greater than less than or equal to greater than or equal to equal to not equal to |
In order to study the relational operators, it is desired
to have knowledge of if statements. Here, if it is followed by the condition
and the condition is built up from the relational operators in between the
operands.
3. Logical Operator
The logical operator is used to compare or evaluate
logical and relational expressions. There are three logical operators.
An expression that contains both && and || is
called compound expression.
4. Assignment Operator
One of the most common assignment operators is an equal
sign. The character or value on the right is assigned to the variable on the
left of equal to sign. The other forms of assignment operators are:
1. += evaluates the expression to its right and adds the
resulting value to the variable on its left.
2. -= evaluates the expression to its right and subtracts
the resulting value to the variable on its left.
3. /= evaluates the expression to its right and divides the
resulting value to the variable on its left.
4. *= evaluates the expression to its right and multiplies
the resulting value to the variable on its left.
5. a<<=5 shifts the bits of a to the left by 5-bit
positions.
6. a>>=5 shifts the bits of a to right by 5-bit
positions
5. Increment and Decrement Operators
The increment and
decrement operators are very commonly used in C language. The increment
operators and decrement operators are extensively used in the loops using
structures such as for, while, do, etc. The syntax of the operators is given
below.
++<variablename> --<variablename> <variablename>++ <variablename)-- |
preincrement predecrement postincrement postdecrement |
The preincrement operator increases the value of the
variable by 1 and then the processing does whereas post increment first
processes and increase the value of it by 1.
6. Conditional Operator
A conditional operator is very rarely used. This can be
carried out with the conditional operator (? : ) An expression that makes use
of the conditional operator is called a conditional expression. This can
replace the if-else statement. The syntax of conditional operator is:
Expression_1 ? expression_2: expression_3
During evaluating
the conditional expression, expression_1 is evaluated at the first step. If
expression_1 is true (nonzero), then expression_2 is evaluated and this becomes
the value of the conditional expression.
Library Functions
INTRODUCTION
In C language, a number of library functions are used.
They carry out various commonly used operations or calculations. Some functions
return a data item to their access point and others indicate whether a
condition is true or false. Some other functions carry out special operations
on data items.
Library functions that are functionally similar and
usually grouped together as object programs (compiled) in separate library
files. These library files are supplied as a part of each C compiler.
A library function is accessed simply by writing the
function name, followed by a list of arguments that represent information being
passed to the function.
The arguments must be enclosed in parentheses and
separated by commas. These arguments can be constants, variable names, etc.
Some important functions are given below.
List of Library Functions
Function |
Type |
Purpose |
abs(i) ceil(d) cos(d) cosh(d) exp(d) fabs(d) floor(d) fmod(d1,d2) getchar() log(d) pow(d1,d2) printf(…) putchar(c) rand() sin(d) sqrt(d) srand(u) scanf(…) tan(d) toascii(c) tolower(c) toupper(c) |
int double double double double double double double int double double int int int double double void int double int int int |
Return the absolute value of i. Round up the next integer value Return the cosine of d. Return the hyperbolic cosine of d. Raise e to the power d. Return the absolute value of d. Round down the next integer value Return the remainder Enter a char from the standard input
device Return the natural logarithm of d. Return d1 raised to the power d2. Send data items to the standard
output device Send a character to the standard
output device Return a random positive integer Return the sine of d. Return the square root of d. Initialize the random number
generator. Enter data items from a standard
input device. Return the tangent of d. Convert value of an argument to
ASCII. Convert the letter to lowercase. Convert the letter to uppercase. |
Data Input/output
The most common library functions responsible for input
and output operations in C are: getchar (),
Putchar (), scanf (), printf (), gets (), and puts ().
The getchar () and putchar () are the functions used to accept a single
character from the keyboard and display on the monitor. The scanf () and printf
() functions are flexible.
They can accept values, characters, and strings and use
suitable format specifier that can be displayed. Knowing the structure of these
functions one can write many C programs in a simple form. Let us examine each
of them.
The getchar () Function
Single character can be entered into the computer using
the C library function getchar (). This is a part of the standard I/O library.
It returns a single character from the standard input device (keyboard). The
function does not require any arguments but empty parentheses must follow the
keyword getchar.
Syntax:
Character variable = getchar ();
While using getchar () with file handling functions, if
an end-of-file condition is encountered with reading a character with the
getchar function, the value of the symbolic constant EOF will automatically be
returned.
# Write a program to input a character form the keyboard and print.
#include <stdio.h> main() { char c; printf(“\n Enter a character: “); c = getchar (); printf(“\n The character input is
:”); putchar (c); } |
The putchar () Function
The putchar () function is used to display single
characters. It is a part of standard C I/O library. It transmits a single
character to the standard output device (monitor). The character being
transmitted will normally be represented as a character-type variable. It must
be expressed as an argument to the function, enclosed in parentheses, following
the word put char.
Syntax:
Putchar ( character variable);
# Write a program to test and verify putchar () function.
#include <stdio.h> main() { char c; printf (“\n Enter a character of
your own:”); c = getchar (); printf(“\n The character that you
have entered is:”); putchar (c); } |
While executing the program, if you enter a word, the
first character is only displayed. This is due to the fact that single
character is passed to the character-type variable c.
String Input/output Functions
The above discussed functions can print the characters
only. You can use a scanf() function to read a line of text but during
printing, the characters before the white space are only printed. Let us
examine the following program.
# Write a program to accept a string of 80 characters long and print it.
#include <stdio.h> #include <ctype.h> main() { char string [80]; printf(“\n Enter a string:”); scanf(“%s”,&string); printf(“\n The string accepted is
%s”, string); } |
While executing the above program if you enter a word of
80 characters long without any spaces, it will be printed. But if you supply
space before at any place, only the first word will be printed.
The gets() and puts() Function
The gets() and puts() functions are used to input
complete sentences with comma, semicolon, etc. and that can be printed on the
screen.
Example
#include <stdio.h> main() { char ch [80]; gets (ch); …….. ……… } |
The above segment of the program has defined ch variable
with 80 characters as an array. The gets() function contains the same variable
in the parentheses.
Here, puts() is an output function which lets to display
the output on a suitable device. This function is generally used to display the
output that has been accepted from the keyboard.
Write a program in C to accept a sentence with comma and semicolon and
print on the screen.
#include <stdio.h> void main () { char c[ 80]; printf(“\n Enter a sentence:”); gets (c); printf(“\n The entered sentences
is:\n”); puts (c); } |
We can use an alternative form of entering a line of text
using the following convention.
# Write a program to input a line of text without using gets () and puts ()
function.
#include <stdio.h> #include <conio.h> main () { char line [80]; printf(“\n Enter a line of text:”); scanf(“% [^\n”, line); clrscr (); printf(“\n You have entered the line
of text as follows”); printf(“\n\n %s”, line); } |
General Input: The scanf() Function
The C library function scanf() is used for entering the
data from the standard input device such as a keyboard. This function can be
used to enter any combination of numerical values, single characters, and
strings.
Syntax:
scanf(“control string”, arg1, arg2, ………, argn);
Here, the control
string (also called format string) includes the group of characters with one
group of characters for each input data. Each character group begins with a %
sign. A single character group consists of the % sign followed by a conversion
character that indicates the data type. Different types of data items and
conversion character are given in the below table.
Conversion Character |
Meaning |
%c %d %e %f %g %h %i %o %s %u %x [……..] |
Data item is a single character Data item is a decimal integer Data item is a floating point value
(exponent, scientific notation) Data item is a floating point value Data item is a floating point value Data item is a short integer Data item is a decimal, hexadecimal
or octal number Data item is an octal integer Data item is a string followed by a
whitespace character (the null character \0 will automatically be added at
the end) Data item is unsigned decimal
integer Data item is a hexadecimal integer Data item is a string which may
include whitespace characters. |
Example: Test for input of a decimal number.
#include <stdio.h> main () { int i; printf(“\n Enter an integer:”); scanf(“%d”,&i); printf(“\n The input decimal value
%d”, i); } |
General Output: The printf () Function
The output data can be given to the monitor from the computer
using the printf() function. This function is useful for printing any numerical
values, single characters, and strings. It is similar to the scanf() function
but it is used to display the data on the suitable standard output device. The
printf() function moves the data from computer’s memory to the output device.
Syntax
Print(“control string”, arg1, arg2, ……., argn);
The control string is also known as a format string. The
format string contains text, commas and a format specifier such as %c, %d, %f,
etc. which receive the data from the arguments respectively.
Example: Test of a format string and format specifier.
#include <stdio.h> main () { int i; printf(“\n Enter an integer:”); scanf(“%d”,&i); printf(“\n The input decimal value
%d”,i); } |
Let us examine the line:
printf(“\n The input decimal value %d”,i);
This line
contains %d within the double quotes which is format specifier and receives the
value from i.
……………………………………………………………………………………………………………………………………………………….
Control Structures
INTRODUCTION
C programs are written in the linear fashion. The linear
programs have almost no logical comparison. A realistic C program may require
that a logical test is carried out at some particular point within the program.
One of the several possible actions will then be carried out, depending on the
outcome of the logical test.
The outcome obtained by making comparisons and moving
further calculations is known as branching. Logical statements are tested from
several available groups of statements within the program. The program which
forms repetitions for a certain number of time is known as looping.
All these branching, selection, and looping are the
fundamental necessities of the program without which one cannot make decisions
and the program remains incomplete. Structures use different kinds of signs and
symbols for constructing the control flow within the program. The logical
expressions, relational operations, assignment operators are extensively used
in the different program.
The common relational operators are: <, <=, >,
>=, the equality operators are: = = and !=. The logical connectives are
logical operators such as && (And), || (OR). The conditional operator ?
: is also used in the expression in the program.
There are three different kinds of statements in C;
expression statements, compound statements and control statements. An
expression statement consists of an expression followed by the semicolon. A
compound statement consists of a sequence of two or more consecutive statements
enclosed in braces ({ and }).
The enclosed statements can be expression statements,
other compound statements or control statements. Most control statements
contain expression statements or compound statements including embedded
compound statements.
Thus, control statements are two types They are:
1. Decision-making statements
·
if statement
·
else statement
·
switch statement
2.
Looping statements
·
for loop
·
while loop
·
do-while loop
The if Statement
A single line if statement makes a decision about a
single condition.
Syntax:
If (condition)
statement;
# Write a program to check whether a given number is divisible by 4.
#include <stdio.h> void main() { int i; printf(“\n Enter a number:”); scanf(“%d”,&i); if (i%4=0) printf(“\n The number given is
divisible by 4. \n”); } |
# Write a program to convert a given time number into seconds.
#include<stdio.h> void main() { float years, secs; int success; printf(“\n Input Your Age in
Years:”); scanf(“%f,&years); success = years; if (successs ==0) { printf(“\n The input value is not
floating point number.”); } if success !=0) secs = years *365*24*60*60; printf(“\n You have lived for %f
seconds.\n”,secs); } |
In above program, if statement justify the same condition
for two times. The program becomes longer. The judgment takes place two times
and if you have such conditions repeatedly in the program it slows down the
program.
# Write a program to determine the largest number among three input
numbers.
#input <stdio.h> void main() { float a, b, c, big; printf(“\n Input First Number:”); scanf(“%f”,&a); printf(“\n Input Second Number:”); scanf(“%f”,&b); printf(“\n Input Third Number:”); scanf(“%f”,&c); /* making comparison and computing
*/ big = a; if (b>big) big =b; if (c>big) big =c; printf(“\n Largest Number among
three is %f \n”,big); } |
For a condition,
the program need to execute more than one line should be placed compound or
placed within the compound statements as:
If (condition) { Statement; Statement; } |
The if..else Statement
The if..esle statement is the statement which compares
the given condition. If the condition is true, the execution takes place
immediately after the if clause. If the condition is false, the execution takes
place immediately after the else clause. The statements within after if and
else can be compounded. If the statements are not compounded, the first
statement immediately after the clause will be executed.
It is a condition testing statement. As long as the
statement 1; a group is not included in the compound statement, only the first
line will be executed. If you want to execute multiple lines under the given
condition use if clause or else clause.
# Write a program to test whether the given input is zero or non-zero.
#include<stdio.h> void main() { int input; printf(“\n Enter a number:”); scanf(“%d”,&input); if(input) printf(“\n It is non-zero.\n”); else printf(“\n It is zero.\n”); } |
Compound Statement
A compound statement is set of statements enclosed within
a pair of curly braces. The curly braces are:{ and}. The {braces is opening
brace and } is closing brace. We have discussed these compound statements in
our previous examples.
A compound statement is not simply sequences of
executable statements. They can also contain variable declarations at the
beginning. The variables declared explicitly within the compound statements
have local scope.
Example: Test of variables within the compound statements
#include<stdio.h> void main() { int i = 10; printf(“\n In the main, i is %d.\n”,
i); /* beginning of a compound statement
*/ { /* variable declared */ int i = 20; printf(“\n Inside the compound
statement. i is %d\n”,i); i++; printf(“\n After incrementing the
value of i is %d\n”,i); } printf(“\n In the main() the value
of i is %d. \n”i); } |
# Write a program to check whether a given number is a prime number.
/* check prime number */ #include<stdio.h> #include<conio.h> main () { int a, b=2, r, n; printf(“\n Enter a number:”); scanf(“%d”,&a); n = a; if (a==1 | | a==2 | | a==3) printf(“The num %d is prime
number”,n); while (b! = (a-1) { aa: r = a%b; b=b+1; if ( r ==0) { printf(“\n The num %d is not a prime
number.”, n); break; else if (b!= (a-1) { goto aa; else printf(“\n The num %d is a prime
number.”, n); } } |
# Write a program to check whether a given number is odd or even.
#include <stdio.h> #include <conio.h> main() { int a,r; printf(“\n Enter a number:”); scanf(“%d”, &a); r=a%2; if(r==0) printf(“\n The given number %d is
even number.”, a); else printf(“\n The given number %d is
odd number.”, a); getch(); } |
# Write a program to check whether the given number is larger than 100.
#include <stdio.h> #include <conio.h> void main () { int a; printf(“\n Enter a number:”); scanf(“%d”, &a); if (a>=100) printf(“\n The number is larger than
100”); else printf(“\n The number is smaller
than 100”); |
# Write a program to check whether a student can enroll
in grade XI where the conditions are:
Students must score more than 70 in Math, Science and English.
#include <stdio.h> #include <conio.h> void main () { clrscr(); int sc, math, eng; printf(“\n Enter marks scored in
Science:”); scanf(“%d”,&sc); printf(“\n Enter marks scored in
Maths:”); scanf(“%d”,&math); printf(“\n Enter marks scored in
English:”); scanf(“%d”,&eng); if (sc>=70 && math>=70
&& eng>=70) printf(“\n You are selected.”); else printf(“\n You are not selected.”); } |
The Switch Statement
INTRODUCTION
The switch statement causes a particular group of
statements to be chosen from several available groups. The switch statement is
useful when a variable is to compare with different constants, and in case it
is equal to a constant, a set of the statement are to be executed. The
constants used in the case can be of char or int data type only.
Syntax:
Switch (n) { Case 1: Statement 1; Statement 2; Break; Case 2: Statement 1; Statement 2; Break; Case 3: Statement 1; Statement 2; Break; ………… …………. default: statement ; statement; } |
Note: If you are using a character in place of n in above
syntax example, the case should be enclosed in a single quote as case ‘1’ :,
case ‘2’:, etc.
# Write a program to accept choice to find the cost price for traveling
from Kathmandu to different destination.
#include <stdio.h> #include <conio.h> void main () { int choice, num; float rate, total=0; printf(“\n Enter your choice: \n”); printf(“\n 1. Pokhara “); printf(“\n 2. Biratnagar “); printf(“\n 3. Birgunj“); printf(“\n 4. Exit“); scanf(“%d”, &choice); switch (choice); { case1: rate =350; printf(“\n Number of persons: “); scanf(“%d”,&num); total = rate * num; printf(“\n The cost is : %5.2f”,
total); break; case 2; rate =300; printf(“\n Number of persons : “); scanf(“%d”, &num); total = rate *num; printf(“\n The cost is %5.2f”,
total); break; case 3; rate =250; printf(“\n Number of persons : “); scanf(“%d”, &num); total = rate *num; printf(“\n The cost is %5.2f”,
total); break; case 4: break; default: puts (“Thank you”); break; } |
Design a program to input two integer numbers from keyboard. On the basis
of choice, find out product, sum and difference.
#include <stdio.h> #include <conio.h> main () { clrscr (); /* use of case, switch and getch ()
*/ int a, b, t=0; char ch; printf(“\n Enter first number :”); scanf(“%d”,&a); printf(“\n Enter second number :”); scanf(“%d”,&b); again: printf(“\n Enter choice : 1, 2 or
3”); ch = getch (); switch (ch) { printf(“\n Enter choice : 1, 2 or
3”); ch = getch (); switch (ch) { case ‘1’: t=a*b; printf(“\n Product is: %d”,t); break; case ‘2’: t=a+b; printf(“\n Sum is : %d,t); break; case ‘3’ : t=a-b; printf(“\n Difference is: %d”, t); break; default: printf(“\n Wrong entry.”); goto again; } } |
# Write a program to find area and perimeter of a triangle.
#include <stdio.h> #include <math.h> main () { float a, b, c, base, height, area,
s, p; int k; printf(“\n Enter 1 for 3 sides of
triangle & 2 for height and base of triangle :”); scanf(“%d”, &k); switch (k) { case 1: printf(“\n Enter 3 sides a, b &
c:”); scanf(“ %f %f, &a, &b,
&c ); p = a+b+c; s=p/2; area = sqrt ((double) (s* (s-a)*
(s-b)* (s-c) ) ); printf( “\n Perimeter = %6.2f
\n”,p); printf(“\n Area = %7.2f\n”, area); break; case 2: printf(“\n Enter height and base of
triangle:”); scanf(“ %f %f, &height,
&base); area = (base*height) /2; printf(“\n Area = %7.2f\n”, area); break; } |
Looping Constructs
A loop is structured construct which repeats for given
number of times. Looping makes a program more flexible. The number of times the
loop passes is known as iteration. The iteration is initialized at the
beginning whereas the last value of the loop is known as the sentinel value.
The loop repeats till the sentinel value. For the
construction of the loop, the loop variable should be initialized, incremented
or decremented and assigned the last value of the loop. Basically, there are
two types of loops.
1. Finite Loop and
2. Infinite Loop
A finite loop has a certain number of repetitions. It
stops when the last value is reached. But, the infinite loop does not stop
because it does not have the last value assigned. The infinite loop, in this
case, is useless. But, some system programmers use infinite loops for system
delay and operational delay inside the processor.
A loop consists of two segments known as control
statement and the body of the loop. There are three kinds of loops. They are:
1. For loop
2. While loop
3. do …while loop
For loop: Before using
for loop, let use to examine the structure of statement.
Syntax:
for ( initialization expression;
test expression; updated expression) { statement 1; statement 2; ………………...3; …………………..; statement n; } |
Initialization expression is the expression which
initiates the first value of the loop.
Test expression determines the last value of the
expression.
The updated expression is the increment or decrement from
the initialization so that the last value or test expression could be reached.
The infinite loop, where beginning and ending are not
expressed there is no initialization, text and update expressions.
# Write a program to find sum of given three numbers using for loop
construct.
/* Program to find sum of given
three numbers using for loop */ #include <stdio.h> #include <conio.h> int main () { int i=1, a[3]; float sum=0; float avg=0; for (i=1; i<=3; i++) { printf(“\n Enter %d number: “i); scanf (“%d", &a [i]); } avg=sum/3; printf(“Sum of given numbers is :
%4.2f”, sum); printf(“\n Average is %4.2f”, avg); } |
# Write a program to print first ten even numbers.
#include <stdio.h> main () { int n=2,c =1; for (c=1; c<=10; c++) { printf(“%d\t”,n); n=n+2; } } |
# Write a program to find the factorial of a given number.
/* finding factorial of a number */ #include <stdio.h> #include <math.h> void main () { int n, i, fact; printf(“\n Enter a number:”); scanf(“%d”,&n); if (n= =0) { printf(“\n Factorial of %d is 1”,n); } else { fact =1; for (i=1; i<n; i++) { fact =fact *i; } printf(“Factorial of %d is %d”, n,
fact); } } |
# Write a program to print first 10 number of Fibonacci series of order 2.
#include <stdio.h> #include <conio.h> #include <math.h> void main () { int a=1,b=1,c=0,d; for (d=1; d<=10; d++) { printf(“%d”,a); c=a+b; a=b; b=c; } |
Looping With while statement
The while statement is used to carry out looping
operation, in which group of statements is executed repeatedly until some
condition has been satisfied.
Syntax:
while (expression) { statement 1; statement 2; ………………….; statement n; } |
The statement will continue as long as the expression is
true. The statement can be simple or compound though it is usually compound
statement. It should be noted that within the compound statement, the
expression should be changed for stopping the loop. Let us examine a program
below.
# Write a program to print the numbers is prime number. A prime number is
divisible by 1 and itself.
/* check prime number */ #include <stdio.h> #include <conio.h> main () { int a, b=2, r, n; printf(“\n Enter a number :”); scanf(“%d”, &a); n =a; if (a==1 || a==2 || a==3) printf(“The num %d is prime number”,
n); while (b!=(a-1)) { aa: r=a%b; b=b+1; if (r==0) { printf(“\n The num %d is not a prime
number “,); break; } else if (b!= (a-1)) { goto aa; } else printf(“\n The num %d is a prime
number”,n); } } |
# Write a program to check whether given number is Armstrong number.
Armstrong number is the number which is equal to the sum of the cubes of its
individual digits.
/* Check for Armstrong number */ #include <stdio.h> void main () { int a, n, r, sum=0; printf(“\n Enter a number:”); scanf(“%d”,&a); n=a; while (n!=0) { r=n; if (r!=0) { sum +=r*r*r; } n =n/10; } printf(“\n Sum of cubes of given
digits = %d”, sum); if (sum==a) { printf(“\n Given number %d is equal
to sum of cubes of individual digits %d”, a, sum); printf(“\n The number is Armstrong
number”); } else printf(“\n The number is not a an
Armstrong number”); |
…………………………………………………………………………………………………………………………………………………………..
Looping with do…while Statement
We have come to across the use of while statement. It is
top tested, i.e., it evaluates before executing any of the statement in its
body. The do..while loop evaluates the condition after the execution of the
statements in its construct. At least one time the do…while statement executes.
Hence, do…while statement is known as bottom tested loop.
Syntax:
do { statement 1; statement 2; ………………….; statement n; } while (test expression); |
If the program loop should pass through 1 time or single
iteration, do…while statement would look like;
do
Statement 1;
While (test expression);
# Write a program to print the following numeric pattern.
1
12
123
1234
12345
#include <stdio.h> #include <conio.h> void main () { clrscr (); int outloop=1; do { int inloop =1; do { printf(“%d”,inloop); inloop = inloop +1; } while (inloop <=outloop); outloop = outloop+1; printf(“\n”); } while (outloop <=5); } |
# Write a program to check whether a number is palindrome or not.
#include <stdio.h> #include <conio.h> void main () { int n, num,digit, sum=0, rev=0; printf(“\n Enter a number”); scanf(“%d”,&num); n= num; do { digit = num ; sum+= digit; rev =rev*10+digit; num /=10; } while (num !=0); printf(“\n Sum of the digits = M”,
sum); printf(“\n The reversed number is:
M”, rev); if (n==rev) printf(“\n Given number is
palindrome”); else printf(“\n Given number is not
palindrome”); } |
The break Statement
A break statement
is used in the program to breaking from the current point. It terminates the
execution of the current loop and the control is transferred to the statement
immediately by following the loop.
while (1) { scanf(“%d”, &i); if (I ==-1) break; sum+=1; num++; } |
This program segment has used the break statement. If the
input value is -1, the condition i==-1 is true and the break statement is
executed. Otherwise, the program continues.
# Write a program to check whether a given number is a prime number.
/* check prime number */ #include <stdio.h> #include <conio.h> main () { int a, b=2, r, n; printf(“\n Enter a number :”); scanf(“%d”, &a); n =a; if (a==1 || a==2 || a==3) printf(“The num %d is prime number
“,n); while (b!=(a-1)) { aa: r= a%b; b=b+1; if (r ==0) { printf(“\n The num %d is not prime
number”,n); break; } else if (b!= (a-1)) { goto aa; } else printf(“\n The num %d is a prime
number “,n); } } |
# Modify the above program and recheck whether a given number is prime
number using different logic.
#include <stdio.h> #include <conio.h> void main () { int a, b=2, r, n; clrscr (); printf(“\n Enter a number: “); scanf(“%d”, &a); n=a; if ((a==1 || (a==2 || (a==3)) printf(“\n The number %d is prime
number”,a); if (a>3) { while (b!= (a-1)) { aa: r= a%b; b= b+1; if (r==0) { printf(“\n %d is not a prime number”,
n); break; } else if (b! =(a-1)) goto aa; else printf(“\n The num %d is a prime
number”, n); } } } |
The continue Statement
As its name implies, it is used to continue the normal
flow of programe statement execution in loop; skipping parrticular iteration in
the loop as soon as certain condition is satified. The continue statement is
used to bypass the remainder of the current pass through a loop. The loop does
not terminate when continue statement is encountered. Instead, the remaining
loop statement is skipped and the computation proceeds directly to the next
pass through the loop.
Syntax:
#include <stdio.h> #include <conio.h> void main () { int i=1,num, sum=0; for (i=0; i<5; i++) { printf(“\n Enter an integer:”); scanf(“%i”, &num); if (num<0) { puts (“\n You have entered a
negative number.”); continue; } sum+=num; } printf(“\n The sum of the positive
integers entered = %i\n”, sum); getch (); } |
When you execute the above program, at the time you enter
a negative number, you will be prompted for negative entry of any number. It
allows you to go to next iteration. Thus, you can enter a new value for five
iterations. When you finish entering 5 positive integers, you will get the
result as you desire.
Difference
between break and continue statement
Break statement |
Continue statement |
When break statement is encountered the entire loop or switch statement
is terminated. |
when continue statement is
encountered the entire loop is not terminated only that particular itration is
skipped. |
It is used with loop and switch case statement. |
It is used only with loop structure. |
It uses a keyword break. |
It uses a keyword continue. |
The goto Statement
The goto statement is common in GWBASIC and QBASIC.
Although QBASIC is structured it resembles in many cases with the procedural
programming concept. The goto statement in programming allows you to jump from
one place to another without any conditions. This is an unconditional transfer
to another part of the program.
Syntax:
goto label name; |
Use: Unconditional jump from one point to another part of
the program.
# Write a program to check whether a given number is a prime number or not.
#include <stdio.h> #include <conio.h> main () { int a, b=2, r, n; printf(“\n Enter a number :”); scanf(“%d”, &a); n =; if (a==1 || a==2 || a==3) printf(“ The num %d is prime
number”,n); while (b! =(a-1)) { aa: r=a%b; b=b+1; if (r==0) { printf(“\n The num %d is not a prime
number”,n); break; } else if (b!= (a-1)) { goto aa; } else printf(“\n The num %d is a prime
number”,n); } } |
# Modify the above program and recheck whether a given number is prime
number using different logic.
#include <stdio.h> #include <conio.h> void main () { int a, b=2, r, n; clrscr (); printf(“\n Enter a number :”); scanf(“%d”, &a); n=a; if ((a==1 || (a==2) || (a==3)) printf(“\n The number %d is prime
number”,a); if (a<3) { while (b!=(a-1)) { aa: r=a%b; b=b+1; if (r==0) { printf(“\n %d is not a prime
number”,n); break; } else if (b! =(a-1)) got aa; else printf(“\n The num %d is a prime
number”, n); { } } |
Nested Control Structures
Loops like if…else, for, do…while and while statements
can be nested, one within another. A loop inside another loop is nested loop.
While constructing nested loops, it is necessary to have the same type of
looping structure. The number of loops within a loop as many as you desire but
some systems limits to its memory limitation.
# Write a program to print multiplication table of number from 1 to 10 up
to 10 multiples.
/* multiplication table */ #include <stdio.h> #incldue <conio.h> void main () { int pro, i, j; for (int i=1; i<=10; i++) { for (int j=1; j<=10; j++) { pro=i*j; printf(“%d\t”, pro); } } } |
# Write a program to print the following pattern.
*
**
***
****
*****
#include <stdio.h> #include <conio.h> void main () { int i, j; char c=’*’; for (i=1; i<=5; i++) { for (j=1; j<=I; j++) { printf (“%c”, c); } printf(“\n”); } } |
# Write a program to print the following numeric pattern
(using do…while condition).
1
12
123
1234
12345
#include <stdio.h> #include <conio.h> void main () { clrscr (); int outloop=1; do { int inloop =1; do { printf(“%d”,inloop); inloop = inloop +1; } while (inloop <=outloop); outloop =outloop+1; printf(“\n”); } } |
……………………………………………………………………………………………………………………………………………………………..
Functions
INTRODUCTION
A number of statements grouped into a single logical unit
are called as function. It is true that C program is the collection of
functions. The function main() in the program is executed first. The other
functions are executed when the function main() calls them directly or indirectly.
It is necessary to have a single function main () in
every C program along with other functions. It is observed that the main()
function is also user defined function. It is executable with suitable
parameters.
We are aware of syntax and use of commands, statements,
and function in programming languages. C supports the use of library functions
which are used to carry out a number of commonly used operations or
calculations.
A C program can be modularized through the use of
intelligence of such functions. Hence, it is a modular programming. The C
language has two types of functions. They are:
1. Built-functions or C library functions
2. User-defined functions.
1. Built-function-or-C-Library-Functions:
The library functions are made available to the programmer in the inclusion of
the software product. They are precisely constructed to determine the type of
data they accept and the return type.
The library functions such as pow (), sqrt(), strcmp(),
etc, are located in the Lib folder by default.
2. User-defined Functions:
These are the functions determined by the
users. They are created for calculating different tasks. The general features
and facilities obtained from the use of user-defined functions are:
1. The repeated instructions can be placed within a single function
which can then be accessed whenever it is needed.
2. A different set of data can be transferred to the
function each time if it is accessed.
3. The use of a function avoids the need for redundant
(repeated) programming of the same instructions.
4. Functions provide the logical clarity resulting from the
decomposition of the program into several concise functions.
5. The use of functions also enables a program to build a
customized library of frequently used routines.
6. Function avoids repetitive programming between programs.
7. It also promotes portability since programs can be
written that are independent of system-dependent features.
Let us examine a function defined by the user.
int cube (int i) { Int retval; Retval = i* i * I; Return retvl; } |
This function is capable of returning a value (integer)
since it is explicitly declared in the definition line. The word cube is the
function name. The body of the function computes the cube of the value given to
i and returns the integer type of value through the variable reveal.
# Write a program to find the cube of 10 during function call and cube of
different integer value.
#include <stdio.h> #include <conio.h> int cube (int i) { int retval; retval = i*i*I; return retval; } void main () { int inputval; /* Cube of constant integer: */ /* function call with fixed value 10
as integer */ printf(“\n The cube of 10 is %d\n”,
cube (10)); /*Cube of input integer: */ Printf(“\n Input an inter:”); scanf(“%d”,&inputval); printf(“\n The cube of given value
%d is %d \n”, inputval, cube (inputval)); } |
You can predict the output. The program will give the
cube value of 10 and cube of a given number.
Use of Function
The functions are used to enhance the program. The user
defined functions help to calculate the values and return them. The functions
can be used in different programs as required. The basic three fundamental
properties of function are:
1. Functions help to divide the program into a number of
parts.
2. Reduces the size of a program because it can be called
independently.
3. Makes easier to find errors and debug them.
While writing a program, it is split into smaller
programs or functions in C. A main program is split into different programs or
functions .
The major activities of the function while programming
is:
1. Function declaration
2. Function call
3. Function definition
1. Function Declaration
The function is generally written above the main()
function. It is true that main is the main function without other functions
cannot execute. It is the entry point. A complete function can be written
before the main () function and that can be called from within the main()
function.
The generalized concept about the declaration of function
could be as follows:
·
Declare function to
inform the compiler that the function would use at the later point.
·
Declare function at the
beginning of a program.
·
Function declaration
includes function name, arguments, and their types, and return type of data.
Example
Void sum(); /*function declaration without parameter or
arguments*/
Syntax:
Type specifier, function name (arguments);
Here,
Type specifier refers to the type of the function such as
void, int, float, etc.
Function is the name of the function which can have as
many as 40 characters arguments could be int, float, int pointer, etc. which
indicates the type of return value in the function.
The function is generally declared before the main(). It
may be defined anywhere in the program but it should be declared at the
program.
2. Function Call
This is the part which executes the function. The
function is called from within the main().
The function and its parameters are explicitly included
within the function. Let us examine the function call as stated in above
program. The last section of this line cube (inputval) is the function call.
Although, it could be called in various ways, one of the simplest ways of
calling function is shown at this level.
A function can be accessed or called by specifying its
name followed by a list of arguments enclosed in the parentheses and separated
by commas. If the function call does not require any arguments, an empty pair
of parentheses must follow the name of the function.
The arguments appearing in the function call are referred
to as actual arguments. In the normal function call, there will be one actual
argument for each formal argument. The programmer needs to mention at least the
following points about calling a function.
·
Call from the main
program with arguments or without arguments.
·
Functionname ();
indicates function defined.
·
During function calling,
control transfers to the called function. Eg. Sum(); calls sum() function.
3. Arguments
The actual arguments must correspond to the formal
arguments in the function definition, i.e., the number of actual arguments must
be the same as the number of formal arguments and each argument must be of the
same data type as its corresponding formal argument.
·
Arguments are the
variables within the function.
·
The arguments can be
either passed by value or by reference.
·
During argument passed
by value, the numbers are explicitly defined.
·
The references take the
values through the variables.
…………………………………………………………………………………………………………………………………………..
Function Definition
Function Definition
The body of the function begins just like in the same
fashion as the main () function. The body of the function contains various
statements, calculation modules, logic to determine different values and
processing and return value. The return value is the type of value that should
have been declared in the function declaration part. The general concept of a
function definition is given below.
Parameter declaration
{ Body of function; Return expression; } |
Note:
·
Generally, the function
is defined before mains ().
·
The function is
generally called from the main ().
·
The function defined
before main follows a semicolon.
·
The function definition
contains function body and calculation section.
While defining a function, one has to remember the
followings.
·
Contains the actual
codes for the program.
·
The body of the function
follows function declaration.
·
Function declaration and
a name of the function definition should be same with the same arguments and
same return data type.
·
Function declaration
terminates with the semicolon (;).
·
Function definition
terminates without semicolon (;).
Example:
void main () { /* function definition*/ Program codes; } |
Function Prototype
The
functionprototype is the outline of a general function. The prototype given
below illustrates the different parts of a function.
#include <stdio.h> ......... .......... /* function declaration or prototype
*/ void function1 (); void function2 (); .......... ......... main () { ............. ........... /* calling function */ function1 (); function2 (); ............ ........... } /* function definition */ function (parameters) { ...................; body of the function; .....................; } |
# Write a program to find the sum of two numbers with a function sum ().
#include <stdio.h> #include <conio.h> void sum (); void main (); { printf(“/n Example of calling
function “); sum (); /* function is called */ printf(“/n return from function”); } /* function defition */ void sum () { int a, b, t; printf(“\n print first number:”); scanf(“%d”, &a); printf(“\n print second number:”); scanf(“%d, &b); t=a+b; printf(“\n Sum of the two is %d”,
t); } |
Functions handle the variables. The variables within the
function itself are local to the function. A variable explicitly declared
outside the function (outside main () also) is known as the global variable.
Global variables are accessed by all the functions in the program. The use of
global variable are with the help of scope resolution operator.(::) which is
beyond this text.
Illustration of global variable the above program is changed to accept a
global variable.
#include <stdio.h> #include <math.h> Float t; Void sum (); Void main () { Printf(“\n Example of calling
function “); Sum; /* fucntion is called */ Printf(“\n Sum of the two is %4.2f”,
t); Printf(“\n return from function”); } /* function defition */ Void sum () { Int a,b; Printf(“\n Print first number:”); Scanf(“%d”, &a); Printf(“\n Print second number:”); Scanf(“%d”, &b); t=a+b; } |
Function argument passed by value
#include <stdio.h> #include <conio.h> #include <math.h> sum (int,int); main () { printf(“\n Example of calling
function:”); sum (15, 10); printf(“\n Return from the
function.”); return 0; getch (); } sum (int a, int b) { int t; t=a+b; printf(“\n Value of A = %d”,a); printf(“\n Value of B =%d”, b); printf(“\n sum of %d and %d is
%3.2f”, a, b, t); } |
Parameter passed by value
#include <stdio.h> #include <math.h>\ sum (int, int); main() { int tot; printf(“\n Example of calling
function”); tot=sum (10, 15); printf(“\n Return from function\n”); printf(“\n The sum is %d”, tot); return0; } /*function definition */ sum (int a, int b) { int t; printf(“\n Value of a =%d\n”, a); printf(“\n value of b =%d\n”, b); t=a+b; return (t); } |
Function call with parameter passing by value.
#include <math.h> #include <conio.h> void change (int, int); void main () { int a = 15, b = 10; clrscr (); printf(“\n Before calling
function”); printf(“\n Value of a = %d”, a); printf(“\n Value of b = %d\n\n”, b); printf(“\n After calling function”); change (a, b); printf(“\n After returning from
function”); printf(“\n Value of A = %d”, a); printf(“\n Value of b = %d, b); } /* function definition */ void change (int a, int b) { int t; t=a; a=b; b=t; printf(“\n Value of a = %d”, a); printf(“\n Value of b = %d\n\n”, b); } |
Parameter passing by reference
#include <stdio.h> #include <math.h> #include <conio.h> void change (int &, int &); /*
address of values */ main() { int a=15, b=10; clrscr (); printf(“\n Before calling funtion
“); printf(“\n value of A = %d”, a); printf(“\n value of B = %d\n\n”, b); printf(“\n After function is
called:”); change (a,b); /* function called by
passing reference */ printf(\n After returning from
function”); printf(\n Value of A = %d, a); printf(“\n Value of B = %d”, b); } /* function definition */ void change (int &a, int &b) { int t; t=a; a=b; b=t; printf(“\n Value of A = %d”,a); printf(“\n Value of b = %d\n”, b);\ } |
Interchanging the input values in the program using function. Here, the
function is preceded by the main () function.
#include <stdio.h> /* interchanging the value */ void swap (int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; } void main () { int i, j; printf(“\n Enter first number:”); scanf(“%d”, &i); srintf(“\n Enter second number:”); scanf(“%d”, &j); printf(“\n Before swapping %d %d
\n”, i, j ); swap (&i, &j); printf(&i, &j); printf(“\n After swapping %d %d”, i,
j); } |
Function That Returns a Value
A function with a return value produces a value and
returns it to the statement within the function that call it. Function with
return values requires that a return statement is used so that the value is
returned to the calling statement.
C does not place any restriction on the type of return
values except that the value cannot form an array. Hence array cannot be the
return type. A pointer to an array can be returned. But a function can return
an array that is a part of a structure.
# Write a program to find the factorial of a number with the help of a
function fact (unsigned int).
#include <stdio.h> #include <conio.h> long fact (unsigned int); /*
function prototype */ void main (void) { unsigned int Num; long factorial; printf(“\n Enter a positive
number:”); scanf(“%u”, &Num); factorial = fact (Num); printf(“\n The factorial of %u is
%li”, Num, ffactorial); } long fact (unsigned int n) { long fact (unsigned int n) { long 1fact; int i; if (n==0) 1fact = 1; /* Factorial of 0 is 1 */ else { 1fact = 1; for (i=2; i<=n;i++) 1fact = 1fact *i; } return 1fact; } |
# Write a program to check whether a given word is palindrome by using
function.
#include <stdio.h> #include <string.h> #include <ctype.h> enum Boolean{ false, true}; enum Boolean IsPalindrome (char
string[]) { int left, right, len=strlen
(string); enum boolean matched = true; if (len == 0) return true; left = 0; right = len-1; /* compare the first and last
letter, second and last but one ..*/ while (left <right &&
matched) { if (string [left] != string[right]) matched =false; else { left++; right--; } } return matched; int main (void) { char string [40]; printf(“\n Program to test the given
string is palindrome \n”); printf(“\n Enter a string:”); scanf(“%s”, string); if (ispalindrome (string) printf(“\n The given string %s is a
palindrome \n”, string); else printf(“\n The given string %s is
not a palindrome \n”, string); return 0; } Array
and Strings INTRODUCTION It is true that many applications
require the processing of multiple data items that have common features.
Here, it should be noted that the data items are similar. The individual data
items can be characters, integers, floating point numbers, etc. However, they
all must be of the same type and the same storage class. Having these features
an array can be formed. Each array element or individual
data item in the array is referred by specifying the array name followed by
one or more subscripts. Therefore, it is also known as subscripted variables
as in Algebra. Hence, an array is a sequence of data in memory, wherein all
the data are of the same type and are placed in physically adjacent
locations. For example, 10 integer items or elements are placed one after
another in the memory. It is true that strings characters
are also placed in arrays. The strings are the array of characters. The array
can be one dimensional, two dimensional or multidimensional. Define
an Array An Array can be defined as the
collection of data items of the same type and we can access the array using
the common name. Int age [15]; This definition is one-dimensional
array where, int is data type of the array, age is the name of the array and [15] is the maximum number of
elements in the array. Accessing
Array Elements For accessing a particular element
in an array, the array name is followed by square braces enclosing an integer
which is called array index. The array index indicates the particular element
of the array which is going to be accessed. Note: ·
The value of the symbolic constant will be
substituted for the constant itself during the compilation process. ·
Automatic variables can be initialized but
automatic arrays cannot be initialized. ·
The array size need not be specified
explicitly when initial values are included as a part of an array definition. ·
With a numerical array, the array size will
automatically be set equal to the number of initial value included within the
definition. Initialization
of One-Dimensional Array One dimensional array is the
elements that construct a row or a single column. If the elements of the same
type are placed one after the other with similar characteristics, it forms a
one-dimensional array. int number [10] ={1, 2, 3, 4, 5, 6,
7, 8, 9, 10}; Here, int is the data type of the array the number is the name of the array [10] indicates the maximum number of
elements {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; are
the elements explicitly declared. Then, number [1] = 1 number [2] = 2 number [3] = 3 etc. If a program requires a
one-dimensional array declaration, the declaration is written in the same manner
as the array definition with the following exceptions. 1.
The square brackets may be empty since the
array size will be specified as a part of the array definition. Array
declarations are customarily written in this form. 2.
Initial values cannot be included in the
declaration. Accessing
One Dimensional Array While accessing one-dimensional
array through the keyboard we use the convention; &arrayname [expression]; The expression is the position at
which the array can be located. # Write a program to read an print
static array.
In the above program, int a [10]
explicitly declares 10 elements in the array. The array elements are enclosed
in the curly braces. The elements are summed up and their result is obtained
in floating point. Array
Initialization with Constant Value Int a[5] ={2, 4, 6, 8, 10};
Example of an array initialization
with the constant value.
# Write a program to read the static
array elements and find their sum.
In the above program, the array
definition a[] is the empty parameter which can hold as many elements as
required. You can include more elements within the curly braces. # Write a program to accept 10
elements in an array find their sum.
In this program, the definition int
a[10] declares 10 integer type of elements that can be grouped together but
they are not declared. They are accessed through the keyboard and placed in
the array. Their sum is obtained and printed. # Write a program to accept ages of
10 persons and print the average age.
# Write a program to sort the given
list of array elements in ascending order.
# Write a program to initialize 10
positive numbers (elements) in the array and find the largest among them.
……………………………………………………………………………………………………………………………………………………………… Two Dimensional
Arrays In the mathematics, we sometimes study set of numbers laid out in rows and columns. The rows are thought of as numbered
one through four from top to bottom, and the columns are numbered , one
through three from left to right. If we represent these numbers by t, then
these numbers are: t2,3 will represent -43, which is in row 2 and
column 3. We need two subscripts. The row subscript is always written
first and the column subscript second. In the two-dimensional array written
above, t2,3 =-43, t4,1 =27, and t3,2 = 62.
In BASIC these subscripts must be lifted and placed in parentheses as T(2,3),
but we still say “T sub two three”. The two-dimensional array declared
in a similar manner to one-dimensional array. The declaration of an array
would look like: Int a[3] [4]; Just as with the one-dimensional
arrays, the two-dimensional arrays must be placed in the square brackets
where first square bracket represents the number of rows and value within
second square bracket represents columns. Thus, a maximum number of rows and
columns can be declared as needed in the program. If you are declaring the
three-dimensional array, you will need three square brackets. Int a[3] [4] [5]; The total number of elements in this
array would be, 120. Two-dimensional
array could be defined as: int values [3] [4] =
{1,2,3,4,5,6,7,8,9,10,11,12}; The first number within the square
bracket indicates the number of rows and the second value in the square
bracket represents the number of columns. Thus, a total number of values or
set of arrays is 12. There is a modification in above declaration. Int values [3] [4]; { {1,2,3}; {5,6,7,8}; {9,10,11,12}; }; Accessing
Two Dimensional Arrays While inputting and accessing the
two dimensional array from the keyboard, we use the following convention. &arrayname[ expression1]
[expression]; Here, &arrayname is the name of the
array [expression1] is the row position [expression2] is the column position # Write a program to sort numbers in
a array in ascending order.
# Write a program to sort array
elements in descending order.
# Write a program to insert an
element in the series of elements.
# Write a program to define a two
dimensional array and print them and their positions.
# Write a program to demonstrate
Matrix Addition.
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, Array
with Function The array can be passed as arguments
to functions. An array can be passed as an argument from one function to
another. Let a function sum computes the sum of the array elements a[0], a[1],………..a[n] Two parameters are required an array
parameter a to catch the array passed and a parameter n to catch the index of
the last item in the array to be summed. If we assume that the array is an
array of ints and that the index n is of type int, the parameters in sum can
be described as: int sum(int a[], int n) The parameter declaration for the
array includes square brackets to signal the functions sum that a is an array
name and not the name of an ordinary parameter. # Write a program to demonstrate the
array passing within the function.
Using
Address Operator The base address of array elements
can be passed to the called function using address operator &. After the
base address is passed to the called function, pointer variables can access
other elements of an array. Passing array elements with an
address: ·
Only the name of the array is as an
argument. ·
It passes an address of the first element
called base address to the called function and can be accessed to other
elements by using pointer variables. Array
with Pointers A pointer is a variable that can
hold the address of another variable. # Write a program to pass array of
elements to the function sort() and print unsorted data before function call
and sorted data after function call.
# Write a program to find the
greatest number among the given numbers.
Arrays
of Strings A string is the sequence of
characters placed one after the other terminated with a null character’\0’.
Hence if you are entering a certain number of characters, the total
characters in the array would be the sum of the characters plus one. Each
character within the string will be stored within one element of the array. It is true that some characters
within a string can be processed individually (e.g. Piglatin). However, most
of the strings are processed as complete entities. The strings are processed
using string manipulating functions. C compilers include library
functions that allow strings to be compared, copied or concatenated. Other
library functions permit operations on individual characters within the
string. They allow individual characters to be located within the strings. # Write a program to accept a
character form the keyboard and print.
# Write a program to convert
lowercase character into uppercase character.
# Write a program to accept a
sentence and print it.
# Write a program to print the first
word of a string though you input a single word or sentence.
After running this program, you will
get only the first word of the sentence. The compiler terminates the other
characters encountered immediately after the first white space. The format specifier %s accepts a
word. The texts separated after the word with space are truncated. Hence, the
program prints a single word. # Write a program to enter name of 5
persons and display on the screen.
In the above program, the line char
name [5] [30] handles names of five persons each with a length of 30
characters including spaces and other printable characters. The line gets
(name [i] accepts the names of 5 persons where the value of i goes on
changing from 0 to 4. The gets() function handles the string of any length.
In other words, it accepts or gets the string to get string =gets). We can
use the puts () function to display the string which is used in an example. # Write a program to sort the given
strings in ascending order.
…………………………………………………………………………………………………………………………………………………. String
Manipulating Functions Generally, the early programmers
think that the strings are handled in the similar fashion as numbers in C
programming. The handling of strings is totally different from handling the
numbers. Some of the important functions used to manipulate strings are
described with the help of examples in preceding sections. ·
The strlen () function This function is used to measure the
length of the string accepted by the user or declared in the array of string. Syntax :
strlen(string) # Write a program to reverse a
string and measure its length also.
·
The strrev () function This function is used to reverse the
given string. Hence all the characters given by the user are reversed. Syntax:
streev(string); # Write a program to demonstrate the
use of strrev () function.
·
The strlwr() and strupr() functions The strlwr() function converts the
uppercase characters of the given string into lowercase whereas the strupr()
function converts lowercase characters into uppercase. Syntax:
strlwr(string); strupr(string); # Write a program to test the
strlwr() and strupr() functions.
·
The strcpy () function The strcpy() function is used to
copy a string from one variable into another variable where both the
variables are of the same type. You cannot copy data stored in the numeric
variable into a string variable. Syntax:
strcpy (target,source); Demonstrate strcpy() function
In the above program, the content of
source variable is passed to target variable. If we print both the variables,
we get the same result. ·
The strcat() function This function is generally used to
merge two strings and produce the single string. Hence, both the strings are
concatenated and a new string is in the form of merged string. Syntax:
stract(target, source); # Write a program to right
concatenate two strings “International” and “Forum”.
·
The strcmp() function The strcmp function compares two
strings and produces the result to store in a numeric variable. If both the
strings are like, it produces 0 whereas 1 is produced when both strings are
not alike. Syntax:
strcmp (string1, string2); # Write a program to compare two
strings.
# Write a program to input various
sentences. Count number of words, sentences and characters in multiple text
line.
# Write a program to count number of
words, lines and characters.
…………………………………………………………………………………………………………………………………………………………… Dereferencing
Pointers INTRODUCTION A pointer variable points to the address
in the memory. A pointer can be used to access the data from that memory
where the pointer points. Dereferencing is an operation performed to access
and manipulate data obtained in the memory location pointed by a pointer. 1.
int a, b, *p, *q; /*Illegal use of pointers
*/ A pointer variable is dereferenced
when the unary operator * is used as a prefix to the pointer variable. Any
operation performed to the dereference pointer directly affects the value of
the variable it points to. Void
Pointers The programmer should note that a
pointer defined as int cannot hold the data type defined as float or char.
Hence, pointers defined to be specific data type cannot hold the address of
any other type of variable. Pointer
Arithmetic It is true that the size of the data
type which the pointer variable points to is the number of bytes accessed in
memory when the pointer variable is dereference using the indirection
operator (*). The size of the pointer variable is dependent on the type of
variable pointed by the pointer. The C language allows arithmetic
operations to be performed on pointer variables. Some valid pointer
arithmetic and invalid pointer arithmetic are listed below. Valid
Pointer Arithmetic 1.
p = p – b 2.
p = (int*) (p-q); 3.
p = (int*) (p-q)-a; 4.
p = p+a Invalid Pointer
Arithmetic 1.
int a, b, *p, *q; /*Illegal use of pointers
*/ 2.
p = - q; /*Illegal use of pointers */ 3.
p = p - q; /*Illegal use of pointers
conversion*/ 4.
p = p/q /* Illegal use of pointer */ Pointers
to Pointers A pointer is a variable. It is a
data. It can hold the address of a variable. With the help of pointer, we can
access the data at the address. Similarly, we can also have pointers to
pointers just as we have pointers to integers. Pointers to pointers offer
flexibility in handling arrays, passing the pointer variable to functions,
etc. The general format of pointing to
pointer could be: <data_type> **
<ptr_to_ptr>; Here, data_type is the type of pointer
data **indicates pointer to pointer Ptr_to_ptr is the variable name of
the pointer to pointer Pointers
and Arrays When we declare an array, the array
elements are stored in continuous locations. So, when the pointer is
increased, it always points to next location of similar data type. # Write a program to find the
address of given value in the program.
Above program holds a set of array
integers. They are placed at different locations in the memory. The pointer
*p is used to point the location and %u (unsigned format specifier) is used
to access the pointer location. Note that ampersand sign & is used before
the pointer variable to find the address. Facts regarding
the relation between pointers and arrays are: 1.
Array elements are always stored in
contiguous memory locations irrespective of the size of the array. 2.
The size of the data type which the pointer
variable refers to is dependent on the data type pointed by the pointer. 3.
A pointer when incremented, always points
to a location after skipping the number of bytes required for the data type
pointed to by it. Passing
Arrays to Functions At the time of manipulating arrays
with the help of a function, entire array elements are necessarily passed in
the function instead of passing one element at a time. This can be achieved
by pointing the base address of the array with the array name. # Write a program to demonstrate
that the arrays are passed to the functions.
The function sortit actually sorts
the original array itself directly. Since the address of the array is passed
as an argument to it. No temporary array is created in this case. This type
of function is called cal by reference. Write a program to find the smallest
number explicitly defined in the array.
Pointer
and Array The pointers can be used to locate
the elements in an array. While accessing the elements of an array, we
consider the following points. 1.
Array elements are always stored in
contiguous memory locations irrespective of their sizes. 2.
The size of the data type which the pointer
variable refers to is dependent on the data type pointed to by the pointer. 3.
A pointer which is incremented always
points to a location after skipping the number of bytes required for the data
type pointed to by it. Example:
Array of
Pointers An array of pointers is similar to
an array of any predefined data type. Since pointer variable always contains
an address; an array of pointers is a collection of addresses. These can be
addresses of ordinary isolated variables or array elements. The elements of
an array of pointers are stored in the memory just as the elements of any
other kind of array. Example:
Pointers
and Strings As in integer array, in character
array also we get the base address of a string by mentioning character
variable to pointer variable. To get other elements of an array, we can
increase the value of a pointer. When a pointer is increased, it points to
the immediate location of its type, till null character (‘\0’) is not
reached. # Write a program to find the
greatest number in an array using pointer variable with a function.
Pointers A pointer is a variable that represents the
location or address of a variable or array element. Uses 1. They are used to pass information back and
forth between a function and calling point. 2. They provide a way to return multiple date
items. 3. They provide alternate way to access
individual array elements. When we declare a variable say x, the computer
reserves a memory cell with name x. the data stored in the variable is got
through the name x. another way to access data is through the address or
location of the variable. This address of x is determined by the expression
&x, where & is a unary operator (called address operator). Assign
this expression &x to another variable px(i.e. px=&x).this new
variable px is called a pointer to x (since it points to the location of x.
the data stored in x is accessed by the expression *px where * is a unary
operator called the indirection operator. Ex: if x=3 and px=&x then *px=3 Declaration and Initialisation A pointer variable is to be declared initially.
It is done by the syntax. Data type *pointer variable Int *p declares the variable p as pointer
variable pointing to a an integer type data. It is made point to a variable q
by p= &q. In p the address of the variable q is stored. The value stored in q is got by *p. If y is a pointer variable to x which is of
type int, we declare y as int *y ; Ex: float a; float *b; b=&a; Note : here in ‘b’ address of ‘a’ is stored and
in ‘*b’ the value of a is stored. Passing pointers to a function Pointers are also passed to function like
variables and arrays are done. Pointers are normally used for passing
arguments by reference (unlike in the case if variable and arrays, they are
passed by values). When data are passed by values the alteration made to the
data item with in the function are not carried over to the calling point;
however when data are passed by reference the case is otherwise. Here the
address of data item is passed and hence whatever changes occur to this with
in the function, it will be retained through out the execution of the
program. So generally pointers are used in the place of global variables. Ex: ): #include void f(int*px, int *py main() { int x = 1; int y=2; f(&X,&y); printf(“\n %d%d”, x,y); } Void f(int *px, int *py); *px=*px+1; *py=*py+2; return;} Note: 1. here the values of x and y are increased by
1 and 2 respectively. 2. arithmetic operations *, +, -, / etc can be
applied to operator variable also. Passing function to other function A pointer to a function can be passed to
another pointer as an assignment. Here it allows one function to be
transferred as if the function were a variable. Pointer and one dimensional arrays An array name is really a pointer to the first
element in the array i.e. if x is a one dimensional array, the name x is
&x[0] and &x[i] are x + i for i= 1,2,……. So to read array of numbers
we can also use the following statements int x[100],n; for (i=1 ; i<=n; ++i) scanf (‘%d”, x + i ) (in the place of scanf
(“%d”, &x[i] ) ) Note : the values stored in the array are got
by * ( x + i ) in the place x[i]. Dynamic memory allocation Usually when we use an array in c program, its
dimension should be more than enough or may not be sufficient. To avoid this
drawback we allocate the proper ( sufficient) dimensions of an array during
the run time of the program with the help of the library functions called
memory management functions like ‘malloc’, ‘calloc’, ‘realloc’ etc. The
process of allocating memory at run time is known as dynamic memory
allocation. Ex; to assign sufficient memory for x we use the
following statement x= (int *) malloc (n* sizeof (int) ) , for in
the place of initial declaration int x[n] Similarly in the place of float y [100] we use
y = (float *) malloc (m* sizeof (float) ); Example to read n numbers and find their sun main() { int *x, n, i, sum=0; printf(“\n Enter number of numbers”); scanf(“%d”, &n); x=(int *)malloc(n * sizeof(int)); for(i=1;i<=n,++i) { scanf(“%d”, x+i): sum += *(x+i); } Printf(“\nThe sum is %d ”, sum); } Structures and Unions We know an array is used to store a collection
of data of the same type. But if we want to deal with a collection of data of
various type such as integer, string, float etc we use structures in C
language. It is a method of packing data of different types. It is a
convenient tool for handling logically related data items of bio-data people
comprising of name, place, date etc. , salary details of staff comprising of
name, pay da, hra etc. Defining a structure. In general it is defined with the syntax name
struct as follows Struct structure_name { Data type variable1; Data type variable2; … } For example : 1. Struct
account { int account no. char name[50]; float balance; }customer[20] Note :1 here account no., name and balance are
called members of the structure 2. struct
date { int month; int day; int year; }dateofbirth; In these examples customer is a structure array
of type account and dateofbirth is a structural type of date. Within a
structure members can be structures. In the following example of biodata
structure date which is a structure is a member. For example struct date { int day; int month; int year; } Struct biodata { name char[30]; int age ; date birthdate; }staff[30]; Here staff is an array of structure of type
biodata Note: we can declare other variables also of
biodata type structure as follows. Struct biodata customer[20]; , Struct biodata
student; etc Processing a structure The members of a structure are themselves not
variable. They should be linked to the structure variable to make them
meaningful members. The linking is done by period (.) If staff[] is structure array then the details
of first staff say staff[1] is got by staff[1].name, staff[1].age,
staff[1].birthdate.day, staff[1].birthdate.month, staff[1].birthdate.year . we can assign name,
age and birthdate of staff[1] by Staff[1].name=”Jayachandran” staff[1].age=26 staff[1].birthdate.day=11 staff[1].birthdate.month=6 staff[1].birthdate.year=1980 If ‘employee’ is a structure variable of type
biodata as mentioned above then the details of ‘employee’ is got by declaring
‘employee as biodata type by the statement biodata employee; The details of employee are got by
employee.name, employee.age, employee.birthdate.year etc. Structure initialisation Like any other variable or array a structure
variable can also be initalised.by using syntax static Struct record { char name[30]; int age; int weight; } Static struct record student1={“rajan”, 18, 62} Here student1 is of record structure and the
name,age and weight are initialised as “rajan”, 18 and 62 respectively. 1.Write a c program to read biodata of students
showing name, place, pin, phone and grade Solution #include main() { Struct biodata { Char name[30]; Char Place[40]; Int pin; Long Int phone; Char grade; }; Struct biodata student[50]; Int n; Prinf(“\n no of students”); Scanf(“%d”,n); For(i=1;i<=n;++i) { Scanf(“%s”,student[i].name); Scanf(“%s”,student[i].place); Scanf(“%d”,student[i].pin); Scanf(“%ld”,student[i].phone); Scanf(“%c”,student[i].grade); } } User Defiined Data Type This is to define new data type equivalent to
existing data types. Once defined a user-defined data type then new variables
can be declared in terms of this new data type. For defining new data type we
use the syntax typedef as flollows typedef type new-type. Here type refers to existing data type For example Ex1: Typedef int integer; Now integer is a new type and using this type
variable, array etc can be defined as Integer x; Integer mark[100]; Ex2: Typedef struct { Int accno; Char name[30]; Float balance; }record; Now record is structure type using this type
declare customer, staff as record type Record customer; Record staff[100]; Passing structures to functions Mainly there are two methods by which
structures can be transferred to and from a function. 1 Transfer structure members individually 2 Passing structures as pointers (ie by
reference) Example 1 #include Typedef struct { Int accno; Char name[30]; Float balance; }record; Main() { ….. Record customer; . . . . . Customer.balance=adjust(customer.name,customer.accno,balance) . . . . . } Float adjust(char name[], int accnumber, float
bal) { Float x; . . . . . X= . . . . . Return(x); } Example 2 #include Typedef struct { Int accno; Char name[30]; Float balance; }record; Main() { Record customer; Void adjust(record *cust) . . . . . . Adjust(&customer); Printf(“\n
%s\t%f”,coustomer.name,customer.balance) } Void adjust(record *cust) { Float x; . . . . Cust->balance=… . . . . Return; } In the first example structure members are
passed individually where as in the second case customer is passed entirely
as a pointer named cust. The values of structure members are accessed by
using -> symbol like cust->.name, cust->balance etc. Unions Union is a concept similar to a structure with
the major difference in terms of storage. In the case of structures each
member has its own storage location, but a union may contain many members of
different types but can handle only one at a time. Union is also defined as a
structure is done but using the syntax union. Union var { Int m; Char c; Float a; } Union var x; Now x is a union containing three members
m,c,a. But only one value can be stored either in x.m, x.corx.a FILE HANDLING (Data
Files) Data Files are to store data on the memory
device permanently and to access whenever is required. There are two types of
data files 1 Stream Oriented data files 2 System Oriented data files Stream oriented data files are either text
files or unformatted files. System oriented data files are more closely
related to computer’s operating system and more complicated to work with. In
this session we go through stream oriented data files. Opening and Closing data files The first step is to create a buffer area where
information is stored temporarily before passing to computer memory. It is
done by writing File *fp; Here fp is the pointer variable to indicate the
beginning of the buffer area and called stream pointer . The next step is to
open a data file specifying the type i.e. read only file , write only file ,
read /write file. This is done by using the library function fopen The syntax is fp=fopen(filename,filetype) the filetype can be 1.‘r’ ( to open an existing file for reading
only) 2.‘w’ ( to open a new file for writing only. If
file with filename exists, it will be destroyed and a new file is created in
its place) 3.‘a’ ( to open an existing file for appending.
If the file name does not exist a new file with that file name will be
created) 4.‘r+’ ( to open an existing file for both
reading and writing) 5.‘w+’ ( to open a new file for reading and
writing. If the file exists with that name, it will be destroyed and a new
one will be created with that name) 6.6 ‘a+’ ( to open an existing file for reading
and writing. If the file does not exist a new file will be created). For writing formatted data to a file we use the
function fprintf. The syntax is Fprintf(fp,”conversion string”, value); For example to write the name “rajan” to the
file named ‘st.dat’ File *fp; Fp=fopen(“st.dat”,’w’); Fprintf(fp,”%[^\n]”,”rajan”); The last step is to close the file after the
desired manipulation. This is done by the library function fclose. The syntax
is fclose(fp); Example 1 To create a file of biodata of students with
name ‘st.dat’. #include #include Tpedef struct { Int day; Int month; Int year; }date; Typedef Struct { char name(30); char place(30); int age; date birthdate; }biodata; Main() { File *fp; biodata student; fp=fopen(“st.dat”,’w’); Printf(“Input data”); Scanf(“%[^\n]”,student.name); Scanf(“%[^\n]”,student.place); Scanf(“%d”,&student.age); Scanf(“%d”,&student.birthdate.day); Scanf(“%d”,&student.birthdate.month); Scanf(“%d”,&student.birthdate.year); Fprintf(fp,”%s%s%d%d%d%d”,student.name,student.place,student.age,student.birthdate.day,
student.birthdate.month, student.birthdate.year) Fclose(fp); } Example 2: To write a set of numbers to a file. #include main() { file *fp; Int n; float x fp=fopen(“num.dat”,’w’); Printf(“Input the number of numbers”); Scanf(“%d”,&n); For(i=1;i<=n;++i) { Scanf(“%d”,&x); Fprintf(fp,”%f\n”,x); } Fclose(fp); } Processing formatted data File To read formatted data from a file we have to
follow all the various steps that discussed above. The file should be opened
with read mode. To open the existing file ‘st.dat’ write the following syntax file *fp; fp=fopen(“st.dat”, ‘r+’); For reading formatted data from a file we use
the function fscanf Example: Tpedef struct { Int day; Int month; Int year; }date; Typedef Struct { char name(30); char place(30); int age; date birthdate; }biodata; Main() { File *fp; biodata student; fp=fopen(“st.dat”,’r+’); fscanf(fp,”%s”,student.name); printf(“%s”,student.name); fclose(fp); } Processing Unformatted data files For reading and writing unformatted data to
files we use the library functions fread and fwrite in the place of fscanf
and fprintf. The syntax for writing data to file ‘st.dat’
with stream pointer fp is Fwrite(&student, sizeof(record),1,fp); Here student is the structure of type biodata Example: To write biodata to a file Tpedef struct { Int day; Int month; Int year; }date; Typedef Struct { char name(30); char place(30); int age; date birthdate; }biodata; Main() { File *fp; fp=fopen(“st.dat”,’a+’); biodata student; Printf(“Input data”); Scanf(“%[^\n]”,student.name); Scanf(“%[^\n]”,student.place); Scanf(“%d”,&student.age); Scanf(“%d”,&student.birthdate.day); Scanf(“%d”,&student.birthdate.month): Scanf(“%d”,&student.birthdate.year); Fwrite(&student,sizeof(record),1,fp); Fclose(fp); } Example 2: To read biodata from the file. Tpedef struct { Int day; Int month; Int year; }date; Typedef Struct { char name(30); char place(30); int age; date birthdate; }biodata; Main() { File *fp; fp=fopen(“st.dat”,’a+’) biodata student; fread(&student,sizeof(record),1,fp); printf(“%s\n”,student.name); printf(“%s\n]”,student.place); printf(“%d\n”,&student.age); printf(“%d\n”,&student.birthdate.day); printf(“%d\n”,&student.birthdate.month): printf(“%d\n”,&student.birthdate.year); fclose(fp); } Some problems and solutions of C: 1.WAP to input an integer and check whether
number is above 50 or not. [ Using if loop statement] Ans: #include #include void main() { int a; printf(“Enter a value for a: ”); scanf(“%d”,&a); if(a>=51) { printf(“%d is greater than 50”,a); } else { printf(“%d is less than or equal to 50”,a); } getch() } 2.WAP for finding factorial of a given number
using while statement. Ans: #include #include void main() { clrscr(); int number; long int factorial=1; printf(“\nEnter the number:”); scanf(“%d,&number); while (number>1) { factorial=factorial * number –; printf(“\nThe factorial is %d”, factorial); } getch(); } Output: Enter the number =4 The factorial is 24 3.WAP in C to input any five number in an
array, find the average and if the average is greater than 50 print good
otherwise print bad. Ans: #include #include void main() { clrscr(); int a[5],ar,s=0,i,j; printf(“Enter any five number”); for (i=0;i50) { printf(“Good”); else printf(“Bad”); } Output: Enter any five numbers 1 4 10 15 25 Bad Discussion: In this program first five numbers is asked to
the user. Which was kept is an array. Since the sum is to be done repeatedly
so the sum is also kept inside loop body where first the entered number is
scaned and added to the sum. Finally, the sum is divided by five to find out
the average of the entered number. If the average is greater than ‘50’ it
display “Good” otherwise it display “Bad”. 4.WAP in C to accept a string and check if the
string is palindrome or not. Ans: #include #include #include void main() { clrscr(); char a[20],b[20]; puts(“Enter a string”); gets(a); strcpy(b,a); strrev(a); if (strcmp(a,b)=0) printf(“The entered string is palindrome”); else printf(“The entered string is not palindrome”); getch(); } Output: Enter a string pen The entered string is not palindrome. Enter a string: dad The entered string is palindrome. |