0% found this document useful (0 votes)
28 views61 pages

Unit I

Unit 1 provides an introduction to the C programming language, covering its features, data types, operators, and the process of executing a C program. Key concepts include variable declarations, functions, and the importance of modularity and portability in C. The document also outlines the rules for identifiers and constants, as well as type conversions and expressions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views61 pages

Unit I

Unit 1 provides an introduction to the C programming language, covering its features, data types, operators, and the process of executing a C program. Key concepts include variable declarations, functions, and the importance of modularity and portability in C. The document also outlines the rules for identifiers and constants, as well as type conversions and expressions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

UNIT-I

Unit 1:
Introduction to C Language, C language elements, Variable declarations and Data types, Operators and
Expressions, If and Switch statements, While, For, Do-while, Arrays, Functions, Types of functions,
Recursion and Argument passing.

OVERVIEW OF C LANGUAGE

Features of c Language:

C is the most popular programming language, C has many advantages:

Modularity: modularity is one of the important characteristics of C. we can split the C program
into no. of modules instead of repeating the same logic statements (sequentially). It allows
reusability of modules.
Middle level language: As a middle level language C combines both the advantages of low level
and high level languages. (arrays, pointers etc).
General purpose programming language: C can be used to implement any kind of
applications such as math’s oriented, graphics, business oriented applications.
Portability: we can compile or execute C program in any operating system (unix,dos,windows).
Powerful programming language: C is very efficient and powerful programming language; it
is best used for data structures and designing system software.

C is case sensitive language

1
Preprocessor Directives:

– Preprocessor Directives are directives which inform the compiler in advance that
the program makes use of functions for which the definitions are available in the
header files.
e.g., #include <stdio.h>
– Any statement that starts with #(pound) symbol is considered as Preprocessor
Directive
Global Declarations:
– Global Declarations includes declaration of all variables and constants that will be
available for all functions in the program.
– All declarations above main function are considered to be in the global scope.
main function:
– Every C Program must have main function.
– There can be more than one function in a program.
– C Program execution begins from main function.
– Each function has 2 parts:
– Function header
– Function Body
1. Declaration section
2. Statement section
The function header includes
Function return type, function name or identifier and function parameters list

Declaration and statement section form the function body.


– local Declarations includes declaration of all variables and constants that will be
used in that function.
– All declarations within any function are considered to be in the local scope.
– All declarations are to be made at the beginning of the function body.

2
– Statement sections may include an input statement or output statement or
assignment statement or function call.
– the last statement of the function body is return statement. This statement returns
value to the function from where it was called.
Comments are non executable statements.
– Comments are used to specify the purpose of the program/statement.
– Comments can be of two types:
• line comment
• block(multi line comment)
Line comment begin with //
Block comment begin with /* and end with */
Sample code showing the usage of comments, preprocessor directives and statements is shown
below:

PROCESS OF EXECUTING A ‘C’ PROGRAM:


The Process of executing a program in ‘C’ involves the following steps:
1. Creating the Program
2.Compiling the Program
3. Linking the Program with functions that are needed from the ‘C’ library
4. Executing the Program

The Process of creating,compiling and executing a ‘C’ program is shown in the


following figure. The steps remain the same irrespective of the operating system though the system
commands for implementing the steps and the convention followed for naming files may vary on
different systems.

3
Let us Discuss each step in detail:
1. Creating the Program: The Program that is to be created must be entered into a file. The file
name can consist of letters, digits and special characters , followed by the extension .C.
First.C
Ab 12.C
2. Compiling and Linking: During the compilation process, the source program, the source
program instructions are translated into a form that is suitable for execution by the computer. The
translation process checks each and every instruction for correctness and if no errors are reported
then it generates the object code.
During the linking stage the other program files and functions that are required by the program are
put together with it.
If mistakes in the syntax and semantics of the language are discovered, they are listed out and the
compilation process ends there. The errors should be corrected in the source program with the help
of an editor and the compilation done again.
Executing the Program: During execution, We load the executable object code in the computers
memory and execute the instruction.
During execution, the program may request some data through the keyword.

Data Types

Data Types and Sizes:


Data Types:

A data type defines the range of values and the operations a program can perform on those
values.
Data type defines the size allocated to the variable and the type of value that can be stored.
Data types supported in C 99 are shown below:
4
Void Data Type:

– Keyword used is void.


– It has no value and no operations can be performed.
– Used when the function does not return any value or does not pass any
parameters.
– Eg., void main(void)
Character:
– C supports two character types: char and wchar_t.
– one byte(8bits) of space is allocated for this data type.
– Keyword char is used to store western characters in the named location.
Integer:
– Provides support for numbers without fractional part.
– Based on the size allocated to the named location we have four keywords
supported namely: short int, int, long int and long long int.
– To know the range of values that can be stored for a particular signed integer
data type: the following formula can be used.
-2n-1 to +2n-1 -1
– To know the range of values that can be stored for a particular unsigned integer
data type: the following formula can be used
0 to +2n -1
Where n indicates the no. of bits allocated for a particular integer data type.
– Limits for the different integer data types are defined in the header file “limits.h”
– The following property also should be true:
Sizeof(short int)<=sizeof(int)<=sizeof(long)<=sizeof(long long)
Table showing the size, minimum and maximum value of different integer data types

Floating point data type:

– Provide support for numbers with fractional values.


– Limits are defined in the C library float.h.
– Supported types : float, double, long double
Real Data Type

5
Provides support for numbers with integer and fractional part

Based on the size allocated we have float, double and long double

IDENTIFIER DEFINITION & RULES, FEW EXAMPLES


Identifiers:

It is the name given to identify a location or a function. There are two types of identifiers
namely:

▪ Standard identifier
▪ User-defined identifier
Standard identifier:

It is the name given to identify the functions/statements that are used in the
program and are defined in the header files. For e.g., printf, scanf

User-defined identifier:

It is the name given by the user to identify a storage location or a function that is
not defined in the header files. The following rules have to be followed by user to give name to
either the location or a function.

Rules for giving name to identifier:

▪ It should start with letter either in lower case or upper case.


▪ Any combination of letters and digits can be used after using the first
character as letter.
▪ It should not be a keyword
▪ There should not be spaces in between the word.
▪ No symbols is allowed only allowed symbol is underscore to link if the
word is lengthy.

Examples of valid identifiers

Rollnumber
Name
Subject1
College_name
Sex
Examples of invalid identifiers
4you
Do today
#welcome

6
Auto
Note: Programmer should ensure that the name given for the identifier at the declaration, the
same name should be used for every subsequent reference in the program.

Constants:
– Constants are data values that cannot be changed during the execution of the program.
– Constants supported in C99 are: Boolean constant, integer constant, real constant,
character constant, string constant and complex constant.
• Boolean constant
Boolean constant is represented as either true or false in our program. To use the boolean
constant we have to include stdbool.h in our program.
• Character constant
Character constant is represented by enclosing character in single quotes. Programming
Language C also supports backslash character constants also called as escape sequences
where we can use a character after the backslash. These constants have predefined meaning and
can be used in output statements.

• String Constant:
String constants are represented by enclosing sequence of characters within double quotes.
• Integer Constant:
Integer Constants are represented as shown below:
Representation Value Type

123 123 short int

-378 -378 int

-32271L -32271 long int

7
76542LU 76542 unsigned long int

12789845LL 12789845 long long int

• Real Constant

Real constants by default are represented as double. However if we want the resulting data to be
float or long double. We have to append the value as shown below:
Representation Value Type

-2.0f -2.0 Float

3.14159L 3.14159 Long double

Variables:
• Variables are named location in memory that can store a value of specific data type.
• Variables value often changes in course of program.
• A variable is a location in memory that is identified by a name and address and can store
value of a particular type.
• The variable can store input data or intermediate processed data or output data.
• The variable value can be modified with input statement or assignment statement.
• For e.g., for the declaration show below pictorially the variable with its attributes is
shown.
A name

int a=5; 5 contents/value of a specified type

2001 address

Variable Declaration:
• A variable can be declared for a particular data type as shown below:

data_type variable_name;

