You are on page 1of 48

Programming in C (AIT 112)

UNIT-I
Introduction to Flowcharts and Algorithms, need of Computer languages and types of computer languages.

ALGORITHM A set of ordered steps for solving a problem, such as a mathematical


formula or the instructions in a program or a sequence of ordered steps to solve a problem.

EXAMPLE 1:

Step 1: Start
Step 2: Print Welcome to AIT, AAU
Step 3: Stop

EXAMPLE 2:

Step 1: Start
Step 2: INPUT A, B
Step 3: C=A+B
Step 4: Write C
Step 3: Stop

FLOWCHART A diagram of the sequence of operations in a computer program


These flowcharts can apply to your processes. Every organizations process can be flowcharted.
Flowcharts are a visual presentation of your process steps. A flowchart is a step by step picture of
your process.
Use flowcharts to
Visualize your processes
Show step by step details of your current process
Overview detail procedures
Study processes
Provide common reference talking points during a meeting
Illustrate a desired flow of a new improved system.
Easily identify non value added steps.
Quickly train your employees
Example:
Start

Read A, B

Sum = A + B

Write Sum

Stop

Prof M. P. Raj (B. Tech - AIT) Page: 1/48


Programming in C (AIT 112)

SYMBOLS OF FLOWCHART

Need of Computer languages


Human Language is commonly used to express feeing and understand other person expression. It
can be oral or gestural kind of communication.
Natural languages such as English, are ambiguous, fuzzily structured and have large (and
changing) vocabularies. Computers have no common sense, so computer languages must be
very precise - they have relatively few, exactly defined, rules for composition of programs, and
strictly controlled vocabularies in which unknown words must be defined before they can be used.

Computer languages are the languages by which a user commands a computer to work on the
algorithm which a user has written to get an output.
OR
A computer language is a set of predefined words that are combined into a program according to
predefined rules (syntax). Over the years, computer languages have evolved from machine
language to high-level languages.

TYPES OF COMPUTER LANGUAGES


Two types of computer language are
Low-level languages
High-level languages
Prof M. P. Raj (B. Tech - AIT) Page: 2/48
Programming in C (AIT 112)

A low-level programming language is a programming language that provides little or no


abstraction from a computer's instruction set architecture. It consists of numeric codes i.e 0 & 1.
These codes are easily understandable to computer but difficult to human.. A lower level
language is used in two generations of computer.
First generation or 1GL
Represent the very early, primitive computer languages that consisted entirely of
1's and 0's - the actual language that the computer understands (machine
language).

Second generation or 2GL


Allow for the use of symbolic names instead of just numbers. Second generation
languages are known as assembly languages. Code written in an assembly
language is converted into machine language (1GL).

CHARACTERSTICS OF LOW LEVEL LANGUAGES


Direct memory management
Little-to-no abstraction from the hardware
Register access
Statements usually have an obvious correspondence with clock cycles
Superb performance
Advantages
Computational Speed is very fast.
Directly understandable by computer.
Disadvantages
Development of a program in machine language is very time consuming.
Error correction is tedious process.

HIGH LEVEL LANGUAGES


High-level programming languages allow the specification of a problem solution in terms
closer to those used by human beings. These languages were designed to make
programming far easier, less error-prone and to remove the programmer from having to
know the details of the internal structure of a particular computer.
Third generation languages (3GL)
With the languages introduced by the third generation of computer programming,
words and commands (instead of just symbols and numbers) were being used.
These languages therefore, had syntax that was much easier to understand. Third
generation languages are known as "high level languages" and include C, C++,
Java, and JavaScript, among others.
Prof M. P. Raj (B. Tech - AIT) Page: 3/48
Programming in C (AIT 112)

UNIT-II
C character set, Identifiers and keywords, Data types, Declarations, Expressions, statements and symbolic constants,
Operators.

HISTORY OF C
C was originally developed in the 1970's by Dennis Ritchie at Bell Telephone Laboratories,
Inc. (now AT&T Bell Laboratories). It is an outgrowth of two earlier languages, called BCPL and B,
which were also developed at Bell Laboratories. C was largely confined to use within Bell
Laboratories until 1978, when Brian Kernighan and Ritchie published a definitive description of
the language.* The Kernighan and Ritchie description is commonly referred to as "K&R c."

STRUCTURE OF A C PROGRAM
Every C program consists of one or more functions, one of which must be called main. The
program will always begin by executing the main function. Additional function definitions may
precede or follow main

Each function must contain:


1. A function heading, which consists of the function name, followed by an optional list of
arguments enclosed in parentheses.
2. A list of argument declaration, if arguments are included in the heading.
3. A compound statement, which comprises the remainder of the function.

The-arguments are symbols that represent information being passed between the function
and other parts of the program. (Arguments are also referred to as parameters.)
Each compound statement is enclosed within a pair of braces, i.e., { and}. The braces
may contain combinations of elementary statements (called expression statements) and other
compound statements. Thus, compound statements may be nested, one within another. Each
expression statement must end with a semicolon (;).
Comments (remarks) may appear anywhere within a program, as long as they are placed
within the delimiters / * and */ (e.g., / * this is a comment */). Such comments are helpful in
identifying the program's principal features or in explaining the underlying logic of various
program features.

Basic Structure Of C Program


Documentation Section Set of comment lines that describes program.
Link Section Provides instructions to the compiler to link functions from the
system library.
Definition Section Define all symbolic constants
Global Declaration Section Variables used in more than one function are declared
here.
main() Function Section
{
/* Declaration part */

}
/* Executable part */
}
Subprogarm section
Function1()
{
} User Defined functions
Function2()
{}
..
Functionn()

Prof M. P. Raj (B. Tech - AIT) Page: 4/48


Programming in C (AIT 112)

Example: Area of a Circle Here is an elementary C program that reads in the radius of a circle,
calculates the area and then writes the calculated result.
*include <stdio.h> /* LIBRARY FILE ACCESS */
/* program to calculate area of a circle */ /* TITLE (COMMENT) */
main() /* FUNCTION HEADING */
{
float radius, area; /* VARIABLE DECLARATIONS */
printf("Radius = ? "); /* OUTPUT STATEMENT (PROMPT) */
scanf( "%f", &radius); /* INPUT STATEMENT */
area = 3.14159 * radius * radius; /* ASSIGNMENT STATEMENT */
printf("Area = ::'.f", area); /* OUTPUT STATEMENT */
}
The comments at the end of each line have been added in order to emphasize the overall
program organization.

The following features should be pointed out in this last program.


1. The program is typed in lowercase. Either upper- or lowercase can be used, though it is
customary to type ordinary instructions in lowercase. Most comments are also typed in
lowercase, though comments are sometimes typed in uppercase for emphasis, or to
distinguish certain comments from the instructions. (Uppercase and lowercase characters
are not equivalent in C. Later in this book we will see some special situations where
certain symbols are characteristically typed in uppercase.)
2. The first line contains a reference to a special file (called stdio.h) which contains
information that must be included in the program when it is compiled. The inclusion of this
required information will be handled automatically by the compiler.
3. The second line is a comment that identifies the purpose of the program.
4. The third line is a heading for the function main. The empty parentheses following the
name of the function indicate that this function does not include any arguments.
5. The remaining five lines of the program are indented and enclosed within a pair of braces.
These five lines comprise the compound statement within main.
6. The first indented line is a variable declaration. It establishes the symbolic names radius
and area as floating point variables (more about this in Chap. 2).
7. The remaining four indented lines are expression statements. The second indented line
(printf) generates a request for information (namely, a value for the radius). This value is
entered into the computer via the third indented line (scanf).
8. The fourth indented line is a particular type of expression statement called an assignment
statement. This statement causes the area to be calculated from the given value of the
radius. Within this statement the asterisks (*) represent multiplication signs. .
9. The last indented line (printf) causes the calculated value for the area to be displayed. The
numerical value will be preceded by a brief label.
10. Notice that each expression statement within the compound statement ends with a
semicolon. This is required of all expression statements.
11. Finally, notice the liberal use of spacing and indentation, creating whitespace within the
program. The blank lines separate different parts of the program into logically identifiable
components, and the indentation indicates subordinate relationships among the various
instructions. These features are not grammatically essential, but their presence is strongly
encouraged as a matter of good programming practice.

Execution of the program results in an interactive dialog such as that shown below. The user's
response is underlined, for clarity.
Radius = ? 3
Area = 28.274309

Prof M. P. Raj (B. Tech - AIT) Page: 5/48


Programming in C (AIT 112)

