Study Note For C Programming
Study Note For C Programming
1. Course Overview:
Course Objectives: However, the process of learning a computer language will also be emphasized.
Emphasis is also on semantics and problem solving. C is a powerful, flexible, portable and elegantly
structured
After completing this course, programming language. Since C combines the features of high students
will be able to -level language with the elements of the assembler, it is suitable for both systems and
applications programming and is undoubtedly the most widely used general-purpose language today.
Unit Contents
1 Introduction to C language
Origins of C, Character Set of C, C Tokens, Keywords and Identifiers, Constants, Variables,
Data types,
Declaration of variables, Declaration of variables as constant, Operators, Types of operators,
Precedence and associativity, Expression, Type conversions in expressions, Input and Output
functions - printf(), scanf(), getchar(), putchar(), Formatted input and formatted output.
2 Decision Control and looping
Introduction, Control Statements- Sequential, Selection, Iteration Statements, branching
structure- if statement, if-else statement, Nested if-else statement, else if Ladder, Conditional
operator, switch statement, Loop control structures- while loop, do-while loop, for loop,
nested for loop, Jump statements-break, continue, go to
3 Functions
Introduction, Purpose of function, Function declaration/ Function prototype, Function
definition, Function call, return statement, Function parameters, Types of functions, Call by
value, Storage classes, Recursion, Examples on recursive function
4 Arrays and Strings
Introduction to one-dimensional Array, Definition, Declaration, Initialization, Accessing and
displaying array elements, Arrays and functions, Introduction to two-dimensional Array,
Definition, Declaration, Initialization, Accessing and displaying array elements, Introductions
to Strings, Definition, Declaration, Initialization, Input, output statements for strings,
Standard library functions, Implementations with standard library functions. Structures and
union Introduction to structure, defining a structure, declaring structure variables, accessing
structure members, nested structure, Array of structure, Array within structure, Introduction
to union, Definition, Declaration, Differentiate between structure and union. Pointers
Introduction to pointer, Definition, Declaring and Initializing pointer variable, Indirection
operator and address of operator, Accessing variable through its pointer, Pointer arithmetic,
Dynamic memory allocation, Pointers & Functions, Pointers & Array, Pointers & Structures.
Algorithms
1
Introduction to C language
Origins of C
Character Set of C
C Tokens, Keywords and Identifiers,
Constants, Variables, Data types,
Declaration of variables, Declaration of variables as constant,
Operators, Types of operators,
Precedence and associativity,
Expression, Type conversions in expressions,
Input and Output functions - printf(), scanf(), getchar(), putchar(), • Formatted input and formatted
output.
Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on
the DEC PDP-11 computer in 1972.
In 1978, Brian Kernighan and Dennis Ritchie produced the first publicly available description of C, now known
as the K&R standard.
The UNIX operating system, the C compiler, and essentially all UNIX application programs have been written
in C. C has now become a widely used professional language for various reasons −
• Easy to learn
• Structured language
• It produces efficient programs
• It can handle low-level activities
• It can be compiled on a variety of computer platforms
Facts about C
• C was invented to write an operating system called UNIX.
• The language was formalized in 1988 by the American National Standard Institute (ANSI).
• Today C is the most widely used and popular System Programming Language.
• Today's most popular Linux OS and RDBMS MySQL have been written in C.
2
Why use C?
C was initially used for system development work, particularly the programs that make-up the operating
system. C was adopted as a system development language because it produces code that runs nearly as fast
as the code written in assembly language. Some examples of the use of C might be −
• Operating Systems
• Language Compilers
• Assemblers
• Text Editors
• Print Spoolers
• Network Drivers
• Modern Programs
• Databases
• Language Interpreters
• Utilities
•
• Pre-processor Commands
• Functions
• Variables
• Statements & Expressions
• Comments
Let us look at a simple code that would print the words "Hello World" −
#include<stdio.h>
int main()
/* my first program in C */
return 0;
3
Let us take a look at the various parts of the above program −
• The first line of the program #include <stdio.h> is a pre-processor command, which tells a C compiler
to include stdio.h file before going to actual compilation.
• The next line int main() is the main function where the program execution begins.
• The next line /*...*/ will be ignored by the compiler and it has been put to add additional comments
in the program. So such lines are called comments in the program.
• The next line printf(...) is another function available in C which causes the message "Hello, World!" to
be displayed on the screen.
• The next line return 0; terminates the main() function and returns the value 0.
Tokens in C
A C program consists of various tokens and a token is either a keyword, an identifier, a constant, a string
literal, or a symbol. For example, the following C statement consists of five tokens −
printf
);
Semicolons
In a C program, the semicolon is a statement terminator. That is, each individual statement must be ended
with a semicolon. It indicates the end of one logical entity.
/* my first program in C */
You cannot have comments within comments, and they do not occur within a string or character literals.
4
Identifiers
A C identifier is a name used to identify a variable, function, or any other user-defined item. An identifier
starts with a letter A to Z, a to z, or an underscore '_' followed by zero or more letters, underscores, and
digits (0 to 9).
C does not allow punctuation characters such as @, $, and % within identifiers. C is a case sensitive
programming language. Thus, Manpower and manpower are two different identifiers in C. Here are some
examples of acceptable identifiers −
Keywords
The following list shows the reserved words in C. These reserved words may not be used as constants or
variables or any other identifier names.
auto Else Long switch
break Enum Registe typedef
r
case extern Return union
char Float Short unsigned
const For Signed void
continue Goto Sizeof volatile
default If Static while
do Int Struct _Packed
double
Whitespace in C
A line containing only whitespace, possibly with a comment, is known as a blank line, and a C compiler totally
ignores it.
Whitespace is the term used in C to describe blanks, tabs, newline characters and comments. Whitespace
separates one part of a statement from another and enables the compiler to identify where one element in
a statement, such as int, ends and the next element begins. Therefore, in the following statement −
int age;
there must be at least one whitespace character (usually a space) between int and age for the compiler to be
able to distinguish them. On the other hand, in the following statement −
no whitespace characters are necessary between fruit and =, or between = and apples, although you are free
to include some if you wish to increase readability.
5
C - Data Types
Data types in c refer to an extensive system used for declaring variables or functions of different types. The
type of a variable determines how much space it occupies in storage and how the bit pattern stored is
interpreted.
1
Basic Types
They are arithmetic types and are further classified into: (a) integer types and (b)
floating-point types.
2 Enumerated types
They are again arithmetic types and they are used to define variables that can only
assign certain discrete integer values throughout the program.
3
The type void
The type specifier void indicates that no value is available.
4 Derived types
They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types
and (e) Function types.
The array types and structure types are referred collectively as the aggregate types. The type of a function
specifies the type of the function's return value. We will see the basic types in the following section, where as
other types will be covered in the upcoming chapters.
Integer Types
The following table provides the details of standard integer types with their storage sizes and value ranges
−
Type Storage size Value range
char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
6
#include<stdio.h> #include<limits.h> int main(){
return 0;
When you compile and execute the above program, it produces the following result on Linux −
The header file float.h defines macros that allow you to use these values and other details about the binary
representation of real numbers in your programs. The following example prints the storage space taken by
a float type and its range values −
#include<stdio.h>
#include<float.h>
int main()
printf("Storage size for float : %d \n",sizeof(float)); printf("Minimum float positive value: %E\n", FLT_MIN );
printf("Maximum float positive value: %E\n", FLT_MAX ); printf("Precision value: %d\n", FLT_DIG );
return0;
When you compile and execute the above program, it produces the following result on Linux −
7
The void Type
The void type specifies that no value is available. It is used in three kinds of situations −
3 Pointers to void
A pointer of type void * represents the address of an object, but not its type. For
example, a memory allocation function void *malloc( size_t size ); returns a pointer
to void which can be casted to any data type.
C - Variables
A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable
in C has a specific type, which determines the size and layout of the variable's memory; the range of values
that can be stored within that memory; and the set of operations that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character. It must begin with
either a letter or an underscore. Upper and lowercase letters are distinct because C is case-sensitive. Based
on the basic types explained in the previous chapter, there will be the following basic variable types −
Variable Definition in C
A variable definition tells the compiler where and how much storage to create for the variable. A variable
definition specifies a data type and contains a list of one or more variables of that type as follows −
8
Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any user-defined
object; and variable_list may consist of one or more identifier names separated by commas. Some valid
declarations are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler to create variables
named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal
sign followed by a constant expression as follows −
Variable Declaration in C
A variable declaration provides assurance to the compiler that there exists a variable with the given type
and name so that the compiler can proceed for further compilation without requiring the complete detail
about the variable. A variable definition has its meaning at the time of compilation only, the compiler needs
actual variable definition at the time of linking the program.
A variable declaration is useful when you are using multiple files and you define your variable in one of the
files which will be available at the time of linking of the program. You will use the keyword extern to
declare a variable at any place. Though you can declare a variable multiple time in your C program, it can
be defined only once in a file, a function, or a block of code.
Example
Try the following example, where variables have been declared at the top, but they have been defined and
initialized inside the main function −
9
#include<stdio.h> //
Variable declaration:
Extern int a, b;
extern int c;
extern float f;
int main ()
{
/* variable definition: */
int a, b; int c; float f;
/* actual initialization */
a =10; b =20; c = a+b;
printf("value of c : %d \n", c);
f=70.0/3.0;
printf("value of f : %f \n", f); return
0;
}When the above code is compiled and executed, it produces the following result −
10
// function definition int
func()
{
return0;
}
Lvalues and Rvalues in C
There are two kinds of expressions in C −
• lvalue − Expressions that refer to a memory location are called "lvalue"
expressions. An lvalue may appear as either the left-hand or right-hand
side of an assignment.
• rvalue − The term rvalue refers to a data value that is stored at some
address in memory. An rvalue is an expression that cannot have a value
assigned to it which means an rvalue may appear on the right-hand side
but not on the left-hand side of an assignment.
Variables are lvalues and so they may appear on the left-hand side of an
assignment. Numeric literals are rvalues and so they may not be assigned and
cannot appear on the left-hand side. Take a look at the following valid and invalid
statements −
11
An integer literal can also have a suffix that is a combination of U and L, for unsigned and
long, respectively.
The suffix can be uppercase or lowercase and can be in any order.
Here are some examples of integer literals −
212 /* Legal */
215u /* Legal */
0xFeeL /* Legal */
078 /* Illegal: 8 is not an octal digit */
032UU /* Illegal: cannot repeat a suffix */
Following are other examples of various types of integer literals −
85 /* decimal */
0213 /* octal */
0x4b /* hexadecimal */
30 /* int */
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */
Floating-point Literals
A floating-point literal has an integer part, a decimal point, a fractional part, and
an exponent part. You can represent floating point literals either in decimal form
or exponential form.
While representing decimal form, you must include the decimal point, the exponent, or
both; and while representing exponential form, you must include the integer part, the
fractional part, or both. The signed exponent is introduced by e or E.
Here are some examples of floating-point literals −
3.14159 /* Legal */
314159E-5L /* Legal */
510E /* Illegal: incomplete exponent */
210f /* Illegal: no decimal or exponent */
.e55 /* Illegal: missing integer or fraction */
12
Character Constants
Character literals are enclosed in single quotes, e.g., 'x' can be stored in a simple variable of
char type.
A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a
universal character (e.g., '\u02C0').
There are certain characters in C that represent special meaning when preceded by a backslash
for example, newline (\n) or tab (\t).
Here, you have a list of such escape sequence codes −
printf("Hello\tWorld\n\n"); return0;
}
When the above code is compiled and executed, it produces the following result −
Hello World
String Literals
String literals or constants are enclosed in double quotes "". A string contains characters that
are similar to character literals: plain characters, escape sequences, and universal characters.
You can break a long line into multiple lines using string literals and separating them using
white spaces.
Here are some examples of string literals. All the three forms are identical strings.
"hello, dear"
"hello, \
dear"
"hello, " "d" "ear"
Defining Constants
There are two simple ways in C to define constants −
• Using #define preprocessor.
• Using const keyword.
13
The #define Preprocessor
Given below is the form to use #define preprocessor to define a constant −
#include<stdio.h>
#define LENGTH 10
#defineWIDTH 5
When the above code is compiled and executed, it produces the following result −
value of area : 50
The const Keyword
You can use const prefix to declare constants with a specific type as follows −
14
#include<stdio.h>
int main()
Const int LENGTH=10; const int WIDTH=5; const char NEWLINE ='\n';
int area;
printf("%c", NEWLINE);
return 0.
}
When the above code is compiled and executed, it produces the following result −
value of area: 50
Note that it is a good programming practice to define constants in CAPITALS.
C - Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions. C language is rich in built-in operators and provides the following types of operators
−
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators
We will, in this chapter, look into the way each operator works.
Arithmetic Operators
15
The following table shows all the arithmetic operators supported by the C language. Assume variable A holds
10 and variable B holds 20 then −
Show Examples
Relational Operators
The following table shows all the relational operators supported by C. Assume variable A holds 10 and variable
B holds 20 then −
B
== Checks if the values of two operands are equal or not. If yes, then the (A == B) is not
condition becomes true. true.
!= Checks if the values of two operands are equal or not. If the values are not (A!= B) is true.
equal, then the condition becomes true.
> Checks if the value of left operand is greater than the value of right (A > B) is not
operand. If yes, then the condition becomes true. true.
< Checks if the value of left operand is less than the value of right operand. If (A < B) is true.
yes, then the condition becomes true.
>= Checks if the value of left operand is greater than or equal to the value of (A >= B) is not
right operand. If yes, then the condition becomes true. true.
<= Checks if the value of left operand is less than or equal to the value of right (A <= B) is
operand. If yes, then the condition becomes true. true.
16
Logical Operators
Following table shows all the logical operators supported by C language. Assume variable A holds 1 and
variable B holds 0, then −
Show Examples
&& Called Logical AND operator. If both the operands are non-zero, then the (A && B) is false.
condition becomes true.
|| Called Logical OR Operator. If any of the two operands is non-zero, then (A || B) is true.
the condition becomes true.
! Called Logical NOT Operator. It is used to reverse the logical state of its !(A && B) is true.
operand. If a condition is true, then Logical NOT operator will make it
false.
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ is as follows
−
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume A = 60 and B = 13 in binary format, they will be as follows −
A = 0011 1100
B = 0000 1101
~A = 1100 0011
The following table lists the bitwise operators supported by C. Assume variable 'A' holds 60 and variable 'B'
holds 13, then –
17
Show Examples
& Binary AND Operator copies a bit to the result if it exists in (A & B) = 12, i.e., 0000 1100
both operands.
| Binary OR Operator copies a bit if it exists in either operand. (A | B) = 61, i.e., 0011 1101
^ Binary XOR Operator copies the bit if it is set in one operand (A ^ B) = 49, i.e., 0011 0001
but not both.
~ Binary Ones Complement Operator is unary and has the (~A ) = -60, i.e,. 1100 0100 in
effect of 'flipping' bits. 2's complement form.
<< Binary Left Shift Operator. The left operands value is moved A << 2 = 240 i.e., 1111 0000
left by the number of bits specified by the right operand.
>> Binary Right Shift Operator. The left operands value is A >> 2 = 15 i.e., 0000 1111
moved right by the number of bits specified by the right
operand.
Assignment Operators
The following table lists the assignment operators supported by the C language −
Show Examples
18
/= Divide AND assignment operator. It divides the left C /= A is equivalent to C = C / A
operand with the right operand and assigns the result
to the left operand.
Show Examples
sizeof() Returns the size of a variable. sizeof(a), where a is integer, will return 4.
& Returns the address of a variable. &a; returns the actual address of the variable.
Operators Precedence in C
Operator precedence determines the grouping of terms in an expression and decides how an expression is
evaluated. Certain operators have higher precedence than others; for example, the multiplication operator
has a higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence than +,
so it first gets multiplied with 3*2 and then adds into 7.
19
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at
the bottom. Within an expression, higher precedence operators will be evaluated first.
Show Examples
Expressions:
• Expressions is a sequence of operators and operands that specifies computation of a value. An expression
may consist of single entity or some combination of such entities interconnected by one or more operators.
• All expression represents a logical connection that’s either true or false.
• Thus, logical type expression represents numerical quantities.
In C every expression evaluates to a value i.e., every expression results in some value of a certain type that
can be assigned to a variable. Some examples of expression are shown in the table given below.
20
A+b
3.14*r*r
a*a+2*a*b+b*b
EXAMPLE
1 #include<stdio.h>
2 #include<conio.h>
3 int main()
4 {
5 int a=123 , b;
6 b=a+2;
7 clrscr();
8 printf(“Value of a = %d\n”,a);
9 printf(“Value of b =%d”,b);
10 getch();
11 return 0;
12 }
Output:
Value of a = 123
Value of b = 125
C - Type Casting
Type casting is a way to convert a variable from one data type to another data type. For example, if you
want to store a 'long' value into a simple integer then you can type cast 'long' to 'int'. You can convert the
values from one type to another explicitly using the cast operator as follows −
(type_name) expression
Consider the following example where the cast operator causes the division of one integer variable by another
to be performed as a floating-point operation −
#include<stdio.h>
main()
21
double mean;
}
When the above code is compiled and executed, it produces the following result −
Type conversions can be implicit which is performed by the compiler automatically, or it can be specified
explicitly through the use of the cast operator. It is considered good programming practice to use the cast
operator whenever type conversions are necessary.
Integer Promotion
Integer promotion is the process by which values of integer type "smaller" than int or unsigned int are
converted either to int or unsigned int. Consider an example of adding a character with an integer −
#include<stdio.h>
main()
%d\n", sum );
When the above code is compiled and executed, it produces the following result −
22
The usual arithmetic conversions are not performed for the assignment operators, nor for the logical
operators && and ||. Let us take the following example to understand the concept −
#include<stdio.h> main(){
int i=17; char c ='c';/* ascii value is 99 */
float sum; sum= i + c; printf("Value of sum : %f\n", sum );
}
When the above code is compiled and executed, it produces the following result −
23
Input and output functions
Puts
Scanf() :
• The format string must be a text enclosed in double quotes. It contains the information for
interpreting the entire data for connecting it into internal representation in memory. Example:
integer (%d) , float (%f) , character (%c) or string (%s).
• The argument list contains a list of variables each preceded by the address list and separated by
comma.
• The number of argument is not fixed; however corresponding to each argument there should be a
format specifier. Inside the format string the number of argument should tally with the number of
format specifier.
if i is an integer and j is a floating-point number, to input these two numbers we may use
#include<stdio.h>
#include<conio.h>
int main()
{
char a;
24
int b;
float c;
double d;
clrscr();
printf(“Enter a character \n”);
scanf(“%c”,&a);
printf(“Enter an Integer \n”);
scanf(“%d”,&b);
printf(“Enter a SP float no: \n”);
scanf(“%f”,&c);
printf(“Enter a DP float no : \n”);
scanf(“%if”,&d);
getch();
return 0; }
Enter a character
X
Enter an integer
6
Enter a SP float no
3.140000
Enter a DP float no
15 3.1400000e+10
Getchar() :
getchar() function will accept a character from the console or from a file, displays immediately while typing and
we need to press Enter key for proceeding.
Syntax :
int getchar(void);
It returns the unsigned char that they [Link] end-of-file or an error is encountered it return EOF.
This function reads a single character from the standard input device, the keyboard being assumed because that
is the standard input device, and assigns it to the variable “a”.
C – EXAMPLE PROGRAM:
#include<stdio.h>
#include<conio.h>
intmain()
{
chara;
clrscr();
printf(“Enteracharacter\n”);
a=getchar();
printf(“Given character is%c\n”,a);
25
getch();
return0;
}
Gets :
Gets function is used to scan a line of text from a standard input device. This function will be terminated by
a newline character. The newline character won’t be included as part of the string. The string may include
white space characters.
Syntax :
This function is declared in the header file stdio.h. It takes a single argument. The argument must be a data item
representing a string. On successful completion, shall return a pointer to string s.
C – EXAMPLE PROGRAM :
#include<stdio.h>
#include<conio.h>
intmain()
char*str;
clrscr();
printf(“Enterastring\n”);
gets(str);
getch();
return0;
Output:
Enter a string
Good morning
Given string is Good morning
26
Printf :
The usually used output statement is printf (). It is one of the library functions.
Format string may be a collection of escape sequence or/and conversion specification or/and string constant.
The format string directs this function to display the entire text enclosed within the double quotes without
any change.
Escape sequence:
Escape sequence is a pair of character. The first letter is a slash followed by a character. Escape sequence
help us to represent within the format string invisible and non-printed character although there are
physically two characters in any escape sequence. It represents only one. The various escape sequences
are
character Meaning
27
%e Data item is displayed as a floating-point value with an exponent.
#include<stdio.h>
#include<conio.h>
intmain()
{
char a=’x’;
int b=10;
float c=3.14;
doubled=3.14e+10;
clrscr();
printf(“Charactera=%c\n”,a);
printf(“Integerb=%d\n”b);
printf(“SP floatno:c=%f\n”,c);
printf(“DP floatno:d=%e\n”,d);
getch();
return0;
}
Output :
Character a= x
Integer b= 10;
SP float no : 3.140000
DP float : 3.140000e+10
28
Unit-2 Decision Control and looping
Introduction, Control Statements- Sequential, Selection, Iteration Statements, Branching structure- if
statement, if-else statement, Nested if-else statement, else if Ladder, Conditional operator, switch statement,
Loop control structures- while loop, do-while loop, for loop, Nested for loop, Jump statements-break,
continue, go to
C - Decision Making
Decision making structures require that the programmer specifies one or more conditions to be evaluated
or tested by the program, along with a statement or statements to be executed if the condition is determined
to be true, and optionally, other statements to be executed if the condition is determined to be false.
Show below is the general form of a typical decision-making structure found in most of the programming
languages −
C programming language assumes any non-zero and non-null values as true, and if it is either zero or null,
then it is assumed as false value.
1 if statement
An if statement consists of a boolean expression followed by one or more statements.
2 if...else statement
29
3 nested if statements
You can use one if or else if statement inside another if or else if statement(s).
4 switch statement
A switch statement allows a variable to be tested for equality against a list of values.
Syntax
The syntax of an 'if' statement in C programming language is −
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
If the Boolean expression evaluates to true, then the block of code inside the 'if' statement will be executed.
If the Boolean expression evaluates to false, then the first set of code after the end of the 'if' statement (after
the closing curly brace) will be executed.
C programming language assumes any non-zero and non-null values as true and
Flow Diagram
30
Example
main () {
a = 10;
a < 20 ) {
return 0;
When the above code is compiled and executed, it produces the following result −
C - if...else statement
An if statement can be followed by an optional else statement, which executes when the Boolean expression
is false.
Syntax
The syntax of an if...else statement in C programming language is −
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
else
{
/* statement(s) will execute if the boolean expression is false */
}
If the Boolean expression evaluates to true, then the if block will be executed, otherwise, the else block will
be executed.
31
C programming language assumes any non-zero and non-null values as true, and if it is either
zero or null, then it is assumed as false value. Flow Diagram
Example
#include<stdio.h> int
main (){
a =100;
a <20){
}else{
} printf("value of a is : %d\n",
a); return0;
32
When the above code is compiled and executed, it produces the following result −
When using if...else if..else statements, there are few points to keep in mind −
• An if can have zero or one else's and it must come after any else if's.
• An if can have zero to many else if's and they must come before the else.
• Once an else if succeeds, none of the remaining else if's or else's will be tested.
Syntax
The syntax of an if...else if...else statement in C programming language is −
if(boolean_expression 1) {
/* Executes when the boolean expression 1 is true */
} else if( boolean_expression 2) {
/* Executes when the boolean expression 2 is true */ }
else if( boolean_expression 3) {
/* Executes when the boolean expression 3 is true */ }
else {
/* executes when the none of the above condition is true */ }
Example
#include<stdio.h> int
main ()
if( a ==10)
printf("Value of a is 10\n");
33
}
elseif( a ==20)
printf("Value of a is 20\n");
}elseif( a ==30)
of a is 30\n");
}else
return0;
When the above code is compiled and executed, it produces the following result −
C - Nested if statements
It is always legal in C programming to nest if-else statements, which means you can use one if or else if
statement inside another if or else if statement(s).
Syntax
The syntax for a nested if statement is as follows –
34
if( boolean_expression 1)
{
Example
main ()
a == 100 )
if( b == 200 )
} }
35
C - Switch statement
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a
case, and the variable being switched on is checked for each switch case.
Syntax
The syntax for a switch statement in C programming language is as follows −
switch(expression){ case
constant-expression :
statement(s);
break;/* optional */
break;
/* optional */
}
The following rules apply to a switch statement −
• The expression used in a switch statement must have an integral or enumerated type, or be of a class
type in which the class has a single conversion function to an integral or enumerated type.
• You can have any number of case statements within a switch. Each case is followed by the value to be
compared to and a colon.
• The constant-expression for a case must be the same data type as the variable in the switch, and it
must be a constant or a literal.
• When the variable being switched on is equal to a case, the statements following that case will execute
until a break statement is reached.
• When a break statement is reached, the switch terminates, and the flow of control jumps to the next
line following the switch statement.
• Not every case needs to contain a break. If no break appears, the flow of control will fall through to
subsequent cases until a break is reached.
• A switch statement can have an optional default case, which must appear at the end of the switch.
The default case can be used for performing a task when none of the cases is true. No break is needed
in the default case.
36
Flow Diagram
Example
#include<stdio.h>
int main ()
switch(grade)
{ case'A':
printf("Excellent!\n");
break;
case'B':
break; case'D':
printf("You passed\n");
37
break; case'F':
printf("Better try
again\n"); break;
default:
printf("Invalid grade\n");
grade ); return 0;
When the above code is compiled and executed, it produces the following result −
Well done
Your grade is B
Syntax
The syntax for a nested switch statement is as follows −
switch(ch1)
{
case 'A':
printf("This A is part of outer switch" );
switch(ch2)
{ case 'A':
printf("This A is part of inner switch" );
break;
case 'B': /* case code */
}
break;
case 'B': /* case code */
}
Example
38
#include<stdio.h>
int main ()
{
/* local variable definition */
int a =100; int b =200;
switch(a)
{
case100: printf("This is part of outer switch\n", a );
switch(b)
{
case200: printf("This is part of inner switch\n", a );
}}
printf("Exact value of a is : %d\n", a );
printf("Exact value of b is : %d\n", b );
return0;}
When the above code is compiled and executed, it produces the following result −
The ?: Operator
We have covered conditional operator? In the previous chapter which can be used to replace
• Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire?
expression.
• If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression.
C - Loops
You may encounter situations, when a block of code needs to be executed several number of times. In
general, statements are executed sequentially: The first statement in a function is executed first, followed
by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
39
A loop statement allows us to execute a statement or group of statements multiple times. Given below is the
general form of a loop statement in most of the programming languages −
C programming language provides the following types of loops to handle looping requirements.
1 while loop
Repeats a statement or group of statements while a given condition is true. It tests the
condition before executing the loop body.
2 for loop
Executes a sequence of statements multiple times and abbreviates the code that manages
the loop variable.
3 do...while loop
It is more like a while statement, except that it tests the condition at the end of the loop
body.
4 nested loops
You can use one or more loops inside any other while, for, or do..while loop.
40
[Link]. Control Statement & Description
1 break statement
Terminates the loop or switch statement and transfers execution to the statement
immediately following the loop or switch.
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition
prior to reiterating.
3 goto statement
Transfers control to the labeled statement.
The Infinite Loop
A loop becomes an infinite loop if a condition never becomes false. The for loop is traditionally used for this
purpose. Since none of the three expressions that form the 'for' loop are required, you can make an endless
loop by leaving the conditional expression empty.
#include<stdio.h>
int main (){ for(;;){
printf("This loop
will run
forever.\n");
}return0;
}
When the conditional expression is absent, it is assumed to be true. You may have an initialization and
increment expression, but C programmers more commonly use the for (;;) construct to signify an infinite
loop.
While loop in C
A while loop in C programming repeatedly executes a target statement as long as a given condition is true.
Syntax
The syntax of a while loop in C programming language is −
While (condition)
{
Statement;
}
Here, statement(s) may be a single statement or a block of statements. The condition may be any expression,
and true is any nonzero value. The loop iterates while the condition is true.
41
When the condition becomes false, the program control passes to the line immediately following the loop.
Flow Diagram
Here, the key point to note is that a while loop might not execute at all. When the condition is tested and the
result is false, the loop body will be skipped and the first statement after the while loop will be executed.
Example
#include<stdio.h> int
main (){
/* local variable definition */ int
a =10;
/* while loop execution */
while( a <20)
{
printf("value of a: %d\n", a);
a++;
} return0;
}
When the above code is compiled and executed, it produces the following result −
42
For loop in C
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a
specific number of times.
Syntax
The syntax of a for loop in C programming language is −
statement(s);
}
Here is the flow of control in a 'for' loop −
• The init step is executed first, and only once. This step allows you to declare and initialize any loop
control variables. You are not required to put a statement here, as long as a semicolon appears.
• Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body
of the loop does not execute and the flow of control jumps to the next statement just after the 'for'
loop.
• After the body of the 'for' loop executes, the flow of control jumps back up to the increment
statement. This statement allows you to update any loop control variables. This statement can be
left blank, as long as a semicolon appears after the condition.
• The condition is now evaluated again. If it is true, the loop executes and the process repeats itself
(body of loop, then increment step, and then again condition). After the condition becomes false,
the 'for' loop terminates.
Flow Diagram
43
Example
#include<stdio.
h> int main ()
{
int a;
/* for loop
execution */
for( a =10; a <20; a = a +1)
{
printf("value of a: %d\n", a);
}
return;
}
44
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Do...while loop in C
Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop in C
programming checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at least one time.
Syntax
The syntax of a do...while loop in C programming language is −
do
{
statement(s);
} while( condition );
Notice that the conditional expression appears at the end of the loop, so the statement(s) in
the loop executes once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the
loop executes again. This process repeats until the given condition becomes false. Flow
Diagram
45
Example
#include<stdio.h> int
main ()
int a =10;
/* do loop execution */
Do
a = a +1;
}while( a <20);
return0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11 value
of a: 12 value of a:
13 value of a: 14
value of a: 15
value of a: 16
value of a: 17
46
value of a: 18
value of a: 19
Nested loops in C
r loop. The following section shows a few examples to illustrate the concept.
Syntax
The syntax for a nested for loop statement in C is as follows −
while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}
The syntax for a nested do...while loop statement in C programming language is as follows −
do
{
statement(s);
do
{
statement(s);
}while( condition );
}while( condition );
47
A final note on loop nesting is that you can put any type of loop inside any other type of loop. For example, a
'for' loop can be inside a 'while' loop or vice versa.
Example
The following program uses a nested for loop to find the prime numbers from 2 to 100 −
Break statement in C
The break statement in C programming has the following two usages −
• When a break statement is encountered inside a loop, the loop is immediately terminated, and the
program control resumes at the next statement following the loop.
• It can be used to terminate a case in the switch statement (covered in the next chapter).
If you are using nested loops, the break statement will stop the execution of the innermost loop and start
executing the next line of code after the block.
Syntax
The syntax for a break statement in C is as follows −
break.
Flow Diagram
48
Example
#include<stdio.h> int
main (){
int a =10;
if( a >15)
return0;
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
Continue statement in C
The continue statement in C programming works somewhat like the break statement. Instead of forcing
termination, it forces the next iteration of the loop to take place, skipping any code in between.
For the for loop, continue statement causes the conditional test and increment portions of the loop to
execute. For the while and do...while loops, continue statement causes the program control to pass to the
conditional tests.
49
Syntax
The syntax for a continue statement in C is as follows −
Continue;
Flow Diagram
Example
#include<stdio.h>
int main ()
{
/* local variable definition */
int a =10;
/* do loop execution */
do{ if( a ==15)
{
/* skip the iteration */
a = a +1;
continue;
goto statement in C
50
A goto statement in C programming provides an unconditional jump from the 'goto' to a labeled statement
in the same function.
NOTE − Use of goto statement is highly discouraged in any programming language because it makes difficult
to trace the control flow of a program, making the program hard to understand and hard to modify.
Any program that uses a goto can be rewritten to avoid them.
Syntax
The syntax for a goto statement in C is as follows −
goto label;
..
.
label: statement;
Here label can be any plain text except C keyword and it can be set anywhere in the C program above or
below to goto statement.
Flow Diagram
51
Example
#include<stdio.h> int
main (){
a =10;
/* do loop execution */
a = a +1;
goto LOOP;
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
52
Unit-3 Functions
• Introduction, Purpose of function,
• Function declaration/ Function prototype,
• Function definition, Function call, return statement,
• Function parameters, Types of functions,
• Call by value , Storage classes, Recursion, Examples on recursive function.
C - Functions
A function is a group of statements that together perform a task. Every C program has at least one function,
which is main(), and all the most trivial programs can define additional functions.
You can divide up your code into separate functions. How you divide up your code among different functions
is up to you, but logically the division is such that each function performs a specific task.
A function declaration tells the compiler about a function's name, return type, and parameters. A function
definition provides the actual body of the function.
The C standard library provides numerous built-in functions that your program can call. For example,
strcat() to concatenate two strings, memcpy() to copy one memory location to another location, and many
more functions.
Defining a Function
The general form of a function definition in C programming language is as follows −
the function
}
A function definition in C programming consists of a function header and a function body. Here are all the
parts of a function −
• Return Type − A function may return a value. The return_type is the data type of the value the
function returns. Some functions perform the desired operations without returning a value. In this
case, the return_type is the keyword void.
• Function Name − This is the actual name of the function. The function name and the parameter list
together constitute the function signature.
• Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the
parameter. This value is referred to as actual parameter or argument. The parameter list refers to
the type, order, and number of the parameters of a function. Parameters are optional; that is, a
function may contain no parameters.
53
• Function Body − The function body contains a collection of statements that define what the
function does.
Example
Given below is the source code for a function called max(). This function takes two parameters num1 and
num2 and returns the maximum value between the two −
int result;
result= num1;
else result=
num2; return
result;
}
Function Declarations
A function declaration tells the compiler about a function name and how to call the function. The actual body
of the function can be defined separately.
Calling a Function
While creating a C function, you give a definition of what the function has to do. To use a function, you will
have to call that function to perform the defined task.
54
When a program calls a function, the program control is transferred to the called function. A called function
performs a defined task and when its return statement is executed or when its function-ending closing
brace is reached, it returns the program control back to the main program.
To call a function, you simply need to pass the required parameters along with the function name, and if the
function returns a value, then you can store the returned value. For example −
#include<stdio.h> /*
function declaration */
int ret;
ret ); return0;
result;
result= num1;
return result;
55
We have kept max() along with main() and compiled the source code. While running the final executable, it
would produce the following result −
Formal parameters behave like other local variables inside the function and are created upon entry into the
function and destroyed upon exit.
While calling a function, there are two ways in which arguments can be passed to a function −
1 Call by value
This method copies the actual value of an argument into the formal parameter of the
function. In this case, changes made to the parameter inside the function have no effect
on the argument.
2 Call by reference
This method copies the address of an argument into the formal parameter. Inside the
function, the address is used to access the actual argument used in the call. This means
that changes made to the parameter affect the argument.
By default, C uses call by value to pass arguments. In general, it means the code within a function cannot
alter the arguments used to call the function.
C - Scope Rules
A scope in any programming is a region of the program where a defined variable can have its existence and
beyond that variable it cannot be accessed. There are three places where variables can be declared in C
programming language −
Let us understand what are local and global variables, and formal parameters.
Local Variables
Variables that are declared inside a function or block are called local variables. They can be used only by
statements that are inside that function or block of code. Local variables are not known to functions outside
their own. The following example shows how local variables are used. Here all the variables a, b, and c are
local to main() function.
56
#include<stdio.h> int
main (){
*/ int a, b; int c;
return0;
Global Variables
Global variables are defined outside a function, usually on top of the program. Global variables hold their
values throughout the lifetime of your program and they can be accessed inside any of the functions defined
for the program.
A global variable can be accessed by any function. That is, a global variable is available for use throughout
your entire program after its declaration. The following program show how global variables are used in a
program.
#include<stdio.h>
int a, b;
return0;
A program can have same name for local and global variables but the value of local variable inside a function
will take preference. Here is an example –
57
#include<stdio.h>
main (){
When the above code is compiled and executed, it produces the following result −
value of g = 10
Formal Parameters
Formal parameters are treated as local variables with-in a function and they take precedence over global
variables. Following is an example −
#include<stdio.h>
c =sum( a, b);
return0;
58
When the above code is compiled and executed, it produces the following result −
value of a in main() = 10
value of a in sum() = 10
value of b in sum() = 20
value of c in main() = 30
int 0
char '\0'
float 0
double 0
pointer NULL
It is a good programming practice to initialize variables properly, otherwise your program may produce
unexpected results, because uninitialized variables will take some garbage value already available at their
memory location.
A storage class defines the scope (visibility) and life-time of variables and/or functions within a C Program.
They precede the type that they modify. We have four different storage classes in a C program −
• auto
• register
• static
• extern
The auto Storage Class
The auto storage class is the default storage class for all local variables.
The example above defines two variables with in the same storage class. 'auto' can only be used within
functions, i.e., local variables.
59
The register Storage Class
The register storage class is used to define local variables that should be stored in a register instead of
RAM. This means that the variable has a maximum size equal to the register size (usually one word) and
can't have the unary '&' operator applied to it (as it does not have a memory location).
The register should only be used for variables that require quick access such as counters. It should also be
noted that defining 'register' does not mean that the variable will be stored in a register. It means that it
MIGHT be stored in a register depending on hardware and implementation restrictions.
The static modifier may also be applied to global variables. When this is done, it causes that variable's scope
to be restricted to the file in which it is declared.
In C programming, when static is used on a global variable, it causes only one copy of that member to be
shared by all the objects of its class.
60
#include<stdio.h>
/* function declaration */
void func(void);
*/ main()
{ while(count--)
func();
return0;
/* function definition */
void func(void)
{ static int i =5;/* local static variable */
i++;
printf("i is %d and count is %d\n", i, count);
}
When the above code is compiled and executed, it produces the following result −
i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1 i
is 10 and count is 0
When you have multiple files and you define a global variable or function, which will also be used in other
files, then extern will be used in another file to provide the reference of defined variable or function. Just
for understanding, extern is used to declare a global variable or function in another file.
61
The extern modifier is most commonly used when there are two or more files sharing the same global
variables or functions as explained below.
#include<stdio.h>
int count ;
main()
count=5;
write_extern();
#include<stdio.h>
void write_extern(void)
Here, extern is being used to declare count in the second file, whereas it has its definition in the first file,
main.c. Now, compile these two files as follows −
count is 5
62
C - Recursion
Recursion is the process of repeating items in a self-similar way. In programming languages, if a program
allows you to call a function inside the same function, then it is called a recursive call of the function.
void recursion()
recursion();
int main()
recursion();
}
The C programming language supports recursion, i.e., a function to call itself. But while using recursion,
programmers need to be careful to define an exit condition from the function, otherwise it will go into an
infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as calculating the factorial of
a number, generating Fibonacci series, etc.
Number Factorial
The following example calculates the factorial of a given number using a recursive function −
63
#include <stdio.h>
if(i <= 1)
return 1;
} int main()
int i = 12;
return 0;
When the above code is compiled and executed, it produces the following result −
Factorial of 12 is 479001600
64
Fibonacci Series
The following example generates the Fibonacci series for a given number using a recursive function −
#include <stdio.h>
int fibonacci(int i)
{
if(i == 0)
{
return 0;
}
if(i == 1)
{ return 1;
}
}
int main()
{
int i; for (i = 0; i < 10; i++)
{
printf("%d\t\n", fibonacci(i));
}
return 0;
When the above code is compiled and executed, it produces the following result −
0
1
1
2
3
5
8
13
21
34
65
Unit-4Arrays and Strings
• Introduction to one-dimensional Array,
• Definition, Declaration, Initialization,
• Accessing and displaying array elements,
• Arrays and functions, Introduction to two-dimensional Array,
• Definition, Declaration, Initialization,
• Accessing and displaying array elements,
• Introductions to Strings, Definition, Declaration,
• Initialization, Input, output statements for strings,
• Standard library functions,
• Implementations with standard library functions
C - Arrays
Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type.
An array is used to store a collection of data, but it is often more useful to think of an array as a collection
of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare 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.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and
the highest address to the last element.
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 −
double balance[10];
Here balance is a variable array which is sufficient to hold up to 10 double numbers.
Initializing Arrays
66
You can initialize an array in C either one by one or using a single statement as follows −
If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if
you write −
balance[4] = 50.0;
The above statement assigns the 5th element in the array with a value of 50.0. All arrays have 0 as the index
of their first element which is also called the base index and the last index of an array will be total size of
the array minus 1. Shown below is the pictorial representation of the array we discussed above −
67
printf("Element[%d] = %d\n", j, n[j]);
} return0;
}
When the above code is compiled and executed, it produces the following result −
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
Arrays in Detail
Arrays are important to C and should need a lot more attention. The following important concepts related
to array should be clear to a C programmer −
1
Multi-dimensional arrays
C supports multidimensional arrays. The simplest form of the multidimensional array is
the two-dimensional array.
68
3 Return array from a function
C allows a function to return an array.
4 Pointer to an array
You can generate a pointer to the first element of an array by simply specifying the array
name, without any index.
Multi-dimensional Arrays in C
C programming language allows multidimensional arrays. Here is the general form of a multidimensional
array declaration −
type name[size1][size2]...[sizeN];
For example, the following declaration creates a three dimensional integer array −
int threedim[5][10][4];
Two-dimensional Arrays
The simplest form of multidimensional array is the two-dimensional array. A two-dimensional array is a
list of one-dimensional arrays. To declare a two-dimensional integer array of size [x][y], you would write
something as follows −
type arrayName [ x ][ y ];
Where type can be any valid C data type and arrayName will be a valid C identifier. A two-dimensional
array can be considered as a table which will have x number of rows and y number of columns. A two-
dimensional array a, which contains three rows and four columns can be shown as follows −
Thus, every element in the array a is identified by an element name of the form a[ i ][ j ], where 'a' is the
name of the array, and 'i' and 'j' are the subscripts that uniquely identify each element in 'a'.
69
int a[3][4]={
};
The nested braces, which indicate the intended row, are optional. The following initialization is equivalent
to the previous example −
#include<stdio.h> int
main ()
int a[5][2]={{0,0},{1,2},{2,4},{3,6},{4,8}};
int i, j;
} return0;
When the above code is compiled and executed, it produces the following result −
70
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1 a[1][1]:
2 a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
As explained above, you can have arrays with any number of dimensions, although it is likely that most of
the arrays you create will be of one or two dimensions.
71
Passing Arrays as Function Arguments in C
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
multidimensional arrays as formal parameters.
Way-1
Formal parameters as a pointer −
void myFunction(int*param){
Way-2
Formal parameters as a sized array −
Way-3
Formal parameters as an unsized array −
}
72
Example
Now, consider the following function, which takes an array as an argument along with another argument
and based on the passed arguments, it returns the average of the numbers passed through the array as
follows −
int i;
double avg;
sum+= arr[i];
return avg;
}
Now, let us call the above function as follows −
73
#include<stdio.h>
/* function declaration */
int main ()
*/ int balance[5]={1000,2,3,17,50};
double avg;
return0;
}
When the above code is compiled together and executed, it produces the following result −
As you can see, the length of the array doesn't matter as far as the function is concerned because C performs
no bounds checking for formal parameters.
C programming does not allow to return an entire array as an argument to a function. However, you can
return a pointer to an array by specifying the array's name without an index.
If you want to return a single-dimension array from a function, you would have to declare a function
returning a pointer as in the following example −
int* myFunction(){
.
80
}
Second point to remember is that C does not advocate to return the address of a local variable to outside of
the function, so you would have to define the local variable as static variable.
Now, consider the following function which will generate 10 random numbers and return them using an
array and call this function as follows −
#include<stdio.h>
int* getRandom()
int i;
main (){
/* a pointer to an int */
int*p;
int i;
p =getRandom();
} return0;
}
When the above code is compiled together and executed, it produces the following result −
r[0] = 313959809
81
r[1] = 1759055877
r[2] = 1113101911
r[3] = 2133832223
r[4] = 2073354073
r[5] = 167288147
r[6] = 1827471542
r[7] = 834791014
r[8] = 1901409888
r[9] = 1990469526
*(p + 0) : 313959809
*(p + 1) : 1759055877
*(p + 2) : 1113101911
*(p + 3) : 2133832223
*(p + 4) : 2073354073
*(p + 5) : 167288147
*(p + 6) : 1827471542
*(p + 7) : 834791014
*(p + 8) : 1901409888
*(p + 9) : 1990469526
Pointer to an Array in C
It is most likely that you would not understand this section until you are through with the chapter 'Pointers'.
Assuming you have some understanding of pointers in C, let us start: An array name is a constant pointer
to the first element of the array. Therefore, in the declaration −
double balance[50];
balance is a pointer to & balance[0], which is the address of the first element of the array balance. Thus,
the following program fragment assigns p as the address of the first element of balance −
p = balance;
It is legal to use array names as constant pointers, and vice versa. Therefore, *(balance + 4) is a legitimate
way of accessing the data at balance[4].
Once you store the address of the first element in 'p', you can access the array elements using *p, *(p+1),
*(p+2) and so on. Given below is the example to show all the concepts discussed above −
82
#include<stdio.h>
balance[5]={1000.0,2.0,3.4,17.0,50.0};
double*p;
int i; p =
balance;
{
printf("*(balance + %d) : %f\n", i,*(balance + i));
} return0;
}
When the above code is compiled and executed, it produces the following result −
83
C - Strings
Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus, a null
terminated string contains the characters that comprise the string followed by a null.
The following declaration and initialization create a string consisting of the word "Hello". To hold the null
character at the end of the array, the size of the character array containing the string is one more than the
number of characters in the word "Hello."
Actually, you do not place the null character at the end of a string constant. The C compiler automatically
places the '\0' at the end of the string when it initializes the array. Let us try to print the above mentioned
string −
greeting[6]={'H','e','l','l','o','\0'}; printf("Greeting
When the above code is compiled and executed, it produces the following result −
84
[Link]. Function & Purpose
1 strcpy(s1, s2);
Copies string s2 into string s1.
2 strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
3 strlen(s1);
Returns the length of string s1.
4 strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
5 strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.
6 strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.
The following example uses some of the above-mentioned functions −
85
#include<stdio.h>
#include<string.h> int
main ()
char str1[12]="Hello";
char str2[12]="World";
char str3[12];
int len;
strcpy(str3, str1);
return0;
}
When the above code is compiled and executed, it produces the following result −
86
Unit-5 Structures and union
• Introduction to structure,
• Defining a structure, Declaring structure variables,
• Accessing structure members, nested structure,
• Array of structure, Array within structure,
• Introduction to union, Definition, Declaration,
• Differentiate between structure and union
C - Structures
Arrays allow to define type of variables that can hold several data items of the same kind. Similarly
structure is another user defined data type available in C that allows to combine data items of different
kinds.
Structures are used to represent a record. Suppose you want to keep track of your books in a library. You
might want to track the following attributes about each book −
• Title
• Author
• Subject
• Book ID
Defining a Structure
To define a structure, you must use the struct statement. The struct statement defines a new data type,
with more than one member. The format of the struct statement is as follows −
struct[structure tag]{
member definition;
member definition;
...
member definition;
The structure tag is optional and each member definition is a normal variable definition, such as int i; or
float f; or any other valid variable definition. At the end of the structure's definition, before the final
semicolon, you can specify one or more structure variables but it is optional. Here is the way you would
declare the Book structure −
87
Struct Books{
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
88
#include<stdio.h>
#include<string.h>
structBooks{ char
title[50]; char
author[50]; char
subject[100]; int
book_id;
};
int main()
/* book 1 specification */
strcpy([Link],"C Programming");
strcpy([Link],"Nuha Ali");
Book1.book_id =6495407;
/* book 2 specification */
strcpy([Link],"Telecom Billing");
strcpy([Link],"Zara Ali");
Book2.book_id =6495700;
89
/* print Book2 info */
return0;
When the above code is compiled and executed, it produces the following result −
book_id : 6495700
#include<stdio.h>
#include<string.h
> structBooks{
char title[50];
90
char author[50];
char subject[100];
int book_id;
};
Programming"); strcpy([Link],"Nuha
Tutorial");
specification */ strcpy([Link],"Telecom
Book2.book_id =6495700; /*
printBook(Book1);
printBook(Book2); return0;
91
printf("Book author : %s\n", [Link]);
When the above code is compiled and executed, it produces the following result −
struct_pointer =&Book1;
To access the members of a structure using a pointer to that structure, you must use the → operator as
follows −
struct_pointer->title;
#include<stdio.h>
#include<string.h>
structBooks
char title[50];
char author[50];
char subject[100];
int book_id;
92
};
/* function declaration */
void printBook(structBooks*book );
structBooks Book2;
/* book 1 specification */
strcpy([Link],"C Programming");
strcpy([Link],"Nuha Ali");
Book1.book_id =6495407;
/* book 2 specification */
strcpy([Link],"Telecom Billing");
strcpy([Link],"Zara Ali");
Book2.book_id =6495700;
printBook(&Book1);
printBook(&Book2);
return0;
void printBook(structBooks*book )
93
printf("Book subject : %s\n", book->subject);
When the above code is compiled and executed, it produces the following result −
Bit Fields
Bit Fields allow the packing of data in a structure. This is especially useful when memory or data storage is
at a premium. Typical examples include −
• Packing several objects into a machine word. e.g. 1 bit flags can be compacted.
• Reading external file formats -- non-standard file formats could be read in, e.g., 9-bit integers.
C allows us to do this in a structure definition by putting :bit length after the variable. For example −
struct packed_struct {
} pack;
Here, the packed_struct contains 6 members: Four 1 bit flags f1..f3, a 4-bit type and a 9-bit my_int.
C automatically packs the above bit fields as compactly as possible, provided that the maximum length of
the field is less than or equal to the integer word length of the computer. If this is not the case, then some
compilers may allow memory overlap for the fields while others would store the next field in the next word.
94
C - Unions
A union is a special data type available in C that allows to store different data types in the same memory
location. You can define a union with many members, but only one member can contain a value at any
given time. Unions provide an efficient way of using the same memory location for multiple-purpose.
Defining a Union
To define a union, you must use the union statement in the same way as you did while defining a structure.
The union statement defines a new data type with more than one member for your program. The format
of the union statement is as follows −
union[union tag]
member definition;
member definition;
...
member definition;
}
[one or more union variables];
The union tag is optional and each member definition is a normal variable definition, such as int i; or float
f; or any other valid variable definition. At the end of the union's definition, before the final semicolon, you
can specify one or more union variables but it is optional. Here is the way you would define a union type
named Data having three members i, f, and str −
Union Data
int i;
float f;
char str[20];
} data;
Now, a variable of Data type can store an integer, a floating-point number, or a string of characters. It
means a single variable, i.e., same memory location, can be used to store multiple types of data. You can
use any built-in or user defined data types inside a union based on your requirement.
The memory occupied by a union will be large enough to hold the largest member of the union. For example,
in the above example, Data type will occupy 20 bytes of memory space because this is the maximum space
95
which can be occupied by a character string. The following example displays the total memory size occupied
by the above union −
#include<stdio.h>
#include<string.h>
Union Data
int i; float f;
char str[20];
};
int main()
return0;
}
When the above code is compiled and executed, it produces the following result −
96
#include<stdio.h>
#include<string.h>
Union Data
int i;
float f;
char str[20];
};
int main()
{
Union Data data;
data.i =10;
data.f =220.5;
return0;
When the above code is compiled and executed, it produces the following result −
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
[Link] : C Programming
Here, we can see that the values of i and f members of union got corrupted because the final value assigned
to the variable has occupied the memory location and this is the reason that the value of str member is
getting printed very well.
Now let's look into the same example once again where we will use one variable at a time which is the main
purpose of having unions −
97
#include<stdio.h>
#include<string.h>
Union Data{
int i; float f;
char str[20];
};
int main()
{ union Data data;
data.i =10;
printf("data.i : %d\n", data.i);
data.f =220.5;
printf("data.f : %f\n", data.f);
strcpy( [Link],"C Programming");
printf("[Link] : %s\n", [Link]);
return0;
}
When the above code is compiled and executed, it produces the following result −
data.i : 10 data.f :
220.500000 [Link] : C
Programming
Here, all the members are getting printed very well because one member is being used at a time.
Array of structures:
An array in which each element is a structure. Just as arrays of any basic type of variable are allowed, so are
arrays of a given type of structures. Although structures contains many different types, the compiler never
gets to know this information because it is hidden away inside a sealed structures capsule, so it can believe
that all the elements in the array have the same type, even though that type is itself made up of lots of
different types.
98
array name[size];
Example:
struct student
{
int rollno;
char name[25];
float totalmark;
} stud[100];
In this declaration stud is a 100-element array of structures. Hence, each element of stud is a separate
structure of type student. An array of structure can be assigned initial values just as any other array. So it
can hold information of 100 students.
example
#include <stdio.h>
#include <conio.h>
Int main()
{
Struct student
{
Int rollno;
Char name[25];
Int totalmark;
}
stud[100];
int n,i;
clrscr();
printf("Enter total number of students\n\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter details of %d-th student\n",i+1);
printf("Name:\n");
scanf("%s",&stud[i].name);
printf("Roll number:\n");
scanf("%d",&stud[i].rollno);
printf("Total mark:\n");
scanf("%d",&stud[i].totalmark);
}
printf("STUDENTS DETAILS:\n");
for(i=0;i<n;i++)
{
printf("\nRoll number:%d\n",stud[i].rollno); 30 printf("Name:%s\n",stud[i].name);
99
printf("Totel mark:%d\n",stud[i].totalmark);
}
getch();
return0;
}
Structure as structure member:( nested structure)
It can have one or more of its member as another structure, but a structure cannot be member
to itself when a structure is used as structure member. In such situation, the declaration of the
embedded structure must appear before the declaration of the outer structure. For example
#include <stdio.h>
#include <conio.h>
Int main()
{
Struct dob
{
Int day;
Int month;
Int year;
};
Struct student
{
Struct dob d ;
Int rollno;
Char name[25];
Int totalmark;
}
stud[25];
int n,i;
clrscr();
printf("Enter total number of students\n\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter details of %d-th student\n\n",i+1);
printf("\nName:\n");
scanf("%s",&stud[i].name);
printf("\nRoll number:\n");
scanf("%d",&stud[i].rollno);
printf("\nTotal mark:\n");
scanf("%d",&stud[i].totalmark);
printf("\nDate of birth (Format:01 06 2010):\n");
scanf("%d%d%d",&stud[i].[Link],&stud[i].[Link],&stud[i].[Link]);
}
100
printf("STUDENTS DETAILS:\n");
for(i=0;i<n;i++)
{
printf("\n\nRoll number:%d\n\n",stud[i].rollno);
printf("Name:%s\n\n",stud[i].name);
printf("Totel mark:%d\n\n",stud[i].totalmark);
printf("Date of birth:%d / %d / %d \n\n",stud[i].[Link],stud[i].[Link],stud[i].[Link]);
}
getch();
return 0;
}
Array of Structure:
Like any other data type, array of structure can be defined, so that each array element can be of
Which defines an array called s, that contains 100 elements, each element is defined to be of type struct
student.
#include<stdio.h>
#include<conio.h>
Struct item
{
Int code;
Char name[20];
Float cost;
};
Void main()
{
Struct item it[100];
Int n,i;
Float *f,f1;
clrscr();
f=&f1;
*f=f1;
printf("Enter numer of records : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n\nEnter Record : %d",i+1);
printf("\n\nEnter Item code : ");
scanf("%d",&it[i].code);
printf("Enter Item Name : ");
fflush(stdin);
101
gets(it[i].name);
printf("Enter Item cost : ");
scanf("%f",&it[i].cost);
}
clrscr();
printf("%-10s%-15s%s","CODE","NAME","COST");
printf("\n ");
for(i=0;i<n;i++)
{
printf("\n%-10d%-15s%.2f",it[i].code,it[i].name,it[i].cost);
}
getch();
}
The allocation of variables in heap contains 2 parts. One is for integral data types (int and char),
and the other is for float type. But it is different in case when we declare a structure.
When we define a structure with 3 data types, one is of integer, other is of character and
another is of float type, the memory for all the 3 types are allocated in integral part. When we
compile this type of programs we did not get any error but when we execute the program,
102
1 the program terminates abnormally. This is because the link fails when connecting floating
2 values to the structure.
3 To solve this problem, we must declare 2 float values, one is of pointer type and the other is
4 normal float value. The memory for float pointer is allocated in the integral part (because
5 pointer has 2 bytes of unsigned int memory) and the memory for another float variable is
6 allocated in the float part. This normal variable points to the float pointer (which resides in
7 integral part), and thus we will establish a link between integral part and float part of heap.
8 Thus, the programs executes normally.
10 To accept student details and to calculate and display result using arrays
11 #include<stdio.h>
12 #include<conio.h>
13 #include<string.h>
14 struct student
15 {
16 Int sno,c,cpp,java,tot;
17 Float avg;
18 char sname[20],res[10],div[12];
19 };
20 Void main()
21 {
22 struct students[100];
23 int id=0,i;
24 clrscr();
25 while(1)
26 {
27 printf("\nEnter Student number : "); scanf("%d",&s[id].sno);
103
19 printf("Enter Student name : ");
20 fflush(stdin);
21 gets(s[id].sname);
22 printf("Enter marks in C : ");
23 scanf("%d",&s[id].c);
24 printf("Enter marks in CPP : ");
25 scanf("%d",&s[id].cpp);
26 printf("Enter marks in JAVA : ");
27 scanf("%d",&s[id].java);
28 s[id].tot=s[id].c+s[id].cpp+s[id].java;
29 s[id].avg=(float)s[id].tot/3;
30 if(s[id].c>=50&&s[id].cpp>=50&&s[id].java>=50)
31 {
32 strcpy(s[id].res,"PASS");
33 if(s[id].avg>=60)
34 strcpy(s[id].div,"FIRST");
35 else
36 strcpy(s[id].div,"SECOND");
37 }
38 else
39 {
40 strcpy(s[id].res,"FAIL");
41 strcpy(s[id].div,"NO DIVISION");
42 }
43 id++;
44 printf("\nDo u want to add another Record(y/n) : "); 45 fflush(stdin);
46 scanf("%c",&ch);
47 if(ch=='n'||ch=='N')
48 break;
49 }
50 for(i=0;i<id;i++)
51 {
52 clrscr();
53 printf("Student Details");
54 printf("\n ");
55 printf("\nStudent number : %d",s[i].sno);
56 printf("\nStudent name : %s",s[i].sname);
57 printf("\nMarks in C : %d",s[i].c);
58 printf("\nMarks in CPP : %d",s[i].cpp);
59 printf("\nMarks in JAVA : %d",s[i].java);
60 printf("\nTotal Marks : %d",s[i].tot);
61 printf("\nAverage Marks : %.2f",s[i].avg);
62 printf("\nResult : %s",s[i].res);
63 printf("\nDivision : %s",s[i].div);
64 printf("\n\nPress any key to continue........");
104
65 }
66 }
Returning structure :
A function can not only receive a structure as its argument, but also can return them.
105
1 #include<stdio.h>
2 #include<conio.h>
3 Struct student
4 { int sno;
5 char sname[20],course[20];
6 float fee;
7 };
11 scanf("%d",&[Link]);
13 fflush(stdin);
14 gets([Link]);
16 gets([Link]);
18 scanf("%f",&[Link]); returns;
19 }
21 {
22 printf("\n\nSTUDENT DETAILS");
106
27 printf("\nStudent Number : %d",[Link]);
29 printf("\nCourse : %s",[Link]);
30 printf("\nFees : %.2f",[Link]);
31 }
32 Void main()
33 {
35 clrscr ();
38 getch();
39 }
107
Unit-5 Pointers
• Introduction to pointer,
• Definition, Declaring and Initializing pointer variable,
• Indirection operator and address of operator,
• Accessing variable through its pointer,
• Pointer arithmetic, Dynamic memory allocation, • Pointers & Functions, Pointers &
Array,
• Pointers & Structures.
C - Pointers
Pointers in C are easy and fun to learn. Some C programming tasks are performed more easily with
pointers, and other tasks, such as dynamic memory allocation, cannot be performed without using pointers.
So it becomes necessary to learn pointers to become a perfect C programmer. Let's start learning them in
simple and easy steps.
As you know, every variable is a memory location and every memory location has its address defined which
can be accessed using ampersand (&) operator, which denotes an address in memory. Consider the
following example, which prints the address of the variables defined −
return 0;
When the above code is compiled and executed, it produces the following result −
108
What are Pointers?
A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory
location. Like any variable or constant, you must declare a pointer before using it to store any variable
address. The general form of a pointer variable declaration is −
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the pointer
variable. The asterisk * used to declare a pointer is the same asterisk used for multiplication. However, in
this statement the asterisk is being used to designate a variable as a pointer. Take a look at some of the
valid pointer declarations −
ip=&var;
When the above code is compiled and executed, it produces the following result −
The NULL pointer is a constant with a value of zero defined in several standard libraries. Consider the
following program −
#include<stdio.h>
int main ()
int*ptr = NULL;
return 0 ;
When the above code is compiled and executed, it produces the following result −
To check for a null pointer, you can use an 'if' statement as follows −
Pointers in Detail
Pointers have many but easy concepts and they are very important to C programming. The following
important pointer concepts should be clear to any C programmer –
110
[Link]. Concept & Description
1 Pointer arithmetic
There are four arithmetic operators that can be used in pointers: ++, --, +, -
2 Array of pointers
You can define arrays to hold a number of pointers.
3 Pointer to pointer
C allows you to have pointer on a pointer and so on.
A pointer in c is an address, which is a numeric value. Therefore, you can perform arithmetic operations
on a pointer just as you can on a numeric value. There are four arithmetic operators that can be used on
pointers: ++, --, +, and -
To understand pointer arithmetic, let us consider that ptr is an integer pointer which points to the address
1000. Assuming 32-bit integers, let us perform the following arithmetic operation on the pointer −
ptr++
After the above operation, the ptr will point to the location 1004 because each time ptr is incremented, it
will point to the next integer location which is 4 bytes next to the current location. This operation will move
the pointer to the next memory location without impacting the actual value at the memory location. If ptr
points to a character whose address is 1000, then the above operation will point to the location 1001 because
the next character will be available at 1001.
Incrementing a Pointer
We prefer using a pointer in our program instead of an array because the variable pointer can be
incremented, unlike the array name which cannot be incremented because it is a constant pointer. The
following program increments the variable pointer to access each succeeding element of the array –
#include<stdio.h>
111
const int MAX =3;
int main ()
Int var[]={10,100,200};
int i,*ptr;
ptr=var;
Return 0;
When the above code is compiled and executed, it produces the following result −
Decrementing a Pointer
The same considerations apply to decrementing a pointer, which decreases its value by the number of bytes
of its data type as shown below –
112
#include<stdio.h>
int main ()
int
var[]={10,100,200};
int i,*ptr;
} return0;
When the above code is compiled and executed, it produces the following result −
The following program modifies the previous example − one by incrementing the variable pointer so long
as the address to which it points is either less than or equal to the address of the last element of the array,
which is &var[MAX - 1] −
113
#include<stdio.h>
int main ()
int var[]={10,100,200};
int i,*ptr;
ptr=var;
i =0;
return0;
When the above code is compiled and executed, it produces the following result −
114
Programs for applying concepts of c language in lab sessions
Section A: Basic Programs:
Question A1: WAP to input roll number, name, marks and phone of a student and display the values.
Question A2: WAP to input roll number, name and marks of a student in 5 subjects and calculate the total and
average marks. Display all the values.
Question A5: WAP to input radius and calculate the area and circumference of a circle.
Question A6: WAP to input length and breadth of a rectangle and calculate the area and perimeter.
Question A7: WAP to input 4 integers a, b, c, d and check that the equation a3 + b3 +c3 = d3 is satisfied or not.
Question A8: WAP to input side of a square and calculate the area.
Question A9: WAP to input principle, rate and time from the user and calculate the simple interest and total
amount. Display all the values.
Question A10: WAP to input the number the days from the user and convert it into years, weeks and days.
Question A11: WAP to input a character and print its ASCII value.
Question A12: WAP to input a number and print its equivalent character code.
Question A13: WAP to find out the quotient and remainder of two numbers. ( Without using modulus ( % )
operator)
Question A14: WAP to input two numbers and print their quotient and remainder.
Question A15: WAP to input two numbers and print the greatest using conditional operator.
Question A16: WAP to input marks of a student and print the result (pass/fail) using conditional operator.
Question A17: WAP to input inches from the user and convert it into yards, feet and inches.
Question A19: WAP to find whether a given number is even or odd using conditional operator.
Question A20: WAP to find out the greatest of three numbers using conditional operator.
Question A21: WAP to input choice (1 or 2). If choice is 1 print the area of a circle otherwise print the
circumference of circle. Input the radius from user.
Question A22: WAP to input a number. If the number is even, print its square otherwise print its cube.
115
Question A23: WAP to input employee code, name and basic salary of an employee and calculate the following
values:
DA 10 % of basic salary
PF 10 % of GS
IT 10 % of GS
NS GS – (PF + IT)
Question A24: WAP to input the temperature in Fahrenheit and convert it into Celsius and vice versa.
Question A27: WAP to find the age of a person by the given date of birth.
Question B1: WAP to input the marks of a student and print the result (passing marks = 40 %).
Question B2: WAP to input the age of a person and check that he is eligible for license for not.
Question B3: WAP to check that a given year is a leap year or not.
Question B4: WAP to input a number and check whether it is even or odd.
Question B5: WAP to input a number and check that number is divisible by 7 or not.
Question B6: According to the Gregorian calendar, it was Monday on the date 01/01/1900. If any year is input
through the keyboard write a program to find out what is the day on 1st January of this year.
Question B7: WAP to input the name and age of a person and display “CHILD” or “TEENAGER” according to the
age.
Question B8: WAP to input the salary of a person and calculate the hra and da according to the following
conditions:
Salary HRA DA
5000-10000 10% 5%
10001-15000 15% 8%
116
Question B9: WAP to input marks in five subjects of a student and calculate the division according to the
following conditions:
Percentage Division
>=60 First
50-59 Second
40-49 Third
<40 Fail
All users are charged meter charges also, which are Rs. 50/-
Question B11: WAP to input monthly salary from the user and calculate the income tax according to the
following rules:
Question B12: WAP to input the selling price and cost price from the user and determine whether the seller
has made profit or incurred loss. Also display the value of profit or loss.
Question B13: WAP to input a character and check that it’s a small letter, capital letter, a digit or a special
symbol.
Question B14: WAP to input two integers and determine that first is multiple of second.
Question B15: WAP to input a character and check that it’s a vowel or a consonant.
Question B16: WAP to convert a small letter into capital letter and vice versa.
Question B17: WAP to input the marks of a student in five subjects and calculate the grade according the
following conditions:
Marks Grade
>90 S
76-90 A
61-75 B
51-60 C
40-50 D
<40 Fail
117
Question B18: WAP to input the sales made by a salesman and calculate the commission according to the
following conditions:
Sales Commission
1-10000 4%
10001-20000 5%
20001-30000 6%
>30000 7%
Question B19: WAP to convert the temperature according to the following conditions:
Choice Conversion
1 Fahrenheit to Celsius
2 Celsius to Fahrenheit
Question B20: WAP to find out the largest of three numbers.
Question B21: WAP to input three numbers and print them in descending order.
Question B22: WAP to input a number (1 to 7) and print the weekday name according to the given number.
Question B23: WAP to input a digit and print the digit in words.
Question B24: WAP to input two numbers and a choice and calculate the result according to the following
conditions:
Choice Result
1 Add
2 Subtract
3 Multiply
4 Divide
5 Remainder
Question B25: WAP to input two numbers and an operator and calculate the result according to the following
conditions:
‘-‘ Subtract
‘*’ Multiply
‘/’ Divide
‘%’ Remainder
Question B26: WAP to calculate the area of a circle, a rectangle or a triangle depending upon user’s choice.
Choice Area
1 Circle
2 Rectangle
3 Triangle
Question B27: WAP to input the marks in theory and practical and print the result.
Question B28: WAP to input a date (dd / mm / yyyy) and check for the validity of the date.
118
Question B29: WAP to print counting from 1 to 10.
Question B33: WAP to print all the numbers falling between 2 numbers entered by the user.
Question B34: WAP to print all the even numbers between 1 and 50.
Question B35: WAP to print all the odd numbers between 1 and 50.
Question B36: WAP to print the sum and average of first n natural numbers.
Question B37: WAP to print the sum and average of first n odd numbers.
Question B38: WAP to print the sum and average of first n even numbers.
Question B40: WAP to input 2 numbers and find out the sum of all the even numbers which are not divisible
by 5 but divisible by 3 and lies between the given two numbers.
Question B41: WAP to input the name and age of a person and print the name as many times as age.
Question B44: WAP to input a number through the keyboard until a ‘.’. Every time a number is entered. The
program should display whether it is greater than, less than or equal to the previous number.
Question B46: WAP to input a number and count its even and odd digits and find out their sum separately.
Question B48: If a number 972 is entered through the keyboard, your program should print “Nine Seven
Two”. Write the programsuch that it does this for any positive integers.
Question B49: A positive integer is entered through the keyboard, along with it the base of the numbering
system in which you want to convert this number. WAP to display the number entered, the base and the
converted number.
Question B50: WAP to input a number and separate the number in its individual digit and print the digits
separated from one another by three spaces each.
Question B51: WAP to convert a decimal number to equivalent binary number (fractions also).
Question B60: WAP to find out the LCM and GCD of two given numbers.
Question B61: WAP to find out the least common divisor of two integers.
Question B62: WAP to check whether square root of a number is prime or not.
Question B64: Input two numbers from the keyboard. Write a program to find the value of one number raised
to the power of another.
Question B65: WAP to print all the ASCII values and their equivalent characters. The ASCII values vary from 0
to 255.
Question B66: WAP to check that given number is Armstrong number or not. ( if the sum of the cubes of each
digits of the number is equal to the number itself, then the number is called the Armstrong number. For
example, 153 = (1*1*1) + (5*5*5) + (3*3*3).
Question B67: 145 is a special number, since it satisfies the following relation:
Question B69: WAP to print out all Armstrong numbers between 1 and 500.
Question B70: Square of 12 is 144. 21, which is a reverse of 12 has a square 441, which is same as 144 reversed.
There are few numbers which have this property. Write a program to find out whether any more such numbers
exist in the range of 10 to 100.
Question B71: WAP to find out the difference between two dates in terms of numbers of days.
Question B72: WAP to input n numbers and calculate the sum, average, maximum and minimum of the given
numbers. (Use only one variable to input the number and also find the second largest).
Question B73: WAP to print the sum of negative numbers, sum of positive even numbers and sum of positive
odd numbers from a list of numbers entered by the user.
Question B74: WAP to print the largest even number and largest odd number from the list of numbers entered
through keyboard.
120
Question B75: WAP to determine all Pythagorean triplets in the range 100 to 1000.
Question B78: Write a menu driven program which has following options:
1. Factorial of a number.
2. Prime or Not 3. Odd or even 4. Exit.
Question B79: WAP to input a number and print its reverse number. Also check that the number is palindrome
or not.
Question B80: WAP to input a number and find out the sum of its digits.
Question B81: WAP to find out the count of the digits of a given integer.
Question B83: WAP to input a name and print the name in the following pattern
R RAJAT
RA RAJA
RAJ RAJ
RAJA RA
RAJAT R
1 1
12 22
123 333
1234 4444
1234 4444
123 333
12 22
1 1
121
5
54
543
5432
54321
A A
AB BB
ABC CCC
ABCD DDDD
ABCD DDDD
ABC CCC
AB BB
A A
* ****
** ***
*** **
**** *
ABCDEFGFEDCBA
ABCDEF FEDCBA
ABCDE EDCBA
ABCD DCBA
ABC CBA
AB BA
A A
A B A
A B C B A
A B C D C B A
A B C B A
A B A
A
122
Question B85: WAP to print the truth table for XY+Z.
Question B86: WAP to print the factorial of all the numbers till the given number.
Question B87: WAP to print the tables of all the numbers till the given number.
Question B88: WAP to input month number and year and print the calendar for the given month.
Question B89: WAP to find out the difference between two dates, in terms of days, months and years.
Question B90: WAP to add number of days or number of months in a given date.
Question B91: WAP to print all the prime numbers till the given number.
Question C1: WAP to count the number of spaces, tabs and new line characters in a given string.
Question C2: WAP to input a character and a string. Each occurrence of a character in the string should be
converted to opposite case i.e. upper to lower case or vice versa.
Question C3: WAP to count the number of words and number of characters in a given line of text except the
spaces.
Question C4: WAP to input a multi word string and produce a string in which first letter of each word is
capitalized.
Question C5: WAP to count the numbers of vowels, consonants, digits and special symbols in a given string.
Question C6: WAP to count the lower case and upper case letters in a string.
Question C8: WAP to search a given string into another string and displays the position if found otherwise
displays 0.
Question C10: WAP to extract specified number of characters from a given position from a string.
Question C11: WAP to count all the occurrences of a character in a given string.
Question C13: WAP to input two strings and print which one is lengthier.
Question C19: WAP to replace every space in a string with a hyphen, tab with a hash and digit with a slash.
Question C20: WAP to input a string and replace every lower case letter with upper case letter, upper case
letter with a lower case letter, digit with a ‘#’ and a special symbol with a ‘%’. Display the new string.
Question C21: WAP to encrypt and decrypt a string using your own method of encryption and decryption.
Question C24: WAP to input 5 strings in an array of strings and display all the strings with their lengths.
Question C26: WAP to display all the palindrome strings from the array of strings.
Question C27: WAP to convert a string into upper case and vice versa.
Question C28: WAP to extract given number of characters from the left of the string.
Question C29: WAP to extract given number of characters from the right of the string.
Question C30: WAP to extract given number of characters, from the desired location from the string.
Question C31: WAP that will print out all the rotations of a string. For example the rotations of the word “abc”
areabc bca cab
Question C32: WAP that replaces two or more consecutive blanks in a string by a single blank.
Question C33: WAP to input 10 names in a 2D array of characters and replace the 1st name with 5th name and
display the resultant array.
Question C34: WAP to input two strings consists of maximum 80 characters. Examine both the strings and
remove all the common characters from both the strings. Display the resultant string.
Question C35: WAP to test whether a string of opening and closing parentheses is well formed or not.
Question C38: WAP to convert a given infix expression to prefix and postfix expression.
Question C39: WAP to convert a postfix expression to the prefix expression and vice versa.
Question C41: WAP to input an arithmetic expression comprising of numeric constants and operators and
evaluate the expression at the input.
124
Question C42: Write a function which has two strings x and y as arguments. The function finds out the first
symbol of x which does not occur in y.
Question C43: Write a program to check that any one of given n strings occur in a string s.
Question D1: WAP to input the marks of 10 students in an array of integers and display the marks.
Question D2: WAP to search how many times a number is present in an array.
Question D4: WAP to input the sales made by a salesman in every month of a given year and find out the total,
average, maximum and minimum sales.
Question D5: WAP to calculate the average of 10 values stored in an array and display all those values which
are more than the calculated average.
Question D6: WAP which finds the locations and values of largest and second largest element in a one
dimensional array.
Question D8: WAP to create a sorted list using arrays. Every time the element is entered in the array, the array
must remain sorted.
Question D9: WAP to rotate an integer array towards right by the given number of times.
Question D10: WAP to input 20 values in an integer array and count the negative, positive, odd and even values
in the array.
WAP to shift the negative numbers to the left and positive numbers to the right so that the
Question D12: WAP to copy the last 5 elements of array B after first 5 elements of array A. Assume length of A
and B is greater than 5.
Question D13: WAP to print all the palindrome numbers from an integer array and find out their sum.
Question D14: WAP to print all the prime numbers from an integer array and find out their sum.
Question D15: WAP to input 10 values in a float array and display all the values more than 75.
Question D16: WAP delete an element from the array and shift the elements
125
Question D17: WAP to delete all the occurrences of a given value from the array and shift the remaining
elements to the left of the array.
Question D22: WAP to check that given array is sorted in ascending / descending order.
Question D24: WAP to count the number of occurrences of a given number in an integer array.
Question D25: An array consists of 50 integers in the range of 1 to 25, write a program that prints the number
of times each integer occurs in the array.
Question D26: A, B, C are the arrays of integers of size a, b, a + b, Write a program to produce a third array C
containing all the elements of array A and B.
Question D27: WAP to merge two arrays according to the following conditions:
126
Question D28: WAP to add and multiply two large integers, which cannot be represented by built in data types.
QuestionD29: WAP to delete all elements in between and occupying two specified positions.
Question D30: WAP to search the first occurrence a given sub array within another array.
Question D31: WAP to merge 4 arrays a, b, c, d in one array. All the arrays are in ascending order.
Question E1: WAP to input the values in a two dimensional array of integers and display the values.
Question E2: WAP to display the values of a two dimensional array in the matrix form.
Question E3: WAP to find out the row sum and column sum of a two dimensional array of integers.
Question E5: WAP to print the left and right diagonal of a square matrix and find out their sum separately.
Question E7: WAP to display the upper and lower triangle of a matrix.
Question E8: WAP to find out the sum and difference of two matrices.
Question E10: WAP to find out the sum of negative, positive, odd and even integers separately from a two
dimensional array.
Question E11: WAP to display those elements of a two dimensional array which are divisible by 10. Also find
their sum.
Question E12: WAP to find out the sum of those numbers in the in a 2D array of integers which are divisible by
4 but less than 15.
Question E13: WAP to print all the prime numbers from a 2D array and find out their sum.
Question E16: WAP to find out the sum of the elements above and below the main diagonal of a square matrix.
Question E18: WAP to print all the elements of a square matrix except the diagonal elements.
Question E19: WAP to find the maximum, minimum and second maximum of a matrix.
Question E20: WAP to sort the elements of a matrix row- wise and column-wise.
127
Question E22: WAP which finds the locations and values of largest and second largest element in a two
dimensional array.
Question E23: Using a two dimensional array A[n*n], write a program to prepare a one dimensional array B[n2]
that will have all the elements of A as if they are stored in column major form.
Question E24: Using a two dimensional array A[n*n], write a program to prepare a one dimensional array B[n2]
that will have all the elements of A as if they are stored in row major form.
Question E25: WAP that receives the month and year from the keyboard as integers and prints the calendar
of the given month. (According to the Gregorian calendar 01/01/1900 was Monday)
Question E26: WAP to print the lower half and upper half of a square matrix.
Question E29: WAP to compute the determinant of a square matrix of real numbers.
Question F1: Write a function that takes one integer argument and returns its square.
Question F3: Write a function to calculate the area of a circle where radius is passed to the function as
argument.
Question F4: Write a function to calculate the area of a rectangle where length and breadth are passed to the
function as argument.
Question F5: Write a function that has three arguments principle, rate and time and returns the simple interest.
Question F6: Write a function that accepts a character as argument and returns its ASCII value.
Question F7: Write a function to swap the values of two integer variables
Question F8: Write a function that has one integer argument and returns 0 if number is even else returns 1.
Question F9: Write a function that has one character argument and displays that it’s a small letter, capital
letter, a digit or a special symbol.
Question F10: Write a function to print the sum and average of first n natural numbers where n is passed to
the function as argument.
Question F11: Write a function to print the sum and average of first n odd numbers where n is passed to the
function as argument.
128
Question F12: Write a function that returns the factorial of a number where number is passed to the function
as argument.
Question F13: Write a function that returns 1 if the number is prime and 0 if not prime. Number is passed to
the function as argument.
Question F14: Write a function that prints the sum of the digits, count of the digits and reverse of a number.
Number is passed to the function as argument.
Question F15: Write a function that returns the sum of the following series where x and n are passed to the
function as argument.
Question F16: Write a function that has two integer arguments and returns first number raised to the power
second number.
Question F17: Write a function called zero_small that has two integer arguments being passed by reference
and sets the smaller of two numbers to 0.
Question F18: Write a function that receives a string (character array) as argument and produces a string in
which first letter of each word is capitalized.
Question F19: Write a function that receives a string and a character as argument and returns 1 if the character
is found in the string else returns 0.
Question F20: Write a function to search a given string into another string and returns the position if found
otherwise returns 0. Both the strings are passed to the function as argument.
Question F21: Write a function to return the length of the string. String is passed to the function as argument.
Question F23: Write a function to search a string in the array of strings. String and array of strings should be
passed to the function as parameters.
Question F24: Write a function to copy one string into another string. Both the strings are passed to the
function as argument.
Question F25: Write a function to compare two strings. The strings must be passed to the function as
argument. The function should return 0 if the strings are equal else returns 1.
Question F26: Write a function to extract given number of characters from the right of the string. String and
integer must be passed to the function as argument.
Question F29: Write a function to delete an element from the array. Array, element to be deleted and size of
the array are passed to the function as argument.
Question F30: Write a function that receives an array and a number as argument and returns number of
occurrences of the number in the array.
Question F31: Write a function that receives an array and a number as argument and returns 1 if the number
is found in the array else returns 0. (Search the number using binary search)
Question F32: Write a function that has three arrays a, b, c as arguments of size m, n and m + n respectively.
The array a is in ascending order, b is in descending order and function should merge both the arrays and
stores them in c in descending order.
Question F33: Write a function that receives a 2D array of integers as argument and prints the sum of row
elements and column elements separately.
Question F34: Write a function to find out the product of two matrices. Matrices are passed to the function as
argument.
Question F35: Write a function to transpose a square matrix. Matrix is passed to the function as argument.
Question F36: Write a function to check the equality of two matrices. Matrices are passed to the function as
argument and function returns 1 if they are equal else returns 0.
Question G1: Write a function to swap the values of two integer variables. The addresses of the variables
should be passed to the function as argument.
Question G3: Write a function that prints the sum of the digits, count of the digits and reverse of a number
using a pointer. Address of the number is passed to the function as argument.
Question G4: Write a function having one argument of string type and print the string in the following pattern
using pointers.
R RAJAT
130
RA RAJA
RAJ RAJ
RAJA RA RAJAT R
Question G5: Write a program to print the following patterns using pointers.
A A
AB BB
ABC CCC
ABCD DDDD
ABCD DDDD
ABC CCC
AB BB
A A
ABCDEFGFEDCBA
ABCDEF FEDCBA
ABCDE EDCBA
ABCD DCBA
ABC CBA
AB BA
A A
Question G6: Write a function to count the number of spaces, tabs and new line characters in a given string
using pointers. The string must be passed to the function as argument.
Question G7: Write a function to count the numbers of vowels, consonants, digits and special symbols in a
given string using pointers. The string must be passed to the function as argument.
Question G8: Write a function to extract specified number of characters from a given position from a string
using pointers. The function has one string argument and two integer arguments.
Question G9: Write a function to concatenate two strings using pointers. Function has two string arguments.
Question G10: Write a function to compare two strings using pointers. Function has two string arguments and
returns 0 if strings are equal else returns 1.
Question G11: Write a function to encrypt and decrypt a string using pointers and use your own method of
encryption and decryption.
Question G12: WAP to reverse all the strings stored in an array using pointers
Question: Write a function to swap two strings stored in an array using pointers. The array of strings is passed
to the function as arguments.
Question G13: Write a function to display all the palindrome strings from the array of strings using pointers.
The array of strings is passed to the function as arguments.
Question G14: Write a function to reverse an array of floats using pointers. The array must be passed to the
function as argument.
131
Question G15: Write a function to print all the palindrome numbers from an integer array and find out their
sum using pointers. The array must be passed to the function as argument.
Question G16: Write a function to delete duplicate elements from the array using pointers. The array must be
passed to the function as argument.
QuestionG17: Write a function to sort an array using bubble sort technique using pointers. The array must be
passed to the function as arguments.
Question G18: Write a function to search a value in the sorted array using binary search technique using
pointers. The array and value must be passed to the function as argument and function should return 1 if found
else returns 1.
Question G19: Write a function to find out the row sum and column sum of a two dimensional array of integers
using pointers. The array must be passed to the function as argument.
Question G20: Write a function to find out the product of two matrices using pointers. The arrays must be
passed to the function as argument.
Question G21: Write a function to transpose a square matrix using pointers. The array must be passed to the
function as argument.
Question G22: Write a function to sort the elements of a matrix using pointers. The array must be passed to
the function as argument.
Question H1: WAP to calculate the GCD of two numbers using recursive function.
Question G2: WAP to find out the factorial of two numbers using recursive function.
Question H4: WAP to sort an array using Quick sort technique (recursive).
Question H7: WAP to sort an array using recursive merge sort technique.
132
Basic salary float
(1) Take an object of the given structure, input the values for the ecode, ename, basic salary, calculate all
other values and display the values.
(2) Take an array of objects of size 10 of the given structure and input, calculate and display the values for
10 employees.
133