e.g., int roll_no;


char sex;
float per_marks;

8
• Multiple Variables can be declared for a particular data type as shown below:

data_type variable_name1,..variable_name n;

e.g., int sub1,sub2,sub3;


char sex,section;
float first_yr_perc,second_yr_perc;

Note: In Multiple variable declaration, each variable should be separated with comma
Note: When need arises for the programmer to store more than one character into the named
location, then the declaration is made as shown below:

data_type variablename[size];
where size takes an integer value specifying the count.
e.g., char stud_name[25];
Variable initialization:
Initializing value to a variable can be done as shown below:
data_type variable_name=value;
– when the data_type is char the value should be enclosed within single quote.
– when the data_type is int the value should be a number with integer part only.
– when the data_type is float the value should be a number with integer part and
fractional part
Type Modifiers/Format Specifiers/Format Strings
The following type modifiers/format specifiers/control strings can be used in
scanf(input statement) or printf(output statement).

– Code Meaning
– %a Reads/prints a floating -point value (C99 only).
– %c Reads/prints a single character.
– %d Reads/prints a decimal integer.
– %i Reads/prints an integer in either decimal, octal, or hexadecimal format.
– %e Reads/prints a floating -point number.
– %f Reads/prints a floating -point number.
– %g Reads/prints a floating -point number.
– %o Reads/prints an octal number.
– %s Reads/prints a string.
– %x Reads/prints a hexadecimal number.
– %p Reads/prints a pointer.
– %n Receives an integer value equal to the number of characters read so far.
– %u Reads/prints an unsigned decimal integer.
– %[ ] Scans for a set of characters.
– %% Reads a percent sign.

9
Operators and expressions:
Operators:

An operator indicates an operation to be performed on data. Below is given a table showing the
different symbols used for different types of operators?

Types of operators Symbolic representation

Arithmetic operators +(addition) , - (subtraction) , *


(multiplication), / (integer division) ,
% ( modulo division)

Assignment operators = (assignment), +=, -=, *=, /=, %=(short


hand assignment)

Relational operators < (less than), <= (less than equal to),
> (greater than), >= (greater than equal to),
= = (equality), != (not equal to)

Logical operators && (and), | | (or) , ! (not)

Increment , decrement operators ++ (increment) , -- (decrement)

Bitwise operators & (and), | (or), ^ (xor), ~ (complement),


<< (left shift), >> (right shift)

Conditional operator ?:

Comma operator ,

Expressions:
• It is defined as the combination of operands and operators where operand can be a
variable or constant.
• An expression can be simple or complex.
• An expression is said to be simple if only one operator is used. For e.g., a+b
• An expression is said to be complex if more than one operator is used. For e.g., a+(b*c)/e
• Based on the number of operators and the positions of the operands and operators an
expression can be divided into six categories as shown below:
Primary expression
Postfix expression
Prefix expression
Unary expression
Binary expression
Ternary expression
• Primary expression:
It is the elementary type of expression where only operand exists and operand can be a
variable or constant or parenthesized expression. For e.g., a, 5, (a+b)

• Postfix expression:
The postfix expression consists of one operand and one operator where the operator is
placed after the operand. For e.g.,clrscr(),a++,a - -. Where clrscr, a are the operands and (),
++ and – are the operators.

• Prefix expression:
The prefix expression consists of one operand and one operator where the operator is
increment or decrement operator placed before the operand for e.g., ++a,--a where a is the
operand and ++,-- are operators.

• Unary expression:
Unary expression consists of one operand and one operator where the operator is an
unary operator placed before the operand and it is similar to prefix expression. For e.g.,
+a, -b, ++a, --c.

• Binary expression:
Binary expression consists of two operands and one operator where the operator is an
arithmetic operator placed between the two operands. For e.g., a+b, a*b, c/d.

• Ternary expression or Conditional Operator:


Ternary expression is an expression that makes use of ternary operator (?:) and the
expression takes the form as shown below:

Expr1? expr2:expr3 where if expr1 is true then expr2 is evaluated else expr3 is evaluated.

For e.g., x>y? printf(“true”):printf(“false”);

If x>y is true then the string true will be printed otherwise false will be printed

Type Conversions :
It is the process of changing from one data type to another data type.

Conversion can be either implicit or explicit.

Implicit Conversion:

If an expression makes use of operands declared of different data types then the system
evaluates the expression by converting the result to a higher data type of an operand used in the
expression. Such type of conversion is called as implicit conversion. This type of conversion is
done by the system by following the rules shown below:
Long double

double

Float

Long long

Long

Int

Short

Char

Note: in the above table lower data type is shown in the last row and higher data type is shown
one step ahead.

For e.g., if we have an expression with three operands one of type int another of type float and
another type of long double then the result will be converted to long double. (As long double is
the higher data type compared to the other two).

Explicit Conversion or Casting:

If the programmer is interested to convert the result of an expression to a specified type


then such type of conversion is called as explicit conversion. This type of conversion is done by
writing the expression as shown below:

(Data type) expression;

Where data type is the type specified by the programmer and expects the result of the expression
to be converted to the type specified.

Precedence and Order of Evaluation:


Evaluation of Expressions:

For an individual to have an understanding of how expressions are evaluated one


should gain knowledge of the following things:

• Precedence
• Associativity
• Conversion rules
Precedence:

It tells of the priority order of operators in complex expression.


Associativity:

when operators with the same precedence are used in the complex expression It specifies
the direction of evaluation. The direction of evaluation can be either from left to right or from right
to left.

The precedence and associativity of the different types of operators is shown below:

Operator Operation Associativity Precedence

() Function call

[] Array size

-> Accessing Member of structure Left to right 1


through pointer variable

Structure variable to member


. access

+ Unary plus

- Unary minus

++ Increment

-- Decrement

! Negation(logical not) Right to left 2

~ Complement

* Pointer operator

& Address operator

Sizeof Size of an object

* Multiplication

/ Integer division Left to right 3

% Modulo division

+ Addition
Left to right 4
- Subtraction

<< Left shift Left to right 5


>> Right shift

< Less than

<= Less than equal to


Left to right 6
> Greater than

>= Greater than equal to

== Equality
Left to right 7
!= Not equal to

& Bitwise and Left to right 8

^ Bitwise xor Left to right 9

| Bitwise or Left to right 10

&& Logical and Left to right 11

|| Logical or Left to right 12

?: Conditional operator Right to left 13

=, +=,-=,*=,/=,%= Assignment operator Right to left 14

, Comma Left to right 15

Example: consider the expression 5 * 4 + 8 / 2

In the above expression we have two operators with the same precedence i.e., * and / so
we apply associativity first i.e., we evaluate the expression from left to right based on the above
table.

1. Next we consider the first occurrence of the operator with that precedence and evaluate
the operands placed before and after that operator for the operation. i.e., 5 * 4.
2. Next we consider the next occurrence of the operator with that precedence and evaluate
the operands placed before and after that operator for the operation i.e., 8 / 2.
Next we evaluate the result of step 1 and 2 with the operator which has least precedence than the
operators in step 1 and 2. i.e.. 20 + 4

Typedef:
The keyword typedef allows us to define an existing data type with other name. The general
form of typedef is given below:

typedef datatype newname;


For e.g.,
typedef int integer;

typedef float real;

In the above example, int is redefined as integer and float redefined as real.

Below we will see a simple example of how typedef is used.


#include <stdio.h>
main()
{
typedef int integer;
typedef float real
integer rollno;
real per_marks;
printf(“enter value rollno and per_marks:”);
scanf(“%d %f”,&rollno,&per_marks);
}

STANDARD INPUT AND OUTPUT FORMATTED INPUT AND OUTPUT


STATEMENTS

Reading a character:
To read a character from the keyboard the programming language C supports the function
getchar(). The getchar() function accepts character from the keyboard until enter key is pressed
but takes only first character. The general form of getchar() function is given below:

Variable=getchar();

The getchar() function does not take any argument.

For e.g.
main()
{
char ch;
ch=getchar();
printf(“%c”,ch);
}
Writing a character:
To write a character to the monitor the programming language C supports the function putchar().
The putchar() function writes a character to the output device. The general form of putchar()
function is given below:

