Unit I
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:
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.
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
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:
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
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:
5
Provides support for numbers with integer and fractional part
Based on the size allocated we have float, double and long double
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.
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
7
76542LU 76542 unsigned 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
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
2001 address
Variable Declaration:
• A variable can be declared for a particular data type as shown below:
data_type variable_name;
8
• Multiple Variables can be declared for a particular data type as shown below:
data_type variable_name1,..variable_name n;
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?
Relational operators < (less than), <= (less than equal to),
> (greater than), >= (greater than equal to),
= = (equality), != (not equal to)
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.
Expr1? expr2:expr3 where if expr1 is true then expr2 is evaluated else expr3 is evaluated.
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.
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).
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
• Associativity
• Conversion rules
Precedence:
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:
() Function call
[] Array size
+ Unary plus
- Unary minus
++ Increment
-- Decrement
~ Complement
* Pointer operator
* Multiplication
% Modulo division
+ Addition
Left to right 4
- Subtraction
== Equality
Left to right 7
!= Not equal to
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:
In the above example, int is redefined as integer and float redefined as real.
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();
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);
}
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.
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
To read a string from the keyboard, if suppose, a character array is declared as shown below:
char college_name[25];
scanf(“%s”,college_name);
To read a string from the keyboard, if suppose, a character array is declared as shown below:
char college_name[25];
gets(college_name);
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);
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.
#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
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
#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 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.
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.
If (condition)
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.
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 – 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.
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.
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.
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.
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
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.
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.
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.
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
} } }
} }
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:
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
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];
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 [ ].
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
• 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.
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.
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));
Functionname(arguments);
main()
{
mul(); /* function call */
}
/* complete program showing the usage of function declaration, function call and definition */
#include <stdio.h>
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 */
}
In C language, each variable has a storage class which is used to define scope and life
time of a variable.
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 :
void main()
int detail;
or
}
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 main() 10
{ 0
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.
void main() 20
{ 20
demo(); 20
demo();
demo();
void demo()
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;
void main() 20
{ 21
demo(); 22
demo();
demo();
void demo()
printf(“%d”,i);
i++;
extern int i;
Ex:
int number;
void main()
number=10;
fun1()
number=20;
fun2()
number=30;
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()
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.
main()
printf("%d",a);
main()
x = 10;
printf("%d",x);
Functions Arguments:
Arguments and parameters refer to the variables or expressions passed from the function. Each
and every argument is separated with comma.
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);
/* function definition with arguments and no /* function definition with arguments and no
return value */ 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
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.
}
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;
return avg;
}
Output
Average value is: 214.400000
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.
#include <stdio.h>
disp( int *num)
int main()
disp (&arr[i]);
return 0;
}
Output:
1234567890
C supports a large number of string handling functions in the standard library "string.h".
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()
#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:
▪ 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.
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.