FEATURES OF C
English like high level language Simple & easy
Rich set of built-in functions and operators helps users to write complex programs Robust
language.
Combined features of low-level and high-level language allow users to develop both system
and customized software Flexible and used to develop any kind of software.
Large set of data types and operators, compiler based Efficient and fast.
Software developed using it can be executed on any computer without none or little
modification highly portable.
Supports may program structure and statements and above all it supports modular or block
programming Structured Programming language.

THE C COMPILATION MODEL


Source code C program written by user

Preprocessor The Preprocessor accepts source code as input and is responsible for removing
comments interpreting special preprocessor directives denoted by #.

For example
#include -- includes contents of a named file. Files usually called header files. e.g
#include <math.h> -- standard library maths file.
#include <stdio.h> -- standard library I/O file
#define -- defines a symbolic name or constant. Macro substitution.
#define MAX_ARRAY_SIZE 100

C Compiler C compiler translates source to assembly code. The source code is received from
the preprocessor.

Assembler The assembler creates object code. On a Windows OS you may see files with a
.OBJ on MSDOS to indicate object code files and in Unix system with .o suffix

Link Editor If a source file references library functions or functions defined in other source
files the link editor combines these functions (with main()) to create an executable file. External
Variable references resolved here also.

Prof M. P. Raj (B. Tech - AIT) Page: 6/48


Programming in C (AIT 112)

C CHARACTER SET

Alphabets:
A, B, C, .., X, Y, Z
a, b, c, .., x, y, z

Digits:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9

Special Symbols:
~!@#$%^&*()_-+=|\{[}]<>,.?/;:

C uses certain combination of these characters such as \b, \t, \n to represent special characters
such as backspace, tab and newline, respectively. These character combination are known as
escape sequences.