putchar(variable);

For e.g.
main()
{
char ch=’a’;
putchar(ch);
}

System defined Functions to handle character operations(supported in ctype.h):

Function name Purpose


Isalpha(ch) Takes one argument as character and checks whether the accepted
character is alphabet or not. If alphabet it returns 1 otherwise returns 0.

Isdigit(ch) Takes one argument as character and checks whether the accepted
character is digit or not. If digit it returns 1 otherwise returns 0.

Islower(ch) Takes one argument as character and checks whether the accepted
character is in lower case or not. If lowercase it returns 1 otherwise
returns 0.

Isupper(ch) Takes one argument as character and checks whether the accepted
character is in upper case or not. If upper case it returns 1 otherwise
returns 0.

Isspace(ch) Takes one argument as character and checks whether the accepted
character is space or not. If space it returns 1 otherwise returns 0. here
space can be newline, tab or space.

Ispunct(ch) Takes one argument as character and checks whether the accepted
character is not an non-control character or not a space or not a letter.
If not an non-control character or not a space or not a letter then it
returns 1 otherwise returns 0.
Reading and Writing Strings:

String:
The group of characters, digits, and symbols enclosed within quotation marks are called as
string. By default a string gets terminated with null character (\0) , this character is not visible to
the user. Whereas a character is enclosed in single quote and it is not terminated with any
Default character.

For e.g., Printf(“welcome to strings”);


“Welcome to strings” is string constant.

Declaration of string variables


Char stringname [size];
for e.g., char stringname[20];
in the above example stringname is the name of the character array.

Initialization of string to character array


char stringname[size]=”value”;
Where value can be sequence of characters.
e.g., char stringname[20]=”learn strings”;

From the above declaration,”stringname” is the name of the character array and
“learnstrings” is the value initialized to the character array. By default terminated with null
character(\0) . Below we will see how the string is initialized and also see how memory is allocated
Name of String name
the array
index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
value l e a r n s t r i n g s \0

Initialization of characters to character array


For e.g.
char name[20]={‘l’,’e’,’a’,’r’,’n’,’ ‘,’s’,’t’,’r’,’i’,’n’,’g’,’s’};
From the above declaration, ”name” is the name of the character array and value is initialized as
character to the character array “name” and by default no character is terminated to mark the end
of the string. Below we will see how the character array is initialized and also see how memory
is allocated.
Name Name
of the
array
index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
value l e a r n s t r i n g s
Converting initialized characters to string
To convert the initialized characters to string just Terminate the initialized array of
characters with null character(\0). The procedure is shown below with an example.
For e.g.
Char name[20]={‘l’,’e’,’a’,’r’,’n’,’ ‘,’s’,’t’,’r’,’i’,’n’,’g’,’s’};

After adding null character the initialization becomes

char name[20]={‘l’,’e’,’a’,’r’,’n’,’ ‘,’s’,’t’,’r’,’i’,’n’,’g’,’s’,’\0’};

which is equivalent to char name[20]=”learn strings”;

Reading a string to the character array using scanf function:

To read a string from the keyboard, if suppose, a character array is declared as shown below:

char college_name[25];

then a string can be read using the scanf statement

scanf(“%s”,college_name);

Reading a string to the character array using gets function:

To read a string from the keyboard, if suppose, a character array is declared as shown below:

char college_name[25];

then a string can be read using the gets() function

gets(college_name);

Printing a string from the character array using printf function:

To print the contents of character array as string, if suppose, a character array is declared as
shown below:

char college_name[25]; and if contents are read using the scanf statement
scanf(“%s”,college_name);

and the contents of the character array can be printed as shown below:
printf(“%s”,college_name);
Printing a string from the character array using puts function:

To print the contents of character array as string, if suppose, a character array is declared as
shown below:

char college_name[25]; and if contents are read using the scanf statement
scanf(“%s”,college_name);

and the contents of the character array can be printed as shown below:
puts(college_name);

Formatted Console I/O

The functions printf( ) and scanf( ) perform formatted output and input— that is, they can read
and write data in various formats that are under your control. The printf( ) function writes data to
the console.

FORMATTED OUTPUT STATEMENT FOR PRINTING STRINGS:

#include <stdio.h>
main()
{
char coll_name[20]=”SPMU College”;
clrscr();
printf(“%s”,coll_name);
printf(“%15s”,coll_name);
printf(“%-15s”,coll_name);
printf(“%15.3s”,coll_name);
printf(“%15.0s”,coll_name);
printf(“%-15.3s”,coll_name);
}
Explanation:
• The first printf statement prints as shown below: SPMU College
• The second printf statement prints as shown below:bbbSPMU college Note: b
indicatesblanspace
• The third printf statement prints as shown below:SPMU college
• Note: - sign makes the string to print to the left
• The fourth printf statement prints as shown below:bbbbbbbbbbbbSPM Note: 15.3
indicates print first three characters of the string andexcess width prints the string
to the right.
• The fifth printf statement prints as shown below:Note: 15.0 indicates print nothing
• The sixth printf statement prints as shown below:SPM
Note:-15.3 print first three characters of the string to the left
FORMATTED OUTPUT STATEMENT FOR PRINTING CHARACTER DATA

#include <stdio.h>
main()
{
char ch=’a’;
clrscr();
printf(“%c”,ch);
printf(“%4c”,ch);
printf(“%-4c”,ch);
}
Explanation:
• The first printf statement prints as shown below:a
• The second printf statement prints as shown below:bbba
• Note: b indicates blank space
• The third printf statement prints as shown below:a
• Note: - sign makes the character to be printed to the left

FORMATTED OUTPUT STATEMENT FOR PRINTING INTEGER DATA

Integer data:
#include <stdio.h>
main()
{
int data=-10;
clrscr();
printf(“%d”,data);
printf(“%10d”,data);
printf(“%-10d”,data);
}
Explanation:
• The first printf statementprints as shown below:-10
• The second printf statement prints as shown below:bbbbbbb-10 Note: b indicates
blankspace
• The third printf statement prints as shown below:-10
• Note: - sign makes the string to print to the left Float data

FORMATTED OUTPUT STATEMENT FOR PRINTING FLOATING POINT DATA

#include <stdio.h>
main()
{
float value=42.3;
clrscr();
printf(“%f”,value);
printf(“%10.2f”,value);
printf(“%-10.2f”,value);
}
Explanation:
• The first printf statementprints as shown below:42.300000
• The second printf statement prints as shown below:bbbbb42.30Note: b indicates blank
space
• The third printf statement prints as shown below:42.30Note: - sign makes the string to
print to the left

Scanf():

scanf( ) is the general -purpose console input routine. It can read all the built-in data types and
automatically convert numbers into the proper internal format.

The prototype for scanf( ) is

int scanf(const char *control_string, . . . );

The scanf( ) function returns the number of data items successfully assigned a value. If an error
occurs, scanf( ) returns EOF. The control_string determines how values are read into the
variables pointed to in the argument list.
You can use scanf( ) to read integers in either octal or hexadecimal form by using the %o and
%x format commands, respectively. The %x can be in either upper- or lowercase. Either way,
you can enter the letters A through F in either case

Code Meaning
%a Reads a floating -point value (C99 only).
%c Reads a single character.
%d Reads a decimal integer.
%i Reads an integer in either decimal, octal, or hexadecimal format.
%e Reads a floating -point number.
%f Reads a floating -point number.
%g Reads a floating -point number.
%o Reads an octal number.
%s Reads a string.
%x Reads a hexadecimal number.
%p Reads a pointer.
%n Receives an integer value equal to the number of characters read so far.
%u Reads an unsigned decimal integer.
%[ ] Scans for a set of characters.
%% Reads a percent sign.
Control Structures or Control Statements:

Control Structures define the flow of execution of statements in a program. There are
three control structures namely:

1. Sequence statements
Statements are executed in sequence one after the other.
2. Selection or conditional Statements

Statement in the program which checks for the condition and accordingly executes some
statements or skips some statements.

3. Repetition or iterative statements

Statement in the program which checks for the condition and executes some statements
repetitively.

Conditional/Decision/Selection Statements:
The programming language C supports decision statements that checks the given condition
and accordingly transfers the control to the block of statements that are to be executed. The
programming language C supports different types of decision statements as listed below:
1. If statement/Null Else Statement/One Way Alternative Selection Statement
2. If –else statement/Dual Alternative/Two Way Selection Statement
3. If-else-if ladder statement/Multi Way Selection Statement
4. Switch( ) case statement/Multi Way Selection Statement
If statement:

It is one type of decision statement that checks for a given condition and transfers the
control to its immediate statement or block of statements if the condition is true otherwise transfers
the control to the next statement if any exists.

It takes the form as shown below:

If (condition)

Statement or block of statements;


Statement x;

From the above syntax, we say that if condition is true statement or block of statements is
executed otherwise statement x is executed if exists.

For e.g., given below is a program to check whether the candidate’s age is greater than 17
or not. If yes display message “eligible for voting”.

#include <stdio.h>
main()
{
int age;
clrscr();
printf(“enter age:”);
scanf(“%d”,&age);
if (age>17)
printf(“eligible for voting”);
}

Explanation: In the above program the if statement checks for the condition and if it is true it
executes its immediate statement otherwise nothing will be executed.
If –else statement:

It is one type of decision statement that checks for a given condition and transfers the
control to its immediate statement or block of statements if the condition is true otherwise transfers
the control to the else block of statements. Whether the condition is true or false it executes the
immediate statement after the if-else block.

It takes the form as shown below:

From the above syntax, we say that if condition is true , statement1 or block of statements
is executed otherwise statement2 or block of statements is executed and whether the condition is
true or false statement x is executed if exists.

For e.g., given below is a program that accepts three integer numbers and adds them and checks
whether the given number is in the range 100 -200 or not. Print separate message if it is in the
range or outside the range.

#include <stdio.h>
main()
{
int a,b,c,tot;
clrscr();
printf(“enter values for a,b,c:”);
scanf(“%d%d%d”,&a,&b,&c);
tot=a+b+c;
if ((tot>=100)&&(tot<=200))
printf(“is within the range”);
else
printf(“is not in the range”);
}
Explanation: In the above program the if statement checks for the condition and if it is true it
executes its immediate statement otherwise it executes the else part of the statement.

Note:

An if statement placed in another if statement is called as nested if statement.

An if – else statement placed either in the if (true) part or else (false) part or in both the
parts of an if-else statement is called as nested if-else statement.

For e.g., given below is a program that checks for the biggest of three numbers and displays the
message accordingly. This program makes use of nested if-else statement.

#include <stdio.h>
main()
{ /* beginning of main */
int a,b,c;
clrscr();
printf(“enter values for a,b,c:”);
scanf(“%d%d%d”,&a,&b,&c);
if (a>b)
{ /* beginning of if block */
if (a>c)
printf(“a is big”);
else
printf(“c is big”);
} /* end of if block */
else
{ /* beginning of else block */
if (b>c)
printf(“b is big”);
else
printf(“c is big”);
} /* end of else block */
} /* end of main */
Explanation: In the above program an if..else block is placed in both parts of an if-else
statement.

else-if ladder statement:

It is one type of decision statement that checks for a given condition and transfers the
control to its immediate statement or block of statements if the condition is true otherwise it
checks for the condition in the else part and transfers the control to the else block of statements if
25 | P r o g r a m m i n g a n d P r o b l e m S o l v i n g – U N I T 3
the condition is true and this process continues until there exists conditions in the else part and
finally if all conditions fail control is transferred to the last else block. Whether the condition is
true or false it executes the immediate statement after the if-else-if ladder block.

It takes the form as shown below:

if (condition)
true statement or block of statements;
else if (condition1)
statement1 or block1 of statements;
else if (condition2)
statement2 or block2 of statements;
else
statement 3 or block3 of statements;
statement x;

From the above syntax, we say that if condition is true , true statement or block of
statements is executed otherwise if condition1 becomes true then statement1 or block 1 of
statements are executed otherwise if condition2 becomes true then statement2 or block 2 of
statements are executed otherwise statement3 or block3 of statements are executed. whether the
condition is true or false statement x is executed if exists.

For e.g., given below is a program that accepts percentage of attendance and prints whether the
student falls under detain list or under condonation list or does not fall into any list.

Criteria for deciding the list :

Percentage of attendance Details

>=75 “No condonation”


>=65 and <75 “condonation”
<65 “detained”
#include <stdio.h>
main()
{ /* beginning of main */
int per;
clrscr();
printf(“enter percentage of attendance:”);
scanf(“%d”,&per);
if (per>=75)
printf(“No Condonation”);
else if ((per>=65) && (per<75))
printf(“Condonation”);
else
printf(“detained”);
} /* end of main */
Explanation: In the above program it first checks for the condition per>=75 and if it is true then
its immediate statement is executed otherwise the condition in the else part i.e., per>=65 and
per<75 is checked if it true then its immediate statement is executed otherwise the statement in the
last else is executed.

Switch Statement:

It is one type of decision statement that checks for a value and transfers the control to the
case statement that matches for the value otherwise transfers the control to the default statement
that is defined. The control is transferred to its immediate statement after the switch statement is
executed.

It takes the form as shown below:

switch(value/variable/expression)
{
case value:
statement 1;
break;
case value :
statement 2;
break;
default :
statement 3;
break;
}
statement x;
From the above syntax, we say that the switch statement transfers the control to its
respective case statement based on the value in the switch and executes the statements defined
for that corresponding case statement and transfers the control to statement x if any exists after the
switch statement.

For e.g., given below a program that illustrates the usage of switch statement

/* program showing switch statement /* program showing switch statement


accepting integer values */ accepting character values */
#include <stdio.h> #include <stdio.h>
main() main()
{ {
int num; char choice;
clrscr(); clrscr();
printf(“enter integer number :”); printf(“enter integer number :”);
scanf(“%d”,&num); cscanf(“%c”,&choice);
switch(num) switch(choice)
{ {
case 1: printf(“one\n”); case ‘o’:: printf(“one\n”);
break; break;
case 2: printf(“two\n”); case ‘t’: printf(“two\n”);
break; break;
case 4:printf(“four\n”); case ‘f’:printf(“four\n”);
break; break;
default: printf(“unknown\n”); default: printf(“unknown\n”);
break; break;
} }
printf(“bai\n”); printf(“bai\n”);
} }
/* program showing switch statement accepting character values and executing
statements if the character value is either in lower case or upper case*/
#include <stdio.h>
main()
{
char choice;
clrscr();
printf(“enter integer number :”);
cscanf(“%c”,&choice);
switch(choice)
{
case ‘O’:
case ‘o’: printf(“one\n”);
break;
case ‘T’:
case ‘t’: printf(“two\n”);
break;
case ‘F’:
case ‘f’:printf(“four\n”);
break;
default: printf(“unknown\n”);
break;
}
printf(“bai\n”);
}

Explanation: In all the above three programs switch statement receives the value and transfers the
control to the case statement that matches for the value in the switch statement and executes the
statements defined for that case and transfers the control to an immediate statement after the
switch.

Iteration Statements or Loops :


The programming language C supports Loop control statements that checks for a given
condition and repeats the statement or block of statements until the condition becomes false or for
a specific number of times. The programming language C supports different types of Loop Control
statements as listed below:

1. while loop
2. do..while loop
3. for loop.
For the successful execution of any of the loop listed above, the programmer should ensure that
the following statements are used without fail.

• Initialization of the test condition variable


• Checking the Test condition variable
• Manipulation of the test condition variable
Note: The absence of any of the statements listed above leads to the loops getting executed
infinitely or the execution becomes unsuccessful.