Escape Sequences
Certain nonprinting characters, as well as the double quote ("), the apostrophe ('), the question
mark (?) and the backslash (\), can be expressed in terms of escape sequences. An escape
sequence always begins with a backward slash and is followed by one or more special characters.
For example, a line feed (LF), which is referred to as a newline in C, can be represented as \n.
Such escape sequences always represent single characters, even though they are written in terms
of two or more characters.

Escape Sequence Purpose ASCII Value

\n New Line 010


\b Backspace 008
\f Form feed 012
\ Single quote 039
\\ Backslash 092
\t Horizontal Tab 009
\r Carriage return 013
\a Alert 007
\ Double quote 034
\v Vertical tab 011
\? Question mark 063
\0 Null 000

IDENTIFIER AND KEYWORDS


Identifiers are names given to various program elements, such as variables, functions and
arrays. Identifiers consist of letters and digits, in any order, except that the first character must
be a letter. Both upper and lower case letters are permitted, though common usage favors the
use of lowercase letters for most type of identifiers. As C language is case sensitive upper and
lowercase letters are not interchangeable.
The underscore character _ can also be included, and is considered to be a letter. An
underscore is often used in the middle of an identifier. An identifier may also begin with an
underscore, though this is rarely done in practice.

Valid examples of identifiers are as below:


X y12 sum_1 sum1 _temp tax_rate area_circle

Invalid examples of identifier are as below:


Prof M. P. Raj (B. Tech - AIT) Page: 7/48
Programming in C (AIT 112)

4-th first character must be letter


x illegal character ()
First-name illegal character (-)
Error flag blank space is not allowed in identifier

NAMING RULES FOR IDENTIFIER


It is any combination of 1 to 31 alphabets, digits or underscores. Some compilers allow up to
247 characters.
First character must be alphabet or underscore.
No commas or blanks are allowed within a variable name.
No special symbol other than an underscore _can be used in a variable name for e.g.
student_name.
As C is case sensitive, so student_name & Student_name are different identifiers
Keywords can not be used as identifiers but as C is case sensitive keywords it is possible to
use an uppercase keyword as identifier but it is considered a poor programming practice.

KEYWORDS
There are certain reserved words, called keywords, that have standard, predefined
meaning in C. These keywords can be used only for their intended purpose; they cannot be
used as programmer-defined identifiers.

auto double int struct


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

DATA TYPES
C supports several different data types of data, each of which may be represented
differently within the computers memory. A C language programmer has to tell the system
before-hand, the type of numbers or characters he is using in his program. These are data types.
There are many data types in C language. A C programmer has to use appropriate data type as
per his requirement.

Each identifier that represents a number or a character within a C program must be


associated with one of the basic data types before the identifier appears in an executable
statement. This is accomplished via a type declaration.

The basic data types are int, char, float, double and void. Basic data types can be
augmented by using the data type qualifiers/modifier short, long, signed and unsigned.
Typical memory requirements are given below.

Size and Range of Data Types on 16 bit machine

Prof M. P. Raj (B. Tech - AIT) Page: 8/48


Programming in C (AIT 112)

CONSTANTS VALUES
C has four basic types of constant values and thus they are classified as integer constants,
floating-point constants, character constants and string constants (there are also enumeration
constants). Integer and floating-point constants represent numbers. They are often referred to
collectively as numeric-type constants. The following rules apply to all numeric-type constants.
1. Commas and blank spaces cannot be included within the constant.
2. The constant can be preceded by a minus ( - ) sign if desired. (Actually, the minus sign is an
operator that changes the sign of a positive constant, though it can be thought of as a part of the
constant itself.)
3. The value of a constant cannot exceed specified minimum and maximum bounds. For each
type of constant, these bounds will vary from one C compiler to another.

Integer Constants
An integer constant is an integer-valued number. Thus it consists of a sequence of digits.
Integer constants can be written in three different number systems: decimal (base 10), octal
(base 8) and hexadecimal (base 16).

Octal integer constant can consist of any combination of digits taken from the set 0
through 7. The first digit must be 0 to identify the constant as an octal number
For e.g.
0 01 0456
Decimal integer constant can consist of any combination of digits taken from the set 0
through 9. If the constant contains two or more digits, the first digit must be something
other than 0.
For e.g.
0 1 234 32767
Hexadecimal integer constant must begin with either 0x or 0X. It can be followed by
any combination of digits taken from the sets 0 through 9 and a through f (either upper or
lowercase). The letters a through f (or A through F) represents the (decimal) quantities 10
through 15.
For e.g.
0 0x23 0X23ab 0x56FF
Unsigned and Long integer constants
An unsigned integer constant can be identified by appending the letter U (either
upper or lowercase) to the end of the constant.
For e.g.
50000U 456u
An long integer constant can be identified by appending the letter L (either upper
or lowercase) to the end of the constant.
For e.g.
123456789L 456789l

Prof M. P. Raj (B. Tech - AIT) Page: 9/48


Programming in C (AIT 112)

An unsigned long integer constant can be identified by appending the letter UL


(either upper or lowercase) to the end of the constant
For e.g.
0XFFFFFUL 0777777UL
Floating-Point Constant
A floating-point constant is a base-10 number that contains either a decimal point or an
exponent (or both)
For e.g.
12.3 0.456 0.005E-6 .121212121 1.

Characters Constant
A character constant is a single character, enclosed in apostrophes (single quotation
marks)
For e.g.
A x 2 &

Character constants have integer values that are determined by the computers particular
character set.

String Constants
A string constant consists of any number of consecutive characters (including none)
enclosed in (double) quotation marks.
For e.g.
hello Hello, \nHow are you? 1245487-656 2*(I+3)/J

Prof M. P. Raj (B. Tech - AIT) Page: 10/48


Programming in C (AIT 112)

The compiler automatically places a null character \0 at the end of every string constant, at the
last character within the string (before the closing double quotation mark). This character is not
visible when the string is displayed. However, null character can be easily checked within string.
Thus, the end of every string can be identified.
Character constant A and string constant A are different. Character constant has an equivalent
integer value, whereas a single character string constant doesnt have a equivalent integer value
because in string constant there are minimum two character that is A\0.

VARIABLES
A variable is an identifier that is used to represent some specified type of information
within a designated portion of the program. A variable represents a single data item that is a
numerical quantity or a character constant. The data item must be assigned to the variable at
some point in the program. The data item can then be accessed later in the program simply by
referring to the variable name.
A given variable can be assigned different data items at various places within the program.
Thus the information represented by the variable can change during the execution of the
program, but data type associated with the variable cannot be changed.
In short, variable is an entity which stores different values of same type during program
execution.

Declaration A declaration associates a group of variables with a specific data type. All
variables must be declared before they are assigned values or used in any other executable
statements.
A declaration consists of data type followed by one or more variable names, ending with a
semi-colon. Duplicate variable declaration is not allowed in any programming language.
For e.g.
int marks, total=0;
float average, percentage, area=0;
char flag, gender=M;
short int a, b, c=0;
long int x, y, z;
double i;
long float factor= 0.323E-6;
unsigned int d, e;

Storage Class And Scope/Visibility Of Variables


Variables in C have not only the data type but also storage class that provides information
about their location and visibility. The storage class divides the portion of the program within
which the variables are recognized.
auto : It is a local variable known only to the function in which it is declared. Auto is the default
storage class.
static : Local variable which exists and retains its value even after the control is transferred to
the calling function.
extern : Global variable known to all functions in the file
register : Social variables which are stored in the register. This variables are accessed very fast
compared all other variables.

Scope Of Variables means in which part of program value of variable will be accessible.
Local: Available only to certain selected statements in the program. It is defined inside a function

Global: It is accessible to all the statements in the function. It is declared outside the function.

Volatile Variable
A volatile variable is the one whose values may be changed at any time by some external
sources.

Example:
volatile int num;

Prof M. P. Raj (B. Tech - AIT) Page: 11/48


Programming in C (AIT 112)

The value of data may be altered by some external factor, even if it does not appear on the left
hand side of the assignment statement. When we declare a variable as volatile the compiler will
examine the value of the variable each time it is encountered to see if an external factor has
changed the value.

CONSTANTS
In C constants are of two types first is symbolic constant or compiler constants and second is
runtime constant. Constants are classified on the basis of when value of constant will be replaced
in an expression.

SYMBOLIC CONSTANTS
Symbolic constant value can be defined as a preprocessor statement and used in the program as
any other constant value. The general form of a symbolic constant is

# define symbolic_name value of constant

Valid examples of constant definitions are:

# define marks 100


# define total 50
# define pi 3.14159

These values may appear anywhere in the program, but must come before it is referenced in the
program. It is a standard practice to place them at the beginning of the program

Second way of declaring constant using const keyword is as below


The values of some variable may be required to remain constant through-out the program.
We can do this by using the qualifier const at the time of initialization.

Example: const int class_size = 30;

The const data type qualifier tells the compiler that the value of the int variableclass_size
may not be modified in the program.

USER DEFINED TYPE DECLARATION


In C language a user can define an identifier that represents an existing data type. The user
defined data type identifier can later be used to declare variables. The general syntax is

typedef type identifier;

here type represents existing data type and identifier refers to the row name given to the data
type.

Example: typedef int Units;


typedef float average;

Here Units symbolizes int and average symbolizes float. They can be later used to declare
variables as follows:

Units dept1, dept2;


Average section1, section2;

Therefore dept1 and dept2 are indirectly declared as integer data type and section1 and section2
are indirectly float data type.

The second type of user defined data type is enumerated data type which is defined as follows.

enum identifier {value1, value2 . Value n};

Prof M. P. Raj (B. Tech - AIT) Page: 12/48


Programming in C (AIT 112)

The identifier is a user defined enumerated datatype which can be used to declare variables that
have one of the values enclosed within the braces. After the definition we can declare variables to
be of this new type as below.

enum identifier V1, V2, V3, Vn

The enumerated variables V1, V2, .. Vn can have only one of the values value1, value2 ..
value n

Example:

enum day {Monday, Tuesday, . Sunday};


enum day week_st, week end;
week_st = Monday;
week_end = Friday;
if(wk_st == Tuesday)
week_en = Saturday;

EXPRESSION
An expression represents a single data item, such as number or a character. The
expression may consist of a single entity, such as a constant, a variable, an array element or a
reference to a function. It may also consist of some combination of such entities interconnected
by one or more operators. Expression can also represent logical conditions that are either true or
false. However, in C the conditions true and false are represented by the integer values 1 and 0
respectively. Thus logical-type expression really represents numerical quantities.
For e.g.
a+b
x=y
c=a+b
x<=y
x == Y
i++
(float) x
&a

OPERANDS & OPERATORS


An entity or variables used on either side of operator is called Operand.
Operators are classified on the basis of number of operands required.
1. Unary
2. Binary
3. Ternary

OPERATORS (common rule BODMAS)


Desctiption Opreator Associativity

( ) , [ ], , . Left to Right

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

Arithmetic /, *, %, +, - Left to Right

Shift <<, >> Left to Right

Relational or <, <=, >, >= Left to Right


comparison

Equality ==, != Left to Right

Bitwise &, ^, |, Left to Right

Logical &&, || Left to Right

Prof M. P. Raj (B. Tech - AIT) Page: 13/48


Programming in C (AIT 112)

Conditional ?: Right to Left

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

Comma , Right to Left

TYPE CASTING
Converting one data type to another is called as casting. For sometimes certain variables
declared as float might be required as int for some expressions. For that purpose the cast is used.
General form
(data type) expression
Eg:
Let a, b are float variables and c integer variable
If we want to use a and b as int in some expression then we can change this as follows
((int)(a+b))+c;
Here a+b is converted to int and then added with c. After the execution of this expression and b
will be returned as float variables.

Prof M. P. Raj (B. Tech - AIT) Page: 14/48


Programming in C (AIT 112)

UNIT III
Basic input/output library functions, control statements, storage types, Defining and accessing, passing
arguments, Function prototypes, Recursion, Library functions.

CONSOLE INPUT/OUTPUT FUNCTIONS

FORMATED FUNCTIONS
TYPE INPUT OUTPUT

char scanf() printf()

int scanf() printf()


float scanf() printf()
String scanf() printf()

UNFORMATED FUNCTIONS
TYPE INPUT OUTPUT
char getch(), getche(), getchar() putch(), putchar()
int - -
float - -
String gets() puts()

Input Functions These functions are used to accept input from user. User can input data
using standard input device (keyboard) or any other input device.

Scanf:
Syntax:
int scanf(format String (formatting characters separated by space or
separator), <address of variable separated by comma>);
Purpose:
scanf reads characters from the standard input, interprets them according to the
specification in format, and stores the results through the remaining arguments.
The other argument, indicate where the corresponding converted input should be
stored, so address operator is put before each variable. Address operator is used to
get address of a variable in memory.
scanf stops when it exhausts its format string, or when some input fails to match
the control specification.
Example:
scanf(%d,&a);
scanf(%d %d,&b,&c);
scanf(%d/%d/%d,&dd,&mm,&yy);
scanf(%3d,&a); here 3 is field width which specifies max number of
characters user can input.

getch
syntax:
int getch(void)
purpose:
Reads single character from keyboard without echoing on screen.
Example:
int password;

Prof M. P. Raj (B. Tech - AIT) Page: 15/48


Programming in C (AIT 112)

char b;
password = getch();
getch(); when we use this function data entered by the user from the keyboard
is not displayed on the screen, so it can be used to temporary pause
the screen also.

getche
Syntax:
int getche(void)
purpose:
Reads single character from keyboard, it echoes it with current text window, using
direct video or BIOS.
Example:
int a;
char b;
a = getche();
b = getche();

getchar
Syntax:
int getchar(void)
Purpose:
It is a macro defined as getc(stdin) getchar returns the next character on
the input stream stdin.
Example:
char gender;
int a;
gender = getchar();
a = getchar();

gets
Syntax:
char *gets(char *s)
Purpose:
It collects a stream of characters terminated by a new line character from
the standard input stream stdin and puts it into s.
Example:
char name[30];
gets(name);

Output Functions These functions are used to display result or message on standard input
device.

printf
Syntax:
int printf(formatting string, <list of variables separated by comma>);
Purpose:
printf converts, formats, and prints its arguments on the standard output under
control of the formatting string. It returns the number of characters printed. The
format string contains two types of objects: ordinary characters, which are copied
to the output stream, and conversion specifications, each of which causes
conversion and printing of the next successive argument to printf. Each conversion
specification begins with a % and ends with a conversion character.
Example:
printf(Welcome to c programming);
printf(Welcome to \C\ programming);
printf(Sum of %d and %d is %d, a, b, c);

Prof M. P. Raj (B. Tech - AIT) Page: 16/48


Programming in C (AIT 112)

putch
Syntax:
int putch(int c);
Purpose:
It outputs the character c to the current text window.
Example:
int a= 65,b=3;
putch(a);
putch(b);
putchar
Syntax:
int putchar(int c);
Purpose:
It is a macro defined as putc(c, stdout) putchar puts the character given by c on
output stream stdout.
Example:
int a= 65,b=3;
putchar(a);
putchar(b);

puts
Syntax:
int puts(const char *s)
Purpose:
It copies a null terminated string s to the standard output stream stdout and
appends a newline character.
Example:
char name[] = College of A.I.T;
puts(name);

STATEMENTS
Compound Statements: Any <statement> can be replaced with a compound statement.
Compound statements have the form:
{
<optional-statement-list>
}

and are used as the body of a function or anywhere that a single statement is expected. The
statement-list are the actions to be performed. Brackets define their own scope. In simple words,
when there are more than one statement compound statement is used.

Assignment Statements: The assignment statement has the following form:


variable = expression
Its purpose is saving the result of the expression to the right of the assignment operator to the
variable on the left. Here are some rules:
The expression is evaluated first
If the type of the expression is identical to that of the variable, the result is saved in the
variable. Otherwise, the result is converted to the type of the variable and saved there.
o If the type of the variable is INTEGER while the type of the result is REAL, the
fractional part, including the decimal point, is removed making it an integer result.
o If the type of the variable is REAL while the type of the result is INTEGER, then a
decimal point is appended to the integer making it a real number.
Once the variable receives a new value, the original one disappears and is no more
available.

Prof M. P. Raj (B. Tech - AIT) Page: 17/48


Programming in C (AIT 112)

Control Statements: It determines the flow of control in a program.

Control statements

Conditional control statements Unconditional control statements

1. simple if statement 1. go to statement


2. if else statement 2. continue
3. Nested if statement 3. break
4. Switch case statement

Looping statements
1. for statement
2. while statement
3. do while statement

Conditional Or Branching Statements


1.0. Simple if statement
The if statement allows to control execution of a program based on whether a given
condition is true or false. else part of the if statement is optional that means program should
do nothing if condition is false then else part can be omitted.
If condition is true then set of statements 1 will be executed and after that it will move to
next statement after if statement. If condition in if statement is false and else part is
present then set of statement 2 will be executed and then it will move to next statement after if.
If condition is false and else part is not present and then it will move to next statement after if.
Expression can be any valid expression which returns either o or value greater than o.
0 false
1 true
Syntax:
if(expression)
{
Set of Statement1;
/* if condition is true, set of statements between
this curly brackets is executed*/
}
else
{
Set of Statement2;
/* if condition is false, set of statements between
this curly brackets is executed*/
}
E.g.:
#include<stdio.h>
#include<conio.h>
main()
{
int pos;
clrscr();
printf(Enter a no:);
scanf(%d,&pos);
if (pos>0)
printf(The given no is a positive number);
getch();

Prof M. P. Raj (B. Tech - AIT) Page: 18/48


Programming in C (AIT 112)

1.1. else if
Another use of else is when there are multiple conditional statements that may all
evaluate to true, yet you want only one if statement's body to execute. You can use an "else if"
statement following an if statement and its body; that way, if the first statement is true, the
"else if" will be ignored, but if the if statement is false, it will then check the condition for the
else if statement. If the if statement was true the else statement will not be checked. It is
possible to use numerous else if statements to ensure that only one block of code is executed.
Syntax:
if ( < expression> )
{
// Execute these statements if < expression > is TRUE
}
else
if ( <another expression > )
{
// Execute these statements if <another expression > is TRUE and
// < expression > is FALSE
}
eg:
eg:
#include<stdio.h>
#include<conio.h>
main()
{
int pos;
clrscr();
printf(Enter any no:);
scanf(%d,&pos);
if(pos>0)&&(pos!=0)
printf(The given no is a positive no);
elseif(pos<0)&&(pos!=0)
printf(The given no is a negative no);
else
printf(The given no is a zero);
getch();
}

1.2. Nested if statement


There can be multiple ifelse statement in a program. Also each if and else part can
have another if..else statement. This is called as nested if statement.
syntax:
if (expression 1)
{
Statements1;
if (expression 1.1)
statements 1.1;

}
else
{
Statements 1.2;

if (expression 1.2)
statements 1.2.1;
else
statements 1.2.2;
}
In most of the situation nested if can be replaced by using logical && operation in single if
statement.

Prof M. P. Raj (B. Tech - AIT) Page: 19/48


Programming in C (AIT 112)

For e.g.
if(a>b)
{
If(a>c)
printf(a is greater);
}
Can be replaced by
if((a>b) && (a>c)
printf(a is greater);

2. switch case statement


The switch statement causes control to be transferred to one of several statements depending on
the value of an expression, which must have integral type. The sub-statement controlled by a
switch is typically compound. Any statement within the sub-statement may be labeled with one or
more case labels, which consist of the keyword case followed by a constant expression and then a
colon (:).
It allows us to make a decision from the number of choices. The keyword case is followed
by an integer constant or a character constant. No two of the case constants associated with the
same switch may have the same value.
First, the expression is evaluated and if the value matches any one of the case statement
then the corresponding statement is evaluated. If there is no match then the statements below,
default is evaluated.
Switch statements can "fall through", that is, when one case section has completed its
execution, statements will continue to be executed downward until a break; statement is
encountered.
Syntax:
switch (expression)
{ case <value1> :
set of statements 1;
break;
case <value2> :
set of statements 2;
break;
case <value3> :
case <value4> :
set of statements for 3 and 4;
break;
.
.
case <valuen> :
set of statements n;
break;
default:
set of statements;
}

eg:
#include<stdio.h>
#include<conio.h>
main()
{
char code;
clrscr();
printf(Enter a code[a/m/p]:);
scanf(%c,&code);
switch(code)
{
case a :
printf(Accounts staff);
break;
case m :
Prof M. P. Raj (B. Tech - AIT) Page: 20/48
Programming in C (AIT 112)

printf (Management staff);


break;
case p :
printf (Purchase staff);
break;
default :
printf (Invalid choice ! Try again);
}
getch();
}

Switch versus if..else if


A float expression cannot be tested using switch
Cases can never have variable expression for e.g.
case a + 10 :
here a + 10 is not allowed.
Multiple cases cannot use same expressions.

LOOPING STATEMENTS

1. while loop
Syntax:
while ( expression)
{
statements;
}
Description:
The expression is evaluated. If it is zero, non statement is executed and
expression is reevaluated. This cycle continues until expression becomes zero, at
which point execution resumes after statement.
Example:
#include<stdio.h>
#include<conio.h>
main()
{
int n,i=0;
clrscr();
printf(Enter the range:);
scanf(%d,&n);
while(i<n)
{
printf(i=%d\n,i);
i++;
}
getch();
}

2. do. While loop


Syntax:
do
{
statements;
} while(expression);
Description:
do while statement test the condition after having executed the statements within
the loop. This means it will executes the statements at least once even if the
condition fails for the first time itself.
Example:
#include<stdio.h>
#include<conio.h>
main()
{
Prof M. P. Raj (B. Tech - AIT) Page: 21/48
Programming in C (AIT 112)

int i,n;
clrscr();
printf(Enter the range:);
scanf(%d,&n);
do
{
printf(i=%d\n,i);
i++;
}while(i<n);
getch();
}
3. for loop
Syntax:
for (expression 1 ; expression 2; expression 3)
statements;
where
expression 1 initialization statement
expression 2 condition checking statement
expression 3 increment or decrement operator
Description:
The first expression is executed as a statement first, the second expression is then
tested to see if the body of the loop should be executed. The third expression is
executed at the end of every iteration of the loop. Any of the three expressions in
the for loop can be omitted. Leaving out the first or the third expressions means
that no additional action is performed either before the loop starts or after each
iteration. Omitting the second expression results in a loop that will always execute,
the value of the controlling expression is assumed to be true. If any expression is
omitted, the separating semi-colons must still be included.
Example:
#include<stdio.h>
#include<conio.h>
main()
{
int i,n;
clrscr();
printf(Enter the range:);
scanf(%d,&n);
for(i=0;i<n;i++)
printf(i=%d\n,i);
getch();
}

Unconditional control statements


1. break statement
It is used to terminate from the loop.This statement is used with for, while, do while,
switch case statements.
Example:
#include<stdio.h>
#include<conio.h>
main()
{
int x=1;
clrscr();
while (x<=10)
{
printf(x=%d\n,x);
if(x==5)
break;
x++;
}
getch();
}
Prof M. P. Raj (B. Tech - AIT) Page: 22/48
Programming in C (AIT 112)

2. continue statement
This statement will take the control to the beginning of the loop. It can be included only in
a while, do while, for statement.

3. goto statement
It transfers the control to anywhere in the program. Avoid using this statement.

Some important programs

1. Program for Factorial


#include<stdio.h>
#include<conio.h>
main()
{
int n,i,f=1;
clrscr();
printf("Enter any no:");
scanf("%d",&n);
for(i=1;i<=n;i++)
f=f*i;
printf("Factorial value=%d\n",f);
getch();
}
2. Program to count the number of digits
#include<stdio.h>
#include<conio.h>
main()
{
int n,c=0;
clrscr();
printf("Enter a no:");
scanf("%d",&n);
while(n!=0)
{
n=n/10;
c++;
}
printf("The total no of digits are:%d",c);
getch();
}
3. Program to reverse a given no
#include<stdio.h>
#include<conio.h>
main()
{
int x,rev=0,rem,i;
clrscr();
printf("Enter the value to be reversed:");
scanf("%d",&x);
while(x>0)
{
rem=x%10;
rev=rev*10+rem;
x/=10;
}
printf("The reversed no is %d",rev);
getch();
}

Prof M. P. Raj (B. Tech - AIT) Page: 23/48


Programming in C (AIT 112)

4. Program to check the given no is prime or not


#include<stdio.h>
#include<conio.h>
main()
{
int n,i;
clrscr();
printf("Enter the no:");
scanf("%d",&n);
for(i=2;i<n;i++)
{
if(n%i!=0)
continue;
else
break;
}
if(i==n)
printf("The given no is a prime number");
else
printf("The given number is not a prime number");
getch();
}
5. Program to generate Fibonacci series
#include<stdio.h>
#include<conio.h>
main()
{
int a=0,b=1,c,i,n;
clrscr();
printf("Enter the range:");
scanf("%d",&n);
printf("%d\t",a);
printf("%d\t",b);
for(i=3;i<n;i++)
{
c=a+b;
a=b;
b=c;
printf("%d\t",c);
}
getch();
}
6. Program to find the sum of n natural numbers
#include<stdio.h>
#include<conio.h>
main()
{
int i,n,sum=0;
clrscr();
printf("Enter the range:");
scanf("%d",&n);
for(i=1;i<=n;i++)
sum=sum+i;
printf("Sum of %d natural numbers are %d",n,sum);
getch();
}

7. Program to find the sum of digits


#include<stdio.h>
#include<conio.h>
main()
{
int n,sum=0,a;
Prof M. P. Raj (B. Tech - AIT) Page: 24/48
Programming in C (AIT 112)

clrscr();
printf("Enter the value to sum:");
scanf("%d",&n);
while(n>0)
{
a=n%10;
sum=sum+a;
n=n/10;
}
printf("The summed digit is %d",sum);
getch();
}
8. Program to check the given no is Armstrong or not
#include<stdio.h>
#include<conio.h>
main()
{
int n,j,s=0,a;
clrscr();
printf("Enter a no:");
scanf("%d",&n);
j=n;
while(n>0)
{
a=n%10;
s=s+a*a*a;
n=n/10;
}
if(s==j)
printf("The given no is an armstrong no");
else
printf("The given no is not an armstrong no");
getch();
}
9. Program to generate prime numbers
#include<stdio.h>
#include<conio.h>
main()
{
int n,i,j;
clrscr();
printf("Enter the range:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=2;j<=i;j++)
{
if(i%j!=0)
continue;
else
break;
}
if(j==i)
printf("%d\t",i);
else
continue;
}
getch();
}

Prof M. P. Raj (B. Tech - AIT) Page: 25/48


Programming in C (AIT 112)

Functions

Definition
Function is a self-contained block of programs that performs a coherent task of some
kind... Every C program can be thought of as a collection of these functions.
There are two types of functions
1. Library functions e.g.: printf() , scanf()
2. User defined functions
User defined functions can be broadly divided into two types
1. Functions without arguments
2. Functions with arguments
1. Functions without arguments
Implementation
Three steps
1. Function prototype declaration
Syntax:
return type function name ();
e.g.:
void message();
void italy();
int sum();
2. Function calling
Syntax:
function name();
e.g.:
----
message();
italy();
sum();
3. Function Definition
Syntax:
return type function name ()
{
body of the function;
}
e.g.:
void message()
{
printf(Welcome to Functions);
}
e.g.:
#include<stdio.h>
#include<conio.h>
void message();
void main()
{
clrscr();
printf("I am in main function\n");
message();
getch();
}
void message()
{
printf("Welcome to c program");
}
Points to remember
1. C program is a collection of one or more functions.
2. If a program function only one function it must be main().
3. Program execution always begin with main().
4. There is no limit on the number of functions that might be present in a C program.

Prof M. P. Raj (B. Tech - AIT) Page: 26/48


Programming in C (AIT 112)

E.g.:
#include<stdio.h>
#include<conio.h>
void message();
void usage();
void main()
{
clrscr();
printf("I am in main function\n");
message();
usage();
printf("I am back in main");
getch();
}
void message()
{
printf("I am in message\n");
}
void usage()
{
printf("I am in usage\n");
}
5. Each of the function is called in a sequence specified by the function calls in the main().
6. After each function has done its thing, its control returns to main().
7. A function gets called when a function name is followed by a semicolon.
8. A function is defined when function name is followed by a pair of braces in which one or more
statements may present.
9. Any function can be called from any other function. Even main() can be called from other
function. For e.g.
main()
{
message();
}
message()
{
printf(I am in C \n);
main();
}
e.g.:
#include<stdio.h>
#include<conio.h>
void italy();
void brazil();
void main()
{
clrscr();
printf("I am in main function\n");
italy();
printf("I am back in main function");
getch();
}
void italy()
{
printf("Welcome to italy\n");
brazil();
printf("I am back in italy\n");
}
void brazil()
{
printf("I am in brazil\n");
}
10. A function can be called any no of times.

Prof M. P. Raj (B. Tech - AIT) Page: 27/48


Programming in C (AIT 112)

11. The order in which the functions are defined in the program and the order in which they are
called need not necessarily be same.
12. A function can call itself. Such a process is called recursion.
13. A function can be called from the other function, but a function cannot be defined in another
function.
Advantages of using functions
1. Writing functions avoids rewriting the same code repeatedly.
2. Using functions it is easier to write programs and keep track of what they are doing.

Functions with arguments


Sometimes we want to communicate between the calling function and the called
function. This is done by using argument.
The mechanism used to convey information to the function is the argument. The
arguments are sometimes also called parameters.
There are two types of arguments.
1. Actual arguments.
2. Formal arguments.
We must declare the type of the arguments through type declaration statements before
beginning with the statements in the functions.
Syntax:
return type function name(data type arg1, data type arg2,.data type arg n)
{
statements;
}
Similarly, we can call a function in two ways.
1. call by value
2. Call by reference.

Call by value
Definition
It is a method of passing a photocopy of the values to the calling functions.
E.g.:
#include<stdio.h>
#include<conio.h>
int add(int x,int y);
void main()
{
int a,b,sum;
clrscr();
printf("Enter any two nos:");
scanf("%d%d",&a,&b);
sum=add(a,b);
printf("Sum=%d\n",sum);
getch();
}
int add(int x,int y)
{ int z;
z=x+y;
return(z);
}

Difference between Pass by value and pass by reference or address:


Pass By Reference :
In Pass by reference address of the variable is passed to a function. Whatever changes
made to the formal parameter will affect to the actual parameters
- Same memory location is used for both variables.(Formal and Actual)-
- it is useful when you required to return more then 1 values
Pass By Value:
- In this method value of the variable is passed. Changes made to formal will not affect
the actual parameters.
- Different memory locations will be created for both variables.
Prof M. P. Raj (B. Tech - AIT) Page: 28/48
Programming in C (AIT 112)

Points to remember
1. In the above program we are passing a photocopy of the value a, b to the function add(). In
add() these values get collected in the variables x and y.
2. The variables a and b is called as actual arguments. whereas the variables x and y are called
as formal arguments.. Any number of arguments can be passed to a function being called.
However, the type, order and number of the actual and formal arguments must always be same.
3. If we want to return some values to the main function then it is done by using the return
statement. The return statement serves two purposes.
a) On executing the return statement, it immediately transfers the control back to the
calling program.
b) It returns the value present in the parentheses, after return to the calling program.
4. There is no restriction on the number of return statements that may be present in a function.
In addition, the return statement need not always be present at the end is called function.
e.g.:
#include<stdio.h>
#include<conio.h>
int code(int d);
void main()
{
int c;
char letter;
clrscr();
printf("Enter a character:");
c=getchar();
letter=code(c);
printf("Letter=%c",letter);
getch();
}
int code(int d)
{
if(d>=65&&d<=97)
return(d+32);
else
return(d);
}

5. Whenever the control returns from a function some value is definitely returned. If we want the
called function should not return any value in that case, we must mention so by using the
keyword void.
6. A function can return one value at a time.
7. If the return statement does not contain any argument then it will return a garbage value.
8. If the value of the formal argument is changed in the called function, the corresponding change
does not take place in the calling function.
E.g.:
#include<stdio.h>
#include<conio.h>
void num(int b);
void main()
{
int a=20;
clrscr();
num(a);
printf("A=%d",a);
getch();
}
void num(int b)
{
int b=60;
printf("B=%d\n",b);
}
Function declaration and prototypes
Prof M. P. Raj (B. Tech - AIT) Page: 29/48
Programming in C (AIT 112)

Eg:
#include<stdio.h>
#include<conio.h>
float square(float x);
void main()
{
float a,b;
clrscr();
printf("Enter any no:");
scanf("%f",&a);
b=square(a);
printf("Square of %f is %f",a,b);
getch();
}
float square(float x)
{
float y;
y=x*x;
return(y);
}
Scope rule of function
This is decided depending upon the variable, where it is declared.
If the variable is declared inside a function then it is called as local variables, and the
corresponding values of the variables are available within that function only.
If the variable is declared outside a function, then it is called as global variables or
external variable and the corresponding values of the variable are available all over the function.
Calling functions with arrays
Array elements can be passed to a function by calling the function by value or by
reference.
In the call by value, we pass values of array elements to the function, whereas in the call
by reference we pass addresses of array elements to the function.
e.g.:

#include<stdio.h>
#include<conio.h>
void display(int m);
void main()
{
int i;
int marks[]={50,60,70,80,90};
clrscr();
for(i=0;i<5;i++)
display(marks[i]);
getch();
}
void display(int m)
{
printf("%d\n",m);
}
Recursive function
A function can call itself . A function is called recursive if a statement within the body of a
function can call the same function. Sometimes called as circular definition. Recursion is thus the
process of defining something in terms of itself.
e.g.:
#include<stdio.h>
#include<conio.h>
int rec(int x);
void main()
{
int a,fact;
clrscr();
printf("Enter any no:");
Prof M. P. Raj (B. Tech - AIT) Page: 30/48
Programming in C (AIT 112)

scanf("%d",&a);
fact=rec(a);
printf("Factorial value=%d",fact);
getch();
}
int rec(int x)
{
int f;
if(x==1)
return(1);
else
f=x*rec(x-1);
return(f);
}

Prof M. P. Raj (B. Tech - AIT) Page: 31/48


Programming in C (AIT 112)

UNIT-IV
Defining and processing Arrays, Passing arrays to a function, Multi dimensional arrays, Define String, Using the String,
Printing a String, String inbuilt Functions (string.h).

Array
Array is nothing but a collection of like data types. These similar elements could be all ints, or all
floats, or all chars etc. Usually the array of characters is called a string, whereas an array of ints
or floats is called simply an array.
Array Declaration
Syntax:
data type variable name[dimension];
e.g.:
int a[10];
float c[5];
char name[40];
Accessing elements of an array
We can access array elements by using a subscript. This subscript variable can take
different values and hence can refer to the different elements in the array in turn.
Points to remember.
1. An array is a collection of similar elements.
2. The first element in the array is numbered 0, so the last element is less then the size of the
array.
3. An array is also known as the subscripted variable.
4. Before using an array its type and dimension must be declared.
5. An array elements are always stored in adjacent memory location.
6. Array starts from the 0th location.
Two types of array
1. Single dimensional array.
e.g.:
#include<stdio.h>
#include<conio.h>
main()
{
int mark[10],avg,n,sum=0,i;
clrscr();
printf("Enter how many nos:");
scanf("%d",&n);
for(i=0;i<n;i++) /* store datas in an array */
{
printf("Enter marks one by one:");
scanf("%d",&mark[i]);
}
for(i=0;i<n;i++)
sum=sum+mark[i]; /* read data from an array */
avg=sum/n;
printf("Average marks=%d",avg);
getch();
}
Array Initialization
1. If the array elements are not given any specific values, they are supposed to contain garbage
values.
2. If the array is initialized where it is declared, mentioning the dimension of the array is optional.
3. If the array is initialized where it is declared, its storage class must be either static or extern.
e.g.:
---
int num[6]={2,4,3,4};
int num[] = { 2,4,4,7,8};
2. Two dimensional array
A two dimensional array is also called as matrix.
Declaration
Prof M. P. Raj (B. Tech - AIT) Page: 32/48
Programming in C (AIT 112)

Syntax:
data type variable name[ row dimension] [ column dimension];
e.g.:
int a[3][3];
e.g.:
#include<stdio.h>
#include<conio.h>
main()
{
int stud[4][2];
int i.j;
clrscr();
for(i=0;i<=3;i++)
{
printf(Enter roll no and marks:);
scanf(%d%d,&stud[i][0],&stud[i][1]);
}
for(i=0;i<=3;i++)
printf(%d\t%d\n,stud[i][0],stud[i][1]);
getch();
}

The array elements are being stored and accessed row wise.
Initializing a 2 dimensional array
While initializing an array it is necessary to mention the second (column) dimension,
whereas the first dimension (row) is optional.
e.g.:
int student [4] [2] = {
{124,89},
{125,90},
{145,90}
};
Multidimensional Array
A three dimensional array can be thoght of as an array of arrays. In practice, one rarely
uses this array.
E.g.:
int stud [2] [2] [2] = {
{
{2,3},
{4,8},
{ 8,10}
},
{
{ 3,8},
{9,7},
{7,5}
}
};

Strings or Character Arrays


A string constant is a one-dimensional array of characters terminated by a null.
E.g.:

char name [] = { k,a,v,I,t,h,a,\0};


or
char name[10] = Kavitha;
eg:
----
#include<stdio.h>
#include<conio.h>
main()
Prof M. P. Raj (B. Tech - AIT) Page: 33/48
Programming in C (AIT 112)

{
char name[10]="Lavanya";
int i=0;
clrscr();
while(name[i]!='\0')
{
printf("%c",name[i]);
i=i+1;
}
getch();
}
Note
1. The length of the string should not exceed the dimension of the character arry.
2. scanf() is not capable of receiving multiword strings. So in that case we can use gets () instead
of scanf ().
Some important programs
Matrix addition
#include<stdio.h>
#include<conio.h>
main()
{
int a[3][3],b[3][3],c[3][3],i,j;
clrscr();
printf("Enter the first matrix value one by one:\n");
for(i=0;i<3;i++)
{
printf("Enter the %d row value:",i+1);
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
}
printf("Enter the second matrix value one by one:\n");
for(i=0;i<3;i++)
{
printf("Enter the %d row value:",i+1);
for(j=0;j<3;j++)
scanf("%d",&b[i][j]);
}
clrscr();
printf("The Matrix Addition is below\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];
printf("\t%d",c[i][j]);
}
printf("\n");
}
getch();
}