While loop or pretest loop Do..while loop or post test loop For loop or pre test loop
This looping statement This looping statement executes This looping statement checks for the
checks for the condition and the statement or block of condition and executes the statement or
executes the statement or statements at least once block of statements repetitively until the
block of statements irrespective of the condition and test condition is true.
repetitively until the test executes the block of statements
condition is true. repetitively until the test It is entry controlled loop
It is entry controlled loop condition is true Syntax of the loop with showing the
Syntax of the loop with It is exit controlled loop positions where the above statements are
showing the positions where Syntax of the loop with showing to be used.
the above statements are to be the positions where the above for(intiallization;condition;manipulation)
used. statements are to be used. {
Initialization Initialization
while(condition ) do }
{ {
manipulation statement manipulation statement
} }while(condition ); e.g..
/* program to print numbers 1 through
15 */
e.g.. e.g.. #include <stdio.h>
/* program to print numbers 1 /* program to print numbers 1 main( )
through 15 */ through 15 */ {
#include <stdio.h> #include <stdio.h> int num;
main( ) main( ) for(num=1;num<=15;num++)
{ { {
int num=1; int num=1; printf(“%3d”,num);
while(num<=15) do }
{ {
printf(“%3d”,num); printf(“%3d”,num); }/* end of main */
num++; num++;
} }while(num<=15);
}/* end of main */
}/* end of main */

In the above program the In the above program the In the above program the initialization for
initialization for the test initialization for the test the test condition variable is num=1 and
condition variable is num=1 condition variable is num=1 and the checking of the test conditionvariable
and the checking of the test the checking of the test condition is num<=15 and the manipulation
condition variable is variable is num<=15 and the statement for the test condition variable is
num<=15 and the manipulation statement for the num++ and the statement that gets
manipulation statement for test condition variable is num++ executed repetitively is
the test condition variable is and the statement that gets Printf(“%3d”,num);
num++ and the statement that executed repetitively is
gets executed repetitively is Printf(“%3d”,num); Note: for loop does not terminate with
Printf(“%3d”,num); semicolon.

Note: While loop does not Note: do..while loop terminates


terminate with semicolon. with semicolon.

INFINITE LOOPS:
A looping process in general, includes the following four steps:
• Setting of a counter
• Execution of the statements in the loop
• Testing of a condition for loop execution
• Incrementing the counter

Programmer failing to consider any one of the above steps definitely will end with
INFINITE LOOP, Which is otherwise executing the body of the loop again and again until
step are taken to terminate the loop by pressing CTRL+C OR CTRL+BREAK.

NESTED LOOPS:

A LOOP is NESTED if similar kind of structure exists. For eg., while within a while, do..while
within a do..while, for within a for.

JUMP Statements:
The programming language C supports statements that allow transferring control in loops and in
switch statement and in program. The statements are listed below:
• Break
• Continue
• Goto

Break statement Continue statement Goto statement
The break statement when used The continue statement when used in The goto statement when used in
in loops and switch statement loops transfers the control to the the program transfers the control
transfers the control to an beginning of the loop by skipping the from that statement to a statement
immediate statement after the statements that follow the continue prefixed with the label used in
loop or switch statement. statement and starts execution with goto. It takes the form
The break statement in loops the previous iteration. goto label;
should be used after a The continue statement in loops Label: statement x;
conditional statement and in should be used after a conditional The goto statement can be
switch statement after defining statement. It cannot be used in conditional or unconditional and
the executable statements for switch statement. can be used in any part of the
every case. As and when the continue statement program.
As and when the break is used in loops the statements that As and when the goto statement is
statement is used in loops or follow the continue statement are not used in program it transfers the
switch statement, the statements executed. control to a statement prefixed
that follow the break are not Representation: with that label.
executed. while(condition) Representation:
Representation: { Unconditional goto
while(condition) if (condition)
{ continue; goto label;
if (condition) } label : statement x;
break; where label can be a string
} do constant
{ conditional goto
do if (condition) if (condition)
{ continue; goto label;
if (condition) }while(condition);
break;
}while(condition);
label : statement x;
for( ; ; ) where label can be a string
for( ; ; ) { constant
{ if (condition) if the control is transferred from
if (condition) continue; goto statement to a label used
break; } below the goto statement then it is
} called as forward jump.
e.g., e.g., If the control is transferred from
#include <stdio.h> #include <stdio.h> goto statement to a label used
main() main() above the goto statement then it is
{ { called as backward jump.
int num,i=1; int num,i=1;
while(i<=15) while(i<=15) e.g.,
{ { #include <stdio.h>
printf(“enter number:”); printf(“enter number:”); main()
scanf(“%d”,&num); scanf(“%d”,&num); {
if (num<0) if (num<0) printf(“welcome”);
break; continue; goto end;
printf(“%3d”,num); printf(“%3d”,num); printf(“to”);
i++; i++; end: printf(“control statements”);
32 | P r o g r a m m i n g a n d P r o b l e m S o l v i n g – U N I T 3
} } }
} }

Explanation: Explanation: Explanation:


In the above program , in the In the above program , in the loop a In the above program , the goto
loop a number is read and number is read and checked for the statement transfers the control to a
checked for the condition if the condition if the number read is less statement prefixed with that label
number read is less than zero than zero then control is transferred to resulting in not executing the printf
then control is transferred the beginning of loop by skipping the statement printf(“to”).
outside the loop by skipping the statements that follow the continue
statements that follow the break statement and proceeds with previous
statement otherwise the printf iteration otherwise the printf
statement is executed and statement is executed and proceeds
proceeds with next iteration with next iteration until the condition
until the condition becomes becomes false.
false.

Array:

Array is a data structure which can store fixed-size sequential collection of elements of the same type.
Purpose of Array:
Instead of declaring individual variables, such as number0, number1, ..., and
number99, youdeclare one array variable such as numbers and use numbers[0], numbers[1],
and ..., numbers[99] to represent individual variables. A specific element in an array is
accessed by an index.
The lowest indexis always zero which corresponds to the first element/location and the highest
index(maximum size -1) refers to the last element/location.

Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the number of
elements required by an array as follows:
Data type arrayName[arraySize];

This is called a single-dimensional array. The arraySize must be an integer constant greater than zero
and type can be any valid C data type. For example, to declare a 10-element array called balance
of typedouble, use this statement:

double balance[10];

Now balance is avariable array which is sufficient to hold upto 10 double numbers.

Initializing Arrays
You can initialize array in C either one by one or using a single statement as follows:

double balance[5]={1000.0,2.0,3.4,7.0,50.0};

The number of values between braces { } can not be larger than the number of elements that we
declare forthe array between square brackets [ ].
Following is an example to assign a single element of the array:
balance[4]=50.0;

The above statement assigns element number 5th in the array with a value of 50.0. All arrays have
0 as theindex of their first element which is also called base index and last index of an array will be
total size of the array minus 1. Following is the pictorial representation of the same array we
discussed above:

Examples of array initialization:


Inputting Values using a for Loop

• Once we know the length of an array, we can input values using a


for loop: array name : scores[9], arrayLength = 9;

for (j = 0; j <arrayLength; j++)


{
scanf(“%d”, &scores[j]);
}//end for

Assigning Values to Individual Elements

• We can assign any value that reduces to an array’s data type:

scores[5] = 42;
scores[3] = 5 + 13;
scores[8] = x + y;
scores[0] = pow(7, 2);

“Copying” Arrays

• We cannot directly copy one array to another, even if they have the same length and
share the same data type.
• Instead, we can use a for loop to copy values:
for(m = 0; m < 25; m++)
{
array2[m] = array1[m];
}//end for

Swapping Array Elements

To swap (or exchange) values, we must use a temporary variable. A common novice’s mistake is
to try to assign elements to one another:
/*The following is a logic
error*/
numbers[3] = numbers[1];
numbers[1] = numbers[3];

/*A correct approach …*/


temp = numbers[3];
numbers[3] = numbers[1];
numbers[1] = temp;
Printing Array Elements

• To print an array’s contents, we would use a for loop:


for(k = 0; k < 9; k++)
{
printf(“%d”, scores[k];
}//end for

TWO DIMENSIONAL ARRAY


Declaring Two Dimensional Arrays
To declare a 2D array in C, a programmer specifies the type of the elements and the number of
elements required by an array as follows:
Data type arrayName [RowSize][colsize];

This is called a two-dimensional array. The RowSize, colsize must be an integer constant greater than zero
and type can be any valid C data type. For example, to declare a 10-element 2 D array called
balance oftype int, use this statement:
int balance[2][5]; or int balance[5][2];

Now balance is a variable array which is sufficient to hold upto 10 int numbers.
Initializing Arrays
You can initialize array in C either one by one or using a single statement as follows:
int balance[2][5]={10,1,2,3,4,50,6,7,80,99};

The number of values between braces { } can not be larger than the number of elements that we
declare forthe array between square brackets [ ].

Following is an example to assign a single element of the array:


balance[1][2]=22; /* to assign a value for the second row, third column */

Inputting Values using a for Loop

• Once we know the length of an array, we can input values using a


for loop: array name : matrix[3][3], arrayLength = 9;

for (i=0;i<3;i++)
for (j = 0; j <3; j++)
{
scanf(“%d”, &matrix[i][j]);
}//end for

“Copying” Arrays

We cannot directly copy one array to another, even if they have the same length and
share the same data type.
Instead, we can use for loop to copy values:
for (i=0;i<3;i++)
for (j = 0; j < 3; j++)
{
array2[i][j] = array1[i][j];
}//end for

Understanding the scope of Functions:


Scope:
Scope refers to the region of a program where a declared variable is visible.
C supports Global Scope and Local Scope.
• We declare Global Scope objects outside of a function; such variables are visible from
their declaration until the end of a program.
• We declare Local Scope objects inside a code block ({ … }); such objects are visible
from their declaration until the end of the block in which they’ve been declared.

Introduction to Top Down Design

• Top-down design is the Process of taking a larger problem, understanding it, and then
breaking it into smaller, more manageable parts.
• Each part, called a module, has its own well-refined task.
Function: Defined as self contained block of code to perform a task.
Functions can be categorized to system-defined functions and user-defined functions.

System defined functions: These are functions that are supported along with the programming language.
The block of instructions of these functions and the task to be performed is predefined. For e.g. clrscr(),
printf(), scanf(), pow(), sqrt() etc.

User defined functions: These are functions that are not supported along with the programming language.
The block of instructions of these functions and the task to be performed is defined by the programmer.

The following are the advantages of functions:


• Reusability of code i.e. block of code defined can be used when required.
• Facilitates Modular Programming i.e. breaking the complex problem into small manageable
sub-problems called as modules and also makes the process of debugging easier.
• Reduces the length of the program.

Important Terminologies:
Function call is the reference made in the calling function by specifying the name of the
function along with arguments if any exists and should be terminated with semicolon.
Calling function is the function in which we write function call statements.
Called function is the definition of function call

for e.g.

main() /* calling function */


{
clrscr(); /* function call */
}

Defining User defined functions:


To understand user-defined functions one should understand the following elements:
• Function definition
• Function declaration
• Function call
Function Definition: The function definition consists of two parts namely
1. Function header
2. Function body
The general format of the function definition is shown below:

Return type function-name(arguments) Function header


Argument declaration;
{ Function Body
Local variable declaration;
Executable statement1;
Executable statement 2;
Return statement;
}

Function Header:
The function header comprises of three parts namely
1. Return type
2. Function name
3. arguments

Return type: Specifies the type of data (primitive/user-defined) that the function will
return.
Function Name: Takes a valid name to identify the function and this name should follow
the rules for naming a user defined identifier.
Arguments: the values/variables that we receive from function call
Function body:
The function body comprises of the following parts enclosed in flower
Braces:
1. Local variable declaration
2. Executable statements
3. Return statement
Local variable declaration: Variables that are needed in that function are declared for
its type.
Executable Statements: These are statements that are needed in the function to assign a
value or to read a value or to print the value or to perform some computations.
Return statement: Every function body ends with return statement. This statement is
used to return a value to the calling function. If the function does not return any value
then the return statement is written as
Return; or return 0;
If the function returns any value then the return statement is written as
Return value; or return expression;
The function definition can be done either above the main function or after the main function.
Example of function definition:
float mul(x,y)
float x,y;
{
float result;
result=x*y;
return result;
}
In the above example in the function header the return type is float and the name of the function
In the function body, result is a variable that is needed in that function and is declared locally for
its type. Result=x*y is the executable statement and the return statement returns the value available in the
variable result.

Function Declaration or prototype declaration: Declaring a function also called as function prototyping
is used to inform the compiler about the specification of the function that will be defined and the syntax for
invoking the function call.
The general format of function declaration is given below:
Return type functionname(arguments);
Where arguments specify the type of data (primitive/user-defined) and each of these arguments should be
separated with comma.
The function declaration is done above the main function.
Example of function declaration:
float mul(float,float);
In the above example the return type is float and the name of the function is mul and the
arguments that should be passed to the function definition through function call should be of type float.

Function call: The function definition is invoked by referring the function name along with arguments if
any exists. The arguments in the function call, if exists will take data or variables declared for its type
matching to the function declaration and definition.
The arguments in the function are called as actual arguments.
The function call should be made always within another function.
The general format for function call which returns value is given below:

Variable=functionname(arguments);
Or
printf(“format string”,functionname(arguments));

Where arguments may or may not exist.


The general format for function call which does not return value is given below:

Functionname(arguments);

Where arguments may or may not exist.

Example of function call which returns values:


main()
{
float y;
y=mul(23.4,12.5); /* function call */
printf(“product of two numbers is %f\n”,y);
}

Example of function call which does not return value:

main()
{
mul(); /* function call */
}
/* complete program showing the usage of function declaration, function call and definition */

#include <stdio.h>

float mul(float,float); /* function declaration */

main()
{
float y;
y=mul(23.4,12.5); /* function call */
printf(“product of two numbers is %f\n”,y);
}
/* function definition
*/float mul(x,y)
float x,y; /* argument declaration */
{
float result; /* local variable declaration
*/result=x*y; /* executable statement */
return result; /* returns the computed value in result to the calling function */
}

Storage Class Specifiers:

In C language, each variable has a storage class which is used to define scope and life
time of a variable.

Storage: Any variable declared in a program can be stored either in memory or


registers. Registers are small amount of storage in CPU. The data stored in registers
has fast access compared to data stored in memory.

Storage class of a variable gives information about the location of the


variable in which it is stored, initial value of the variable, if storage class is not specified;
scope of the variable; life of the variable.

There are four storage classes in C programming.

1 : Automatic Storage class.

2 : Register Storage class.

3 : Static Storage class.

4 : External Storage class.

1: Automatic Storage class : To define a variable as automatic storage class, the keyword
„auto‟ is used. By defining a variable as automatic storage class, it is stored in the memory.
The default value of the variable will be garbage value. Scope of the variable is within the
block where it is defined and the life of the variable is until the control remains within the
block.

Syntax :

auto data_type variable_name;

auto int a,b;


Example:

void main()

int detail;

or

auto int detail; //Both are same

}
The variables a and b are declared as integer type and auto. The keyword
auto is not mandatory. Because the default storage class in C is auto.

Note: A variable declared inside a function without any storage class specification, is by
default an automatic variable. Automatic variables can also be called local variables
because they are local to a function.

Ex : void function1();

void function2(); OUTPUT

void main() 10