Matrix multiplication
#include<stdio.h>
#include<conio.h>
main()
{
int a[3][3],b[3][3],c[3][3],i,j,k;
clrscr();
printf("Enter the first matrix value one by one:\n");
for(i=0;i<3;i++)
{
printf("Enter the %d row value:\n",i+1);
for(j=0;j<3;j++)
Prof M. P. Raj (B. Tech - AIT) Page: 34/48
Programming in C (AIT 112)

scanf("%d",&a[i][j]);
}
printf("Enter the second matrix value one by one:\n");
for(i=0;i<3;i++)
{
printf("Enter the %d row value:\n",i+1);
for(j=0;j<3;j++)
scanf("%d",&b[i][j]);
}
clrscr();
printf("The matrix multiplication is below\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c[i][j]=0;
for(k=0;k<3;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][i];
}
printf("%d\t",c[i][j]);
}
printf("\n");
}
getch();
}
Program to find the Maximum of n numbers
#include<stdio.h>
#include<conio.h>
main()
{
int a[10],big,i,n;
clrscr();
printf("Enter no of values:");
scanf("%d",&n);
printf("Enter the values one by one:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
big=a[0];
for(i=1;i<n;i++)
{
if(big<a[i])
{
big=a[i];
}
}
printf("Biggest no is:\n");
printf("%d\n",big);
getch();
}

Program for ascending order


#include<stdio.h>
#include<conio.h>
main()
{
int a[10],temp,i,j,n;
clrscr();
printf("Enter the no of values:\n");
scanf("%d",&n);
printf("Enter the values:\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
Prof M. P. Raj (B. Tech - AIT) Page: 35/48
Programming in C (AIT 112)

for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("Ascending order values \n");
for(i=0;i<n;i++)
{
printf("%d\n",a[i]);
}
getch();
}

Prof M. P. Raj (B. Tech - AIT) Page: 36/48


Programming in C (AIT 112)

UNIT-V
Define Pointer, Pointer Arithmetic, passing pointer to function, Function data return with a Pointer,
Define structure, passing structure to a function, Unions, typedef, array of structure and pointer to structure.

Pointers
Pointers are special variables that contain addresses i.e. it represents the location of a data item,
such as variable or an array element.
Like normal variables, pointer variables should be declared in the beginning of the program.
Pointer Declaration
Syntax:
data type *variable name;
e.g.:
int *a;
float *cd;
char *name;
Operators in pointers
& address of operator
* value at address operator.
E.g.
#include<stdio.h>
#include<conio.h>
void main()
{
int i=3;
clrscr();
printf("%d\n",i);
printf("%d\n",&i);
getch();
}

Pointer Expressions
Pointer assignment
Eg:
#include<stdio.h>
#include<conio.h>
void main()
{
int i=3;
int *j;
j=&i;
clrscr();
printf("%d\n",i);
printf("%d\n",j);
printf("%d\n",&i);
printf("%d\n",&j);
printf("%d\n",*j);
printf("%d",*(&i));
getch();
}
Pointer Arithmetic
1. Addition of a no to a pointer.
2. Subtraction of one pointer from another pointer.
3. Subtraction of a no from a pointer
4. Comparing two pointers pointing to the objects of the same type.

1. Addition of a no to a pointer
e.g.: 1
#include<stdio.h>
#include<conio.h>
void main()
{
Prof M. P. Raj (B. Tech - AIT) Page: 37/48
Programming in C (AIT 112)

int i=4,*j,*k;
j=&i;
k=&j;
clrscr();
printf("%d\n",i);
printf("%d\n",j);
printf("%d\n",k);
j=j+1;
k=j+3;
printf("%d\n",j);
printf("%d\n",k);
getch();
}
Eg: 2
#include<stdio.h>
#include<conio.h>
void main()
{
int i=3,*x;
float j=1.5,*y;
char k='c',*z;
clrscr();
printf("%d\n",i);
printf("%f\n",j);
printf("%c\n",k);
x=&i;
y=&j;
z=&k;
printf("%d\n",x);
printf("%d\n",y);
printf("%d\n",z);
x++;;
y++;
z++;
printf("%d\n",x);
printf("%d\n",y);
printf("%d",z);
getch();
}

2. Subtraction of a no from a pointer


e.g.:
#include<stdio.h>
#include<conio.h>
void main()
{
int i=4,*j;
j=&i;
clrscr();
printf("%d\n",j);
printf("%d\n",&j);
j=j-2;
printf("%d\n",j);
j=j-5;
printf("%d",j);
getch();
}

3. Subtracting one pointer from another pointer


e.g.:
#include<stdio.h>
#include<conio.h>
void main()
Prof M. P. Raj (B. Tech - AIT) Page: 38/48
Programming in C (AIT 112)

{
static int arr[]={10,20,30,40,67,74};
int *i,*j;
i=&arr[1];
j=&arr[5];
clrscr();
printf("%d\t%d",j-i,*j-*i);
getch();
}
Note:
Here both the pointers should point to the same array.

4. Comparing two pointers pointing to the objects of the same type


e.g.:
#include<stdio.h>
#include<conio.h>
void main()
{
static int arr[]={10,20,30,40,50,60};
int *j,*k;
j=&arr[4];
k=&arr[0]+4;
clrscr();
if(j==k)
printf("The two pointers point to the same location");
else
printf("The two pointer points to the different location");
getch();
}

Pointers and Arrays


e.g.:
#include<stdio.h>
#include<conio.h>
void main()
{
static int num[]={24,34,12,44,56,78};
int i=0,*j;
j=&num[0];
clrscr();
while(i<=5)
{
printf("%d\t",j);
printf("%d\n",*j);
i++;
j++;
}
getch();
}

Calling functions with pointers


Call by reference
Here the addresses of actual arguments in the calling function are copied into formal
arguments of the called function.
The advantage of using call by reference is we can alter the actual arguments. However, in
call by value we cannot achieve this.
Using call by reference, we can make a function return more than one value at a time,
which is not possible ordinarily.
E.g.:
#include<stdio.h>
#include<conio.h>
Prof M. P. Raj (B. Tech - AIT) Page: 39/48
Programming in C (AIT 112)

void swap(int *x,int *y);


void main()
{
int a=10,b=20;
clrscr();
printf("Before swapping\n");
printf("a=%d\n",a);
printf("b=%d\n",b);
swap(&a,&b);
printf("After swapping\n");
printf("a=%d\n",a);
printf("b=%d\n",b);
getch();
}
void swap(int *x,int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
}

Calling functions with arrays (call by reference)


e.g.:
#include<stdio.h>
#include<conio.h>
void display(int *n);
void main()
{
static int num[]={55,78,90,78,80,50,79};
int i;
clrscr();
for(i=0;i<=6;i++)
display(&num[i]);
getch();
}
void display(int *n)
{
printf("%d\n",*n);
}

Passing an entire array to a function


e.g.:
#include<stdio.h>
#include<conio.h>
void display(int *j,int n);
void main()
{
static int num[]={50,60,70,80,90,100,110};
clrscr();
display(&num[0],7);
getch();
}
void display(int *j,int n)
{
int i=1;
while(i<=n)
{
printf("Element=%d\n",*j);
i++;
j++;
}
}
Prof M. P. Raj (B. Tech - AIT) Page: 40/48
Programming in C (AIT 112)

Accessing array elemnets in different ways


e.g.:
#include<stdio.h>
#include<conio.h>
void main()
{
static int num[]={40,50,60,70,80,90};
int i=0;
clrscr();
while(i<=5)
{
printf("%d\t",&num[i]);
printf("%d\t",num[i]);
printf("%d\t",*(num+i));
printf("%d\t",i[num]);
printf("%d\n",*(i+num));
i++;
}
getch();
}

Pointers versus arrays


E.g.:
#include<stdio.h>
#include<conio.h>
void main()
{
static char arr[10]="Nagpur";
char *s="Nagpur";
clrscr();
printf("%s\n",arr);
printf("%s",s);
getch();
}

First difference
In the above program Nagpur gets stored in arr[] and the base address of it is stored in s.

Second difference
E.g.:
#include<stdio.h>
#include<conio.h>
void main()
{
static int arr[10]="Nagpur";
char *s="Nagpur";
clrscr();
s++;
printf("%s\n",s);
arr++;
printf("%s",arr);
getch();
}
Here the Output of s is agpur but the output of an arr is an error message.i.e the compiler
assumes us that we are attempting to change its base address.

Third difference
e.g.
#include<stdio.h>
#include<conio.h>

Prof M. P. Raj (B. Tech - AIT) Page: 41/48


Programming in C (AIT 112)

void main()
{
static char arr[]="Nagpur";
char *s="Nagpur";
clrscr();
printf("Size of arr=%d\n",sizeof(arr));
printf("Size of s=%d",sizeof(s));
getch();
}

Another difference between arrays and pointers are the way the size of operator treats them.
In the above program, size of arr is 7 and size of s is 2.

Pointers and two-dimensional arrays


e.g.:
#include<stdio.h>
#include<conio.h>
void main()
{
static int stud[5][2]={
{101,80},
{102,90},
{103,78},
{104,87},
{105,69},
};
int i,j;
clrscr();
for(i=0;i<=4;i++)
{
for(j=0;j<=1;j++)
printf("%d\t",*(*(stud+i)+j));
printf("\n");
}
getch();
}

Array of pointers
Array of pointers is nothing but collection of addresses.
Eg:
#include<stdio.h>
#include<conio.h>
void main()
{
int *arr[4];
int i=31,j=5,k=19,l=71,m;
arr[0]=&i;
arr[1]=&j;
arr[2]=&k;
arr[3]=&l;
clrscr();
for(m=0;m<=3;m++)
{
printf("%d\t",arr[m]);
printf("%d\n",*(arr[m]));
}
getch();
}

Array of pointers can even contain the addresses of other arrays.


E.g.:
#include<stdio.h>
#include<conio.h>
Prof M. P. Raj (B. Tech - AIT) Page: 42/48
Programming in C (AIT 112)

void main()
{
static int a[]={0,1,2,3,4};
static int *p[]={a,a+1,a+2,a+3,a+4};
clrscr();
printf("%d\t%d\t%d",p,*p,*(*p));
getch();
}
Array of pointers is very popular used for storing several strings in memory.
eg:
Static char *names[]={
kavitha,
anitha,
harini,
};

Limitations of array of pointers to strings


1. When we are using an array of pointers to strings we can initialize the strings at the place
where we are declaring, the array. But we cannot receive the strings from keyboard using
scanf().
2. When we are declaring the array it contains garbage value.

Pointers to pointers
e.g.:
#include<stdio.h>
#include<conio.h>
void main()
{
int i=3;
int *j;
int **k;
j=&i;
k=&j;
clrscr();
printf("%d\n",i);
printf("%d\n",&i);
printf("%d\n",j);
printf("%d\n",&j);
printf("%d\n",*j);
printf("%d\n",k);
printf("%d\n",&k);
printf("%d\n",*k);
printf("%d\n",*(&i));
printf("%d",**k);
getch();
}

Pointers to functions
eg:1
#include<stdio.h>
#include<conio.h>
void main()
{
void display();
clrscr();
printf("%d\n",display);
display();
getch();
}
void display()
{
printf("Test for function");
Prof M. P. Raj (B. Tech - AIT) Page: 43/48
Programming in C (AIT 112)

EG:2
#include<stdio.h>
#include<conio.h>
void main()
{
void display();
void (*funcptr)();
clrscr();
funcptr=display;
printf("%d\n",funcptr);
(*funcptr)();
getch();
}
void display()
{
puts("Hello");
}
Uses
1. To write memory resident programs.
2. To write viruses or vaccines to remove the viruses

Passing structure elements to functions


1. Passing individual structure elements
e.g.:
#include<stdio.h>
#include<conio.h>
void display(char *s,char *t,int n);
void main()
{
struct book
{
char name[25];
char author[25];
int bno;
};
static struct book b1={"C","Balagurusamy",120};
clrscr();
display(b1.name,b1.author,b1.bno);
getch();
}
void display(char *s,char *t,int n)
{
printf("%s\n%s\n%d",s,t,n);
}

2. Passing entire structure to a function


eg:
#include<stdio.h>
#include<conio.h>
struct book
{
char name[25];
char author[25];
int bno;
};
void display(struct book b);
void main()
{
static struct book b1={"C","Balagurusamy",120};
clrscr();
Prof M. P. Raj (B. Tech - AIT) Page: 44/48
Programming in C (AIT 112)

display(b1);
getch();
}
void display(b)
struct book b;
{
printf("%s\n%s\n%d",b.name,b.author,b.bno);
}
Structures
Structures are collection of unlike data types. Like arrays, structure elements are stored in
contiguous memory locations.
There are two steps to define a structure.
1. Declaration of a structure.
2. Accessing of structure elements.
Declaring a structure
Syntax:
struct structure name
{
struct element 1;
struct element 2;
struct element 3;
};
e.g.:
struct book
{
char bookname[25];
float price;
int bookno;
};

Accessing structure elements


We can access structure elements by using a dot operator. Before the dot there must
always be a structure variable and after a dot there must always be a structure element.
E.g.:
Struct book
{
char name[10];
int pages;
float price;
};
struct book b;
e.g.:
b.name
b.pages
b.price
e.g.:
#include<stdio.h>
#include<conio.h>
main()
{
struct book
{
char name[25];
int pages;
float price;

};
struct book b1,b2;
clrscr();
printf("Enter the first book details:\n");
scanf("%s%f%d",b1.name,&b1.price,&b1.pages);
Prof M. P. Raj (B. Tech - AIT) Page: 45/48
Programming in C (AIT 112)

printf("Enter the second book details:\n");


scanf("%s%f%d",b2.name,&b2.price,&b2.pages);
printf("Book details\n");
printf("Name=%s\nPrice=%f\nPages=%d\n",b1.name,b1.price,b1.pages);
printf("Name=%s\nPrice=%f\nPages=%d",b2.name,b2.price,b2.pages);
getch();
}

Like array variables, structure variables are also directly initialized where they are created.
E.g.:
Struct book
{
char name[2];
float price;
int pages;
};
struct book b1={Basic,150.40,230};
struct book b2={C++,140.60,250};
Array of structures
e.g.:
#include<stdio.h>
#include<conio.h>
main()
{
struct book
{
char name[25];
int pages;
int price;
};
struct book b[10];
int i,n;
clrscr();
printf("Enter how many books:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the name,pages,price:\n");
scanf("%s%d%d",b[i].name,&b[i].pages,&b[i].price);
}
for(i=0;i<n;i++)
printf("Name=%s\nPages=%d\nPrice=%d\n",b[i].name,b[i].pages,b[i].price);
getch();
}
Structures within structures ( Nested structure)
eg:
#include<stdio.h>
#include<conio.h>
main()
{
struct address
{
char phone[15];
char city[25];
int pin;
};
struct emp
{
char name[25];
struct address a;
};
struct emp e={"Kavitha","530146","nagpur",10};

Prof M. P. Raj (B. Tech - AIT) Page: 46/48


Programming in C (AIT 112)

clrscr();
printf("Name=%s\nPhone=%s\n",e.name,e.a.phone);
printf("City=%s\nPin=%d",e.a.city,e.a.pin);
getch();
}
Uses of structures
strcutures are used in variety of applications .The most important are in the database
management system.

Unions
Unions are similar to structures .The main difference between these two is a structure enables us
to treat a number of different variables stored at different places in memory. A union enables us
to treat the same space in memory at a no of different variables.
Uses of unions
They are useful for applications involving multiple elements, where values need not be
assigned to all the elements at any one of time.

OR
Unions like structure contain members whose individual data types may differ from one another.
However the members that compose a union all share the same storage area within the
computers memory where as each member within a structure is assigned its own unique storage
area. Thus unions are used to conserve memory. They are useful for application involving
multiple members. Where values need not be assigned to all the members at any one time. Like
structures union can be declared using the keyword union as follows:
union item
{
int m;
float p;
char c;
}
code;

this declares a variable code of type union item. The union contains three members each with a
different data type. However we can use only one of them at a time. This is because if only one
location is allocated for union variable irrespective of size. The compiler allocates a piece of
storage that is large enough to access a union member we can use the same syntax that we use
to access structure members. That is
code.m
code.p
code.c
are all valid member variables. During accessing we should make sure that we are accessing the
member whose value is currently stored.
For example a statement such as
code.m=456;
code.p=456.78;
printf(%d,code.m);
Would produce erroneous result.
In effect a union creates a storage location that can be used by one of its members at a time.
When a different number is assigned a new value the new value supercedes the previous
members value. Unions may be used in all places where a structure is allowed. The notation for
accessing a union member that is nested inside a structure remains the same as for the nested
structure.

The differences between structure and union in c are:


1. Union allocates the memory equal to the maximum memory required by the member of the
union but structure allocates the memory equal to the total memory required by the
members.
2. In union, one block is used by all the member of the union but in case of structure, each
member has their own memory space

Prof M. P. Raj (B. Tech - AIT) Page: 47/48


Programming in C (AIT 112)

3) Structure: The size in bytes is the sum total of size of all the elements in the structure, plus
padding bytes. Size of in bytes of the union is size of the largest variable element in the union.

While structure enables us treat a number of different variables stored at different in memory, a
union enables us to treat the same space in memory as a number of different variables. That is a
Union offers a way for a section of memory to be treated as a variable of one type on one
occasion and as a different variable of a different type on another occasion.

Structure pointers
A pointer pointing to a structure is known as structure pointer
E.g.
#include<stdio.h>
#include<conio.h>
void main()
{
struct book
{
char name[25];
char author[25];
int bno;
};
static struct book b1={"C","Balagurusamy",120};
struct book *ptr;
ptr=&b1;
clrscr();
printf("%s\n%s\n%d\n",b1.name,b1.author,b1.bno);
printf("%s\n%s\n%d",ptr->name,ptr->author,ptr->bno);
getch();
}

Passing address to a structure variable


#include<stdio.h>
#include<conio.h>
struct book
{
char name[25];
char author[25];
int bno;
};
void display(struct book *b);
void main()
{
static struct book b1={"C","Balagurusamy",120};
clrscr();
display(&b1);
getch();
}
void display(b)
{
struct book *b;
printf("%s\n%s\n%d",b->name,b->author,b->bno);
}

Prof M. P. Raj (B. Tech - AIT) Page: 48/48

You might also like