{ 0

int x=100; 100

function2();

printf(“%d”,x);

void function1()

int x=10;

printf(“%d”,x);

void function2()
{

int x=0;

function1();

printf(“%d”, x);

2: Register Storage class : To define a variable as register storage class, the keyword
„register‟ is used. If CPU cannot store the variables in CPU registers, then the variables are
assumed as auto and stored in the memory. When a variable is declared as register, it is
stored in the CPU registers. The default value of the variable will be garbage value.
Scope of the variable within the block where it is defined and the life of the variables is until
the control remains within the block.

Register variable has faster access than normal variable. Frequently used variables are kept
in register. Only few variables can be placed inside register.

NOTE : We can't get the address of register variable

Sytax : register data_type variable_name;

Ex: register int i;

Ex : void demo(); OUTPUT

void main() 20

{ 20

demo(); 20

demo();

demo();

void demo()

register int i=20;

printf(“%d\n”,i);

i++;

}
3 : Static Storage class : When a variable is declared as static, it is stored in the memory.
The default value of the variable will be zero. Scope of the variable is within the block
where it is defined and the life of the variable persists between different function calls. To
define a variable as static storage class, the keyword „static‟ is used. A static variable can
be initialized only once, it cannot be reinitialized.
Syntax : static data_type variable_name;
Ex: static int i;

Ex : void demo(); OUTPUT

void main() 20

{ 21

demo(); 22

demo();

demo();

void demo()

static int i=20;

printf(“%d”,i);

i++;

4 : External Storage class : When a variable is declared as extern, it is stored in the


memory. The default value is initialized to zero. The scope of the variable is global and the
life of the variable is until the program execution comes to an end. To define a variable as
external storage class, the keyword „extern‟ is used. An extern variable is also called as a
global variable. Global variables remain available throughout the entire program. One
important thing to remember about global variable is that their values can be changed by any
function in the program.

Systax : extern data_type variable_name;

extern int i;
Ex:
int number;

void main()

number=10;

fun1()

number=20;

fun2()

number=30;

Here the global variable number is available to all three functions.

Ex : void fun1();

void fun2();

int e=20;

void main()

fun1();

fun2();

void fun1()
{

extern int e;
printf(“e number is :%d”,e);

void fun2()

printf(“e number is :%d”,e);

extern keyword

The extern keyword is used before a variable to inform the compiler that this variable is
declared somewhere else. The extern declaration does not allocate storage for variables.

Problem when extern is not used

main()

a = 10; //Error:cannot find variable a

printf("%d",a);

Example Using extern in same file

main()

extern int x; //Tells compiler that it is defined somewhere else

x = 10;

printf("%d",x);

int x; //Global variable x


S. Storage Storage Initial / default Scope Life
No. Specifier place value
1 auto CPU Garbage value local Within the function only.
Memory
2 extern CPU Zero Global Till the end of the main program.
memory Variable definition might be
anywhere in the C program
3 static CPU Zero local Retains the value of the variable
memory between different function calls.
4 register Register Garbage value local Within the function
memory

Functions Arguments:
Arguments and parameters refer to the variables or expressions passed from the function. Each
and every argument is separated with comma.

Actual Arguments are arguments passed from function call.


Formal Arguments are arguments received in called function.

Actual Argument names and Formal Argument names can be same or different.
Actual Argument names are recognized only in that function.
Formal Argument names are recognized only in the definition of the function.
Example:
Sample(x1,y1)
Main() Int x1,y1;
{ {
intx,y; Formal Arguments
Actual Arguments
Sample(x,y);
} }
Call by Value Call by reference
Passing values/variables from function call. Passing address of the variable(s) from
function call.
Example: Example:
main() main()
{ {
int a,b; int a,b;
clrscr(); clrscr();
printf(“Enter the values of a and b:\n”); printf(“Enter the values of a and b:\n”);
scanf(“%d %d”,&a,&b); scanf(“%d %d”,&a,&b);

/* function call with arguments and no return /* function call with arguments and no return
value */ value */
swap(a,b); swap(&a,&b);

printf(“a=%d b=%d”,a,b); printf(“a=%d b=%d”,a,b);


} }

/* function definition with arguments and no /* function definition with arguments and no
return value */ return value */

void swap(a1, b1) void swap(a1, b1)


int a1,b1; int *a1,*b1;
{ {
int temp; int *temp;
temp=a1; *temp=*a1;
a1=b1; *a1=*b1;
b1=temp; *b1=*temp;
return 0; }
}

Categories of Functions (Based on the arguments and return

type)Functions fall into four categories as listed below:

1. Function with Arguments and with return value.


2. Function with Arguments and no return value.
3. Function with no arguments and with return value.
4. Function with no arguments and no return value.

Below we will see the comparative study of each of these categories of functions:
Function with Function with arguments Function with no arguments Function with no
Arguments and with and no return value and with return value arguments and no
return value return value

Description: Description: Description: Description:


Function call: Function call: Function call: Function call:
• Function call is made • Function call is made • Function call is made by • Function call is
by passing arguments by passing arguments passing no arguments made by passing no
• The function call is • The function call is arguments
assigned to a variable • Function call is not assigned to a variable that • Function call is not
that matches to the assigned to any variable matches to the return type assigned to any
return type of the or not used in printf of the function definition or variable or not used
function definition or function. used in the printf function in printf function.
used in the printf with format specifier
function with format matching to the return type
specifier matching to of the function definition.
the return type of the
Function Definition:
function definition. Function Definition:
Function Definition: Function Definition: • The function
• The function definition will definition will not
• The number of • The number of not receive any arguments.
arguments in the receive any
arguments in the • The return value should arguments.
function definition function definition
match with the return type • The return
should match with the should match with the
of the function definition. statement will not
number of arguments number of arguments
passed from the return any value.
passed from the Below shows an example of
function call. function call.
• The return statement how the programming Below shows an
• The return value
should match with the will not return any instruction changes for this example of how the
return type of the value. category of function. programming
function definition. instruction changes for
Below shows an example of this category of
Below shows an exampleof how the programming #include <stdio.h> function.
how the programming instruction changes for this
instruction changes for this category of function. /* function declaration*/
category of function. int printvalue(void);

#include <stdio.h> main()


{
/* function declaration*/ #include <stdio.h> #include <stdio.h>
int value;
int printvalue(int);
clrscr();
/* function declaration*/ /* function
/* function call */
main() void printvalue(int); declaration*/
value=printvalue();
{ void printvalue(void);
printf(“%d”,value);
int value; main()
}
clrscr(); { main()
/* function call */ {
clrscr(); /* function definition */
value=printvalue(10); /* function call */ int printvalue(void) clrscr();
printf(“%d”,value); printvalue(10); { /* function call */
} } int a; printvalue();
a=10; }
/* function definition */ return a;
int printvalue(a) }
int a; /* function definition */
{ void printvalue(a) /* function definition */
return a; int a; void printvalue(void)
} { {
printf(“%d”,a); int a;
return 0; a=10;
} printf(“%d”,a);
return 0;
}

The Return Statement:


It has two important uses.
➢ First, it causes an immediate exit from the function. That is, it causes program execution
to return to the calling code.
➢ Second, it can be used to return a value.
Returning from a Function
Functions rely on the return statement to stop execution either because a value must be returned
or to make a function's code simpler and more efficient.
Returning Values
All functions, except those of type void, return a value. This value is specified by the return
Statement.
Returning Pointers:

To return a pointer, a function must be declared as having a pointer return type

Passing an Array to a Function

If you want to pass a single-dimension array as an argument in a function, you would have to
declare a formal parameter in one of following three ways and all three declaration methods
produce similar results because each tells the compiler that an integer pointer is going to be
received. Similarly, you can pass multi-dimensional arrays as formal parameters.

1) Formal parameters as a pointer –


void myFunction(int *param) {
.
.
.
}
2) Formal parameters as a sized array –
void myFunction(int param[10]) {
.
.
.
}

3) Formal parameters as an unsized array −


void myFunction(int param[]) {
.
.
.

}
Example1: pass an entire array to a function argument
#include <stdio.h>
/* function declaration */
double getAverage(int arr[], int size);
int main () {
/* an int array with 5 elements */
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
/* pass pointer to the array as an argument */
avg = getAverage( balance, 5 ) ;
/* output the returned value */
printf( "Average value is: %f ", avg );
return 0;
}
double getAverage(int arr[], int size) {

int i;
double avg;
double sum = 0;

for (i = 0; i < size; ++i)


{
sum += arr[i];
}

avg = sum / size;

return avg;
}

Output
Average value is: 214.400000

Example2: pass an entire array to a function argument


#include <stdio.h>
myfuncn( int *var1, int var2)
{
for(int x=0; x<var2; x++)
{
printf("Value of var_arr[%d] is: %d \n", x, *var1);
/*increment pointer for next element fetch*/
var1++;
}
}
int main()
{
int var_arr[] = {11, 22, 33, 44, 55, 66, 77};
myfuncn(&var_arr, 7);
return 0;
}
Output
Value of var_arr[0] is: 11
Value of var_arr[1] is: 22
Value of var_arr[2] is: 33
Value of var_arr[3] is: 44
Value of var_arr[4] is: 55
Value of var_arr[5] is: 66
Value of var_arr[6] is: 77

Example: Call by value method –


#include <stdio.h>
disp( char ch)
{
printf("%c ", ch);
}
int main()
{
char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'I', 'j'};
for (int x=0; x<=10; x++)
{
/* passing each element one by one using subscript*/
disp (arr[x]);
}

return 0;
}
Output:
abcdefghij

In this method of calling a function, the actual arguments gets copied into formal
arguments. In this example actual argument(or parameter) is arr[x] and formal
parameter is ch.

Example: Call by reference method: Using pointers

#include <stdio.h>
disp( int *num)

printf("%d ", *num);

int main()

int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};

for (int i=0; i<=10; i++)

disp (&arr[i]);

return 0;
}

Output:

1234567890

String Library Functions:


The programming language C supports functions for performing operations on strings and these
functions are defined in the header file “string.h”. To use the string functions in your program
you have to include the header file “string.h”. Some of the string handling functions are listed
below:

String Handling Functions

C supports a large number of string handling functions in the standard library "string.h".

Few commonly used string handling functions are discussed below:


Function Work of Function

strlen() Calculates the length of string

strcpy() Copies a string to another string

strcat() Concatenates(joins) two strings

strcmp() Compares two string

strlwr() Converts string to lowercase

strupr() Converts string to uppercase

strcpy()
The strcpy() function is used to make a duplicate copy of the contents of the existing string or is
used to assign a string constant to the character array. The general form of the strcpy() function is
given below:
strcpy(string1,string2);

The strcpy() function takes two arguments named string1 and string2 where string1 should be a
character array declared of some size and string2 can be either string constant or a character
array initialized with string. The content of string2 is copied to string1.
Example:
#include <string.h>
main()
{
char coll_name[10]=”spmu”;
char dcoll_name[10];
strcpy(dcoll_name,coll_name);
printf(“%s”,dcoll_name);
}
Explanation:
In the above program when the strcpy() function gets executed then the contents of the character
array coll_name is copied to the character array named dcoll_name and as a result when printf is
executed it prints spmu.

strncpy()
The strncpy() function is used to copy first n characters from one string to another string. The
general form of the strncpy() function is given below:

strncpy(string1,string2,n);

for eg.
#include <string.h>
main()
{
char coll_name[10];
strcpy(coll_name,”spmu”,2);
coll_name[2]=’\0’;
printf(“%s”,coll_name);
}

Explanation:
In the above program when the strncpy() function gets executed then the first two characters of
the string constant “spmu” is copied to the character array named coll_name and in the next line
we are appending the character array named coll_name with null character(\0) to treat the
contents of the character array as string and as a result when printf is executed it prints sv.

strcat():

The strcat() function is used to append the contents of one string to another string.
strcat(string1,string2);

#include <string.h>
main()
{
char coll_name[15]=”spmu”;
char extension[10]=”colleges”;
strcat(coll_name,extension);
printf(“%s”,coll_name);
}
Explanation:
In the above program when the strcat() function gets executed then the contents of the character
array extension is added to the character array named coll_name and as a result when printf is
executed it prints spmu colleges.

Note: when strcat() function is used always the first argument which is a character array should
be declared of large size then the second argument.

strncat()
The strncat() function is used to append first n characters of one string to another string.
strncat(string1,string2,n);
#include <string.h>
main()
{
char coll_name[15]=”spmu”;
char extension[10]=”colleges”;
strncat(coll_name,extension,3); // concatenates 3 characters from second string to first string
strcat(coll_name,”\0”); // concatenates \0 character
printf(“%s”,coll_name);
}
Explanation:
In the above program when the strncat() function gets executed then the first three characters of
the character array extension is added to the character array named coll_name and in the next line
we are appending the character array named coll_name with null character(\0) to treat
the contents of the character array as string as a result when printf is executed it prints spmucol.

Note: when Strcat() function is used always the first argument which is a character array should
be declared of large size then the second argument.

strcmp()
The strcmp() function is used to compare the content of the two strings based on the ascii code
assigned for the contents of the strings.

Variable=strcmp(string1,string2);
For e.g.
#include <string.h>
main()
{
char coll_name[15]=”spmu”;
int diff;
diff=strcmp(coll_name,”abc”);
if (diff==0)
printf(“strings are equal\n”);
else if (diff<0)
printf(“string2 preceeds string1\n”);
else
printf(“string1 preceeds string2\n”);
}

Explanation:
In the above program, when the strcmp() function gets executed , it compares each and every
character of the two strings and returns the ASCII difference when the ASCII code of the
character is different.

strncmp()
The strncmp() function is used to compare the first n characters of the two strings based on the
ascii code assigned for the contents of the strings.

Variable=strncmp(string1,string2,n);

#include <string.h>
main()
{
char coll_name[15]=”spmu”;
char coll1[15]=”abc”;
int diff;
diff=strncmp(coll_name,coll1,1);
if (diff==0)
printf(“strings are equal\n”);
else if (diff<0)
printf(“string2 preceeds string1\n”);
else
printf(“string1 preceeds string2\n”);
}
Explanation:
In the above program when the strcmp() function gets executed then only the first character of
string1 is compared with first character of string2 and the ascii difference of these characters is
returned to the variable diff and prints the result string1preceeds string2.

strncmpi() or strnicmp()

This function is similar to strncmp() function except that it compares the strings by ignoring the
case.

strlen()

The strlen() function is used to find the length of the string.


Variable=strlen(string1);

#include <string.h>
main()
{
char coll_name[15]=”spmu”;
int len;
len=strlen(coll_name);
printf(“%d”,len);
}

Explanation:
In the above program when the strlen() function gets executed then the characters in the character
array are counted and the count is assigned to the variable len and as a result when printf is
executed it prints 4.
The exit() function:

▪ exit() is a predefined/ library function used to terminate the currently running


program(process) immediately.
Syntax: void exit(int status);

▪ status -> The status in an integer value returned to the parent process.
▪ Here 0 usually means program completed successfully, and nonzero values are used as
error codes. e.g exit(0);

Recursion:
The technique of any function that makes a call to itself is called as recursion.

/* program to find the factorial of a number using recursion */


#include <stdio.h>
main()
{
int x,f,fact(int);
clrscr();
printf(“enter a number:”);
scanf(“%d”,&x);
f=fact(x);
printf(“factorial of %d is %d\n”,x,f);
}

fact(m)
int m;
{
int f=1;
if (m==1)
return(1);
else
f=m*fact(m-1);
return f;
}

Important Questions:

1. Define a Variable. List the rules of an identifier. Give valid and invalid examples.
2. Explain the General structure of C program with a block diagram.
3. Define Data type. Explain the fundamental data types supported in C.
4. Define constant. Explain the different constants supported in C.
5. Write Precedence of Arithmetic Operators.
6. Define Precedence. Explain the precedence of Operators in C.
7. Define Expression. Briefly discuss about the types of expressions.
8. How Expressions are evaluated. Discuss.
9. What is type conversion? Explain.
10. Define Control Structures? Explain the different control structures supported in C.
11. Explain any two forms of Conditional Statements with examples.
12. How Entry Controlled Loop is different from exit controlled loop? Discuss with
examples.
13. Write short notes on break and continue statement.
14. How arrays are declared and initialized? Discuss with examples.
15. Briefly discuss the string handling functions supported in C.
16. Briefly discuss about storage classes.
17. Write a program in C to compute the factorial of a number.
18. Write a program in C to search for an element in a list.
19. Write a program in C to arrange elements in ascending order.
20. Write a program in C to print fibonanci series.
21. Write a program in C to print prime numbers between 1 and n.
22. Write a program in C to interchange two numbers.
23. Write a program in C to check whether a number is odd or even
24. Write a program in C to find the sum of n elements.
25. Write a program in C to illustrate arithmetic operators.
26. Write a program in C to compute matrix multiplication.

You might also like