0% found this document useful (0 votes)
2 views84 pages

Unit I&II Notes (Programming in C)

Uploaded by

Dharshan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views84 pages

Unit I&II Notes (Programming in C)

Uploaded by

Dharshan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 84

BASICS OF C PROGRAMMING

1
Introduction of Programming Paradigms-Application of C language, Structure of C Program,
C Programming: Data Types, Constants, Enumeration Constants, Keywords, Operators:
Precedence and Associativity – Expressions, Input / Output Statements- Assignment
Statements, Decision Making Statements, Switch Statement, Looping Statements.

INTRODUCTION TO C
• C programming is an ANSI/ISO standard and powerful programming language for
developing real time applications. C programming language was invented by
Dennis Ritchie at the Bell Laboratories in 1972. C programming is the most widely
used programming language even today. C is the compact general purpose
programming language. C programming is the basis for all programming
languages.
• C was developed from the Basic Combined Programming Language (BCPL)
called “B” language.
• C is the structured programming language. It is also called as the middle level
programming language because it follows both High level language and Assembly
language.
• Easy to learn
• Ability to extend
• Fast and Efficient
• Versatile and portable
• Combination of High-level and Assembly Language.
• Suitable to create both Application software and System software.

PROGRAMMING PARADIGMS
Paradigm can also be termed as method to solve some problem or do some task.
Programming paradigm is an approach to solve problem using some programming language
or also we can say it is a method to solve a problem using tools and techniques that are
available in the following approaches
• Unstructured Programming
• Structured Programming

Unstructured Programming
Unstructured Programming is a type of programming that generally executes in sequential
order i.e., these programs just not jumped from any line of code and each line gets executed
sequentially. It is also known as non-structured programming that is capable of creating
turning-complete algorithms.
Structured Programming
Structured programming, or modular programming, is a programming paradigm that
facilitates the creation of programs with readable code and reusable components. All modern
programming languages support structured programming.
Structured programs consist of a structural hierarchy starting with the main process and
decomposing downward to lower levels as the logic dictates. These lower structures are the
modules of the program, and modules may contain both calls to other lower-level modules
and blocks representing structured condition/action combinations. All of this can be combined
into a single module or unit of code, or broken down into multiple modules, resident in
libraries.
Modules can be classified as procedures or functions. A procedure is a unit of code that
performs a specific task, usually referencing a common data structure available to the program
at large. Much of the data operated on by procedures is external. A function is a unit of code
that operates on specific inputs and returns a result when called.
Types of structured programming
There are three categories of structured programming:
1. Procedural programming. Defines modules as procedures or functions that are
called with a set of parameters to perform a task. A procedural language begins a
process, which is then given data. It is also the most common category and is
subdivided into the following:
a. Service-oriented programming simply defines reusable modules as
services with advertised interfaces.
b. Microservice programming focuses on creating modules that do not
store data internally and so are scalable and resilient in cloud
deployment.
c. Functional programming, technically, means that modules are written
from functions, and that these functions' outputs are derived only from
their inputs. Designed for serverless computing, the definition
of functional programming has since expanded to be largely
synonymous with microservices.
2. Model-based programming. The most common example of this is
database query languages. In database programming, units of code are associated
with steps in database access and update or run when those steps occur. The
database and database access structure determine the structure of the code.
Another example of a model-based structure is Reverse Polish notation, a math-
problem structure that lends itself to efficient solving of complex
expressions. Quantum computing is another example of model-based structured
programming; the quantum computer demands a specific model to organize steps,
and the language simply provides it.
3. Object-oriented programming (OOP). Defines a program as a set of objects or
resources to which commands are sent. An object-oriented language defines a data
resource and sends it to process commands. The basic concept of OOP is
• Object
• Class
• Data Abstraction and Encapsulation
• Inheritance
• Polymorphism
Applications of C Language
1. Operating Systems:-
With the help of the C programming language, we can write own operating system. Like
Windows Kernel, Linux Kernel and Apple’s OS X kernel are mostly written in C.
2. GUI:-
It stands for Graphical User Interface. The C programming language also helps in developing
popular adobe softwares like Photoshop, Premier Pro, Illustrator etc.
3. Embedded Systems:-
In daily life, we use different embedded systems like coffee machines, microwaves, climate
control systems etc. These all are mostly programmed in C.
4. Database:-
The C programming language helps in developing the popular database management system,
MySQL.
5. Ease of Computation:-
C provides faster computation in programs. The implementation of algorithms and data
structures is swift in C. With the help of C, you can perform high degree calculations such as
MATLAB, Mathematica etc.
6. Gaming:-
C programming is relatively faster than Java or Python. It has been used in various gaming
applications and graphics. C programming language also helps in creating many popular
childhood games like Tic-Tac-Toe, The Snake game etc.
7. Development of New languages:-
Due to the fast execution and simplicity, many languages like Java, C++, Python, PHP, PERL,
JavaScript, etc were influenced by the development of C. In Python, C is used for building
standard libraries. The syntax and control structures of PERL, PHP and C++ are based upon
the C programming language.
8. Assemblers:-
Mainly used to translate Assembly language to Machine language. C also helped in
developing GNU assembler.
9. Text Editors:-
C also helped in creating various text editors like Vim, Gedit etc.
10. Drivers:-
Another application of C is to write driver softwares like Keyboard driver, Network driver,
mouse driver etc.
11. Interpreters:-
With the help of C programming language, you can create language interpreters. C helped in
developing different programming language interpreters like Python and MATLAB
interpreters etc.
12. Network Devices:-
Another application of C is to design network devices.
13. Compiler Design:-
C also helped in designing several popular compilers like Clang C, MINGW, Apple C etc.
This is one of the most popular uses of C language.

Structure of a C Program
Structure of C program is defined by the set of rules called protocol, to be followed by
programmer while writing C program. All C programs consist of the following sections.
1. Documentation section
2. Link Section
3. Definition Section
4. Global declaration section
5. Function prototype declaration
6. Main function
7. User defined function definition section
Format:
Documentation section // optional
Link section or preprocessor section // must
Global declaration // optional
Definition section // optional
main() function section //must
{
Declaration part // must (body of the program)
Execution part
}
Sub program (user defined function(s)) // optional
{
Function body;
}

S.No Sections Description

1 Documentation section Programmer can describe about the program, creation or


modified date, author name etc.
• Single line comment must begin with //
• Multi line comments start with “/*” and end
with “*/”
Comments will be ignored by C compiler during
compilation.

2 Link Section Header files that are required to execute a C program


It has the information about built-in function.
Ex: #include<stdio.h>, #include<conio.h>

3 Definition Section In this section, constant variables and macros are


defined.

4 Global declaration Global variables are defined in this section. These


section variables are used throughout the program.

5 Function prototype Function prototype gives information about a function


declaration section like return type, parameter type and function names.

6 Main function Every C program is started from main function and this
function contains two major sections called declaration
section and executable section.

7 User defined function Users can define their own function in this section which
section perform particular task as per the user requirements.

Simple C program:-
/* my first C program */ /* documentation section */
#include<stdio.h> /* linking section */
main() /* main() function */
{
int n1=5, n2=10, s;
s=n1+n2;
printf(“ Result=%d”, c); /* program body */
}
Result: 15
Or
Example C program to compare all the sections:
You can compare all the sections of a C program with the below C program.
// C basic structure program Documentation section
#include <stdio.h> // Link section
int total ; // Global declaration
void sum (int, int); // Function declaration section
int main () // Main function
{
printf (“This is a C basic program \n”);
sum (10, 5);
return 0;
}
void sum (int n1, int n2) // User defined function
{
total= n1 + n2; // definition section
printf (“Sum of two numbers : %d \n”, total);
}
Output:
This is a C basic program
Sum of two numbers: 15

Steps to write C programs:


The following nsteps are common to all C programs and there is no exception whether
it is a very small C program or very large C program.

Create

Compile

Execute and Run

Get the Output

Rules for writing C program (or) guidelines for C program


• Each instruction in the C program is written as a separate statement.
• All statements are written in lowercase letters only. C is a case sensitive
programming language.
• Every statement must be ended with the semicolon (;).
• All C programs must contain only one main() function and any number of user
defined functions.

Data Types
The data type is the term that refers to the kind of data used in a program. There are
several categories.
1. Basic or Primary data types - char,short int, int, float, double
2. Enumeration data type - enum
3. Derived data types - array, struct, union
4. Void data type - void
Basic or Primary data types
Data type Keyword Range of values size
Character char -128 to 127 1 byte
Integer int -32768 to 32767 2 bytes
Short integer short int -128 to 127 1 bytes
Unsigned short unsigned short 0 to 255 1 bytes
int
Long integer long int -2,147,483,648 4 bytes
to 2,147,483,647
Unsigned long unsigned long 0 to 4 bytes
integer int 4,294,967,295
Floating point float 3.4e-38 to 3.4e38 4 bytes
Double double 1.7e3-08 to 8 bytes
1.7e308

Derived data types


Derived data types are derived from the primary data types.
➢ Arrays - group of same type data stored in a common name.
➢ Structures - group of different type data stored in a common name.
➢ Unions - Same as structure, union use shared memory for all members.
Enumeration data type in C:
Enumeration data type consists of named integer constants as a list. It starts with 0
(zero) by default and the value is incremented by 1 for the sequential identifiers in the list.
syntax : enum identifier { enumerator-list };
Ex:
enum month { Jan, Feb, Mar }; or
/* Jan, Feb and Mar variables will be assigned to 0, 1 and 2 respectively by default */
enum month { Jan = 1, Feb, Mar };
Keywords
• C program has some words with special and predefined meaning that cannot be
changed.
• These words are Keywords or Reserved words.
• There are only 32 keywords used in C program.
• As, C programming is case sensitive, all keywords must be written in lowercase.
List of Keywords, that are Predefined by ANSI C.
auto double int struct
break else long switch
case enum register Typedef
char extern return Union
continue for signed Void
do if static While
default goto sizeof Volatile
const float short Unsigned
Identifiers
Identifiers are the names given to various programming elements such as variables,
functions and arrays.
Example:
int total,average;
char Name[10];
Rules for constructing identifier name in C:
1. First character should be an alphabet or underscore.
2. Succeeding characters might be digits or letters.
3. Punctuation and special characters aren’t allowed except underscore.
4. Identifiers should not be keywords

Difference between keyword and identifier


Keywords Identifier
Keywords are pre-defined words. It Identifiers are User defined words. It does
has a fixed meaning. not have any fixed meaning.
Keyword can’t be used as name of a Identifier is the name of a variable.
variable.

Constants
Constants are fixed values and that remain unchanged during the execution of the
program. The “const” keyword is used to define constants. These fixed values are also called
literals.
Type of Constant based on value type:
1. Numerical constants: Integer constant and Real constant
2. Character constant: single character, string
• Integer constant
➢ An integer constant must have at least one digit.
➢ It must not have a decimal point.
➢ It can either be positive or negative.
➢ No commas or blanks are allowed within an integer constant.
Example: const int a=10;
There are three types of integer constants.
a) Decimal.
b) Octal.
c) Hexadecimal.

a) Decimal integer constant


• It consists of any combination of digits taken from 0 to 9.
• The sign – and + are optional.
Example: const int a=20;
b) An octal integer constant
• It consists of any combination of digit from 0 to 7.
• The first digit must be o to identify the constant as an octal number.
Ex: const int a=27;
c) Hexadecimal integer constant
• It consists of combination of digits from the sets 0 through 9 and A through F
(or a to f).
• Leads with either 0x or 0X.
Ex: const int a=2A;
2. Real constant
• Real constants are called as floating point constants.
• A real constant must have at least one digit
• It must have a decimal point
• It could be either positive or negative
• If no sign precedes an integer constant, it is assumed to be positive.
• No commas or blanks are allowed within a real constant.
Example: const float pi=3.14;
3. Character constants :
• A character constant is a single alphabet, a single digit or a single special
symbol enclosed within single quotes.
• The maximum length of a character constant is 1.
Example: const char ch=’Y’
4. String constant
• It is a collection of characters, character array. String values must be placed within
double quotes.
• Minimum length of string constant is 2, i.e the compiler attached NULL character
for each string.
Example const char name [15] =”Sakthi”
How to use constants in a C program?
We can define constants in a C program in the following ways.
1. By “const” keyword
By “#define” preprocessor directive.
Backslash Character Constants in C:
• There are some characters which have special meaning in C language.
• They should be preceded by backslash symbol to make use of special function.
• Given below is the list of special characters and their purpose.

Backslash_character Meaning

\b Backspace

\f Form feed

\n New line

\r Carriage return

\t Horizontal tab

\” Double quote

\’ Single quote

\\ Backslash

\v Vertical tab

\? Question mark

\o Octal constant (o is an octal constant)

\x Hexadecimal constant (x– hex.dcml


cnst)

OPERATORS AND EXPRESSIONS


Operator
An operator is a symbol used to manipulate data and variables. The operator tells the
computer to perform certain operation.
Operand
An operand specifies an entity on which operation is to be performed. An operand can
be a variable name, a constant, a function call or macro name.
Types of operator based on number of operands are:
➢ Unary operator.
➢ Binary operator.
➢ Ternary operator
Unary Operator
Any operator that uses only one operand to perform a task is called as unary operator.
Example: ++a, b--
Increment operator and Decrement operator
➢ The increment operator adds 1 to its operand and the decrement operator subtracts
1 from the operand.
➢ Both the increment and decrement operators are unary operators. Both acts with
only one operand.
Increment operator
➢ ‘++’ is called as an increment operator.
➢ It has two types, pre increment and post increment.
Pre increment
➢ If the increment operator placed after an operand then it is called as pre increment.
➢ In pre increment the value of the operand is incremented by 1 first and then it is
used.
Example:
A = 5; initial value of A.
B = ++A; now 1 is added with 5 , so now A value is 6 then it is assigned
to B.
Post increment
➢ If the increment operator precedes the operand then it is called as post increment.
➢ In post increment the operand value is used first then incremented by 1.
Example:
A = 5;
B = A++; here the value 5 is assigned to B then A is incremented by 1.
if you print B it prints 5 only.
Pre decrement
The pre decrement is also like the pre increment instead of adding the value here it
subtracts the value by 1.
Example:
A = 9;
B = -- A. B having the value 8.
Post decrement
The post decrement is same like the post increment. Here we use the value and then
subtract 1 from the value.
Example:
A = 9;
B = A --; B having the value 9.

Binary Operator
Operator that uses two operands to perform a task is called as binary operator.
Example: a+ b, c*d
Types of operators based on functionality
C supports the following operators
➢ Arithmetic operators
➢ Assignment operators
➢ Relational operators
➢ Logical operators
➢ Conditional operators
➢ Bitwise operators
➢ Special operators

Arithmetic operators
All the mathematical operations are used in the C programming.
Operator Operation or Example Result
symbol Meaning
+ Addition or unary plus C=4+10 14
- Subtraction C=10-4 6
* Multiplication C=10*4 40
/ Division C=10/4 2
% Modulo division C=10%2 0

Assignment operator
➢ Assignment operators are used to assign the result of an expression or a value
to a variable. The mostly used assignment operator is “equal” ( = ).
Syntax: Variable_name = expression;
Example: C = A + B;
Multiple assignments
We can assign one and the same value to many variables in a single statement by using
multiple assignments.
The general format for multiple assignments is.
Variable_name = variable 1= variable2 = …. = expression;
Example: A = B = C = 10;
Shorthand assignment
Shorthand assignment simplifies the coding of a certain type of assignment operations.
The general format is
Variable_name operator= expression.
Example: A += 1; its equivalent to A= A + 1;
Relational operator
➢ Relational operators are used to test or compare two numeric values or numeric
expression.
➢ This operator provides the relation between two expressions.
Syntax: variable1 relational operator variable2;
The list of relational operators and their meanings and examples are given in the below
table.
Output /
Operator Meaning Example
return value
< Less than 5<4 0
> Greater than 5>4 1
<= Less than or equal to 10 <= 10 1
>= Greater than or equal to 10 >= 5 1
== Equal to 1 == 2 0
!= Not equal to 1 != 2 1
The equal to ( = =) and not equal to ( != ) are called as the equality operators.
The value 1 is taken as true and 0 represents false.
Logical operators
The below table list the logical operators.
Operator Meaning Example Return value
&& Logical AND 5>4 && 4<5 1
|| Logical OR 5>4 || 7<5 1
! Logical NOT !(5<4) 1
➢ The logical AND ( && ) operator provides true ( 1 ) when both the expressions are
true otherwise 0.
➢ The logical OR ( || ) operator provides true ( 1 ) when any one of the expressions is
true. If both the expressions are false then it writes 0.
➢ The logical NOT operator writes 0 if the expression is true otherwise writes 1.
Bitwise operators
➢ Bitwise operators are used for modifying bit pattern (binary representation).
➢ These are used for testing, setting and shifting the actual bits in a byte or word.
➢ Bitwise operators can operate only on an integer operands such as int, char, short,
long, signed, unsigned etc.
Operator Meaning Result
& Bitwise AND If both digits are 1, then the
output is 1
| Bitwise OR If anyone of the digits is 1,
then the output is 1
^ Bitwise exclusive OR(XOR) If both digits are same(0 or
1), then the output is 0
~ One’s complement(NOT) If the digit is 1, then the
output is 0
<< Right shift Performs right shift
>> Left shift Performs left shift

Example: int a=5, b=10, c;


C = a|b; c =5|10; c =15
Note: The bitwise operator first converts the integer into binary then perform its task,
i.e in the bitwise OR operator, any one input digits one, the output become one. Otherwise 0
(a=0101; b=1010) c=1111
Special operator
C supports some special operators
➢ sizeof operator – sizeof()
➢ comma operator – ,
➢ pointer operator - *
sizeof operator
➢ The size of operator is a unary operator.
➢ This operator returns the length in bytes of the variables, constants or
parenthesized type specifier that it precedes.
➢ The length returned by the sizeof operator is always an unsigned integer.
Example:
sizeof(256);
sizeof(int);
sizeof c; //if c is declared in program.
Comma operator
The comma operator is used to separate two or more expressions.
Example:
int a,b,c;
A = (a+b, b+c, c+d)
Conditional operator ( ?: )
➢ The conditional operator contains a condition followed by two statements or
values.
➢ If the condition is true the first statement is executed, otherwise the second
statement is executed.
Syntax: Condition ? expression1 : expression 2;
Expressions and Aassociativity
➢ The operands and the operators are joined together to perform a task is called as an
expression
➢ An expression represents a single data item, usually a number. The expression may
consist of a single entity, such as a constant or variable, or it may consist of some
combination of such entities, interconnected by one or more operators.
➢ Expressions can also represent logical conditions which are either true or false.
However, in C, the conditions true and false are represented by the integer
values 1 and 0, respectively.
Type Casting
When variables and constants of different types are combined in an expression then they
are converted to same data type. The process of converting one predefined type into
another is called type conversion.
Conversion between data types can be done in two ways by casting:
Implicit casting
Explicit casting
Implicit casting
Implicit casting doesn't require a casting operator. This casting is normally used when
converting data from smaller integral types to larger or derived types to the base type.
Example:
int x = 123;
double y = x;
In the above statement, the conversion of data from int to double is done implicitly, in
other words programmer don't need to specify any type operators.

Explicit casting
Explicit casting requires a casting operator. This casting is normally used when converting
a double to int or a base type to a derived type.
Example:
double y = 123;
int x = (int)y;
In the above statement, we have to specify the type operator (int) when converting from
double to int else the compiler will throw an error.
L-Value of Expression:
➢ L-Value stands for left value
➢ L-Value of Expressions refer to a memory location
➢ In any assignment statement L-Value of Expression must be a container(i.e. must
have ability to hold the data)
➢ Variable is the only container in C programming thus L Value must be any
Variable.
➢ L Value Cannot be constant, function or any of the available data type in C

Multiple increment operators inside printf


#include<stdio.h>
void main()
{
int i = 1;
printf("%d %d %d", i, ++i, i++);
}
Output : 3 3 1
Whenever more than one format specifiers ( i.e %d) are directly or indirectly related
with same variable (i,i++,++i) then we need to evaluate each individual expression from right
to left.
After execution we need to replace the output of expression at appropriate place.
No. Step Explanation
1. Evaluate i++ At the time of execution we will be using older value of i = 1
2. Evaluate ++i At the time of execution we will be incrementing the value
that is already modified after step 1 i.e i = 3
3. Evaluate i At the time of execution we will be using value of i modified
in step 2
Below is programmatic representation of intermediate steps -
After Step 1 : printf("%d %d %d",i,++i,1);
After Step 2 : printf("%d %d %d",i,3,1);
After Step 3 : printf("%d %d %d",3,3,1);
After Step 4 : Output displayed - 3,3,1
After solving expressions printing sequence will : i, ++i, i++
Aassociativity: In programming languages, the associativity (or fixity) of an operator is a
property that determines how operators of the same precedence are grouped in the absence of
parentheses
Precedence : In mathematics and computer programming, the order of operations (or
operator precedence) is a rule that defines which procedures to perform first in a given
mathematical expression.

C Operator Precedence Table


Operator Description Associativity

() Parentheses (function call) (see Note 1) left-to-right


[] Brackets (array subscript)
. Member selection via object name
-> Member selection via pointer
++ -- Postfix increment/decrement (see Note 2)
++ -- Prefix increment/decrement right-to-left
+- Unary plus/minus
!~ Logical negation/bitwise complement
(type) Cast (convert value to temporary value of type)
* Dereference
& Address (of operand)
sizeof Determine size in bytes on this implementation

* / % Multiplication/division/modulus left-to-right

+ - Addition/subtraction left-to-right

<< >> Bitwise shift left, Bitwise shift right left-to-right

< <= Relational less than/less than or equal to left-to-right


> >= Relational greater than/greater than or equal to

== != Relational is equal to/is not equal to left-to-right

& Bitwise AND left-to-right

^ Bitwise exclusive OR left-to-right

| Bitwise inclusive OR left-to-right

&& Logical AND left-to-right

|| Logical OR left-to-right

?: Ternary conditional right-to-left

= Assignment right-to-left
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
%= &= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR assignment
<<= >>= Bitwise shift left/right assignment

, Comma (separate expressions) left-to-right

MANAGING INPUT AND OUTPUT OPERATIONS


Formatted I/O Fnctions.
printf( )- used to display output
scanf( )-used to read datainput
➢ The unformatted I/O functions are used only for the character data types.
➢ The formatted I/O functions are used to read all types of data.
Formatted input function – scanf( )
The scanf( ) function is used to read the data from the input device.
syntax: scanf( “ control string”, arg);
Control string - Specifies the required format in which data is entered.
It contains the % symbol followed by the conversion character.
arg - Any valid variable or array.
The variable is preceded by an ampersand ( & ).
Control characters for different data types are listed below.
Conversion character Meaning
%c Reads a single character
%d Reads a decimal integer
%e (or) %f (or)% g Reads a floating point number
%h Reads a short integer
%o Reads octal number
%s Reads string
%u Reads an unsigned decimal integer
%x Reads hexadecimal number

Formatted Output Function – printf( )


➢ The printf( ) function is used to display the data on the screen.
➢ The printf( ) function moves data from the computer memory to the output device.
➢ The control string is same as that used in the scanf( ) function.
Syntax: printf(“control string”,argument1,argument2…);
Example: printf(“%d”,A);
The control or format specification of printf has following format:
%SignW.P type-specifier
Where
1. Sign may minus(-) for left justification, default right justification(+)
2. W indicates the field wicth (i.e. how many 'spaces' the item prints in
3. A period: Separating the width from the next digit(for float value).
4. A digit following the period: specifying the precision (number of decimal places for
numeric data) or the maximum number of characters to be output.

Example:
Printing Integers:
int numStudents=35123;
1. Right justification
printf(" %10d students", numStudents);
Output:
// 35123 students
2.Left justification(minus sybol)
printf(" %-10d students", numStudents);
Output:
// 35123 students
Note:
If the field width is too small or left unspecified, it defaults to the minimum number of
characters required to print the item:
printf("%2d students", numStudents);
// Output:
// 35123 students
Printing Floating-point numbers
1. Use the %f modifer to print floating point values in fixed notation:
double cost = 123.45;
printf("Your total is $%f today\n", cost);
// Output:
// Your total is $123.450000 today

2. Use %e for exponential notation:


printf("Your total is $%e today\n", cost);

// Output:
// Your total is $1.234500e+02 today
3. You can also control the decimal precision, which is the number of places after the
decimal. Output will round to the appropriate number of decimal places, if necessary:
printf("Your total is $%.2f today\n", cost);

// Output:
// Your total is $123.45 today

Printing characters and strings


1. Use the formatting specifier %c for characters. Default field size is 1 character:
char letter = 'Q';
printf("%c%c%c\n", '*', letter, '*');
// Output is: *Q*
2. Use %s for printing strings. Field widths work just like with integers:
printf("%s%10s%-10sEND\n", "Hello", "Alice", "Bob");
// Output:
// Hello AliceBob END
Format specification string Data Output
|%2d| 9 |9|
|%2d| 123 |123|
|%03d| 9 |009|
|%-2d| 7 |7|
|%5.3d| 2 |002|
|%3.1d| 15 |15|
|%3.5d| 15 |0015|
|%5s| “Output sting” |Output string|
|%15s| “Output sting” |Output string|
|%-15s| “Output sting” |Output string|
|%15.5s| “Output sting” |Output string|
|%.5s| “Output sting” |Output|
|%15.5s| “Output sting” |Output|
|%f| 87.65 |87.650000|
|%.4.1s| 87.65 |87.71|

2.6.2 Unformatted I/O functions.


getchar( ) putc ( )
getc( ) putchar( )
getch ( ) puts( )
gets( )
Reading a character
➢ The function getchar( ) is used to read a single character from the keyboard.
➢ Variable_name is any valid variable of the int or char data type.
➢ The getchar( ) reads the character and assigns the ASCII value of it to the left hand
side variable.
➢ The alternate functions for the getchar( ) is the getche( ) and getch( ).
Syntax: variable_name = getchar( );
Example:
char C;
C = getchar( );
C = getche( );
C = getch( );
Writing a character
➢ The function putchar( ) is used to display a character in the screen.
➢ The putch( ) function also works in the same way as the putchar() function. Syntax
is also same for both.
Syntax: putchar( variable_name );
Example:
char C = ‘ S ‘;
putchar( C );

Example program using getchar() and putchar()


#include<stdio.h>
void main()
{
char C;
printf(“\n Enter the character : “);
C = getchar();
printf(“\n The character is : “);
putchar( C );
}
Output
Enter the character : A
The character is : A
DECISION MAKING AND BRANCHING
Control statements
➢ In decision making, the order of program execution is decided by the condition.
➢ Condition is checked by the control statements.
➢ Control statement controls the flow of program execution.
Conditional Satement
Selection or Branching
➢ Based on the result of the condition, the execution path is selected from two or
more paths. This is known as branching. This is also termed as selection.
• if statement
• switch statement
• Conditional operator statements
• goto statement
if Statement
➢ if statement is the powerful decision making statement mostly used in C programs.
➢ It is a two-way decision making statement.
➢ If statement takes the following forms.
• Simple if statement
• if-else statement
• Nested if-else statement
• if-else ladder
Simple if Statement
if statement is used for controlling the flow of execution of the program.
The syntax for the if statement is
if ( condition )
{
Statements;
}
Statement – X;
Flow chart for the if statements

True If
(conditio
n)

Statement; False

Statement-X

if – else Statements
➢ The if statement gives importance to the true statements.
➢ But in if-else statement we have both the true and false statements.
➢ It will be selected according to the given condition.
Syntax for if-else statement
if ( condition )
{
True block statement(s);
}
else
{
False block statement(s) ;
}
Flow chart for if..else statement
False If True
(condition
)

False block statements True block statements

//Example program to find whether the given number is even or odd


#include<stdio.h>
void main()
{
int A;
printf(“\n Enter the value : “);
scanf(“%d”,&A);
if( A%2 = = 0 )
{
printf(“\n The number is even”);
}
else
{
printf(“\n The number is odd”);
}
}
Output
Enter the number : 10
The number is even
Enter the number : 5
The number is odd
Nested if-else statement
➢ In some situations we have to check more number of conditions to make a
decision.
➢ We use nested if-else statements to check the number of logical conditions.
Syntax for nested if-else statement
if( condition 1)
{
if( condition 2 )
{
True statement of 2;
}
else
{
False statement of 2;
}
}
else
{
if( condition 3 )
{
True statement of 3;
}
else
{
False statement of 3;
}
}
Flow chart for Nested-if statement
False If True
(condition
1)

False True False True


If If
(condition (condition
3) 2)

F- Statement - 3 T- Statement 3 F- Statement 2 T- Statement - 2

if-else ladder
➢ if-else ladder is a chain of if statements in which if statement is related with each
else.
➢ It also called as else - if ladder.
Syntax is
if ( condition 1 )
statement-1;
else if( condition 2 )
statement – 2;
……………..
else if( condition – n)
statement-n;
else
Statement;
// Example program to find the biggest of three numbers
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf("\n Enter the three numbers : ");
scanf("%d%d%d",&a,&b,&c);
if((a>b)&&(a>c))
{
printf("\n A is the biggest no");
}
else if(b>c)
{
printf("\n B is the biggest no");
}
else
{
printf("\n C is the biggest no");
}
getch();
Switch statement
➢ The switch statement is a built-in multi way decision statement.
➢ The switch( ) statement evaluates expression and then looks for its value among
the case constants.
➢ If the value matches with the case constant, that particular case statement is
executed.
➢ If not default is executed.
Syntax:
switch ( expression )
{
case constant-1:
statement(s);
break;
case constant-2:
statement(s);
break;
case constant-3:
statement(s);
break;
…………………..
case constant-n:
statement(s);
break;
default:
statement;
}
The break is used to exit from the current case.

Flow chart for switch-case statement


Switch
(expressio
n)

Yes
Cas
Statement 1
e1

No

Yes
Cas
Statement 2
e2

No

Yes
Cas
Statement 3
e3

No

Yes
Cas
Statement n
en

No

Default statement

Unconditional Statement
Unconditional statement will execute without any condition.
• break
• continue
• goto
Break statement
➢ The keyword break allows us to jump out of the loop immediately, used in looping
statement.
➢ When break is encountered inside any loop, control automatically passed to the
first statement after the loop.
Syntax: break;

Example of break statement


Write a C program to find average of maximum of n positive numbers entered by user.
But, if the input is negative, display the average(excluding the average of negative input)
and end the program.

/* C program to demonstrate the working of break statement by terminating a loop, if


user inputs negative number*/
# include <stdio.h>
int main()
{
int num,average,sum=0,i,n;
printf("Maximum no. of inputs\n");
scanf("%d",&n);
for(i=1;i<=n;++i)
{
printf("Enter n%d: ",i);
scanf("%d",&num);
if(num<0)
break; //for loop breaks if num<0.0
sum=sum+num;
}
average=sum/(i-1);
printf("Average=%d",average);
return 0;
}
Output
Maximum no. of inputs
4
Enter n1: 40
Enter n2: 50
Enter n3: 30
Enter n4: -1
Average=40
Continue statement
➢ In some programming situations, we want to omit the looping process then control
takes beginning of the loop.
➢ The keyword ‘continue’ allows us to do this.
➢ When continue is encountered inside any loop, the control will automatically
transfers to the beginning of the loop.
Syntax : continue;
Example of continue statement
Write a C program to find the product of 4 integers entered by a user. If user enters 0
skip it.
//program to demonstrate the working of continue statement in C programming
# include <stdio.h>
int main()
{
int i,num,product;
for(i=1,product=1;i<=4;++i)
{
printf("Enter num%d:",i);
scanf("%d",&num);
if(num==0)
continue; / *In this program, when num equals to zero, it skips the statement
product*=num and continue the loop. */
product*=num;
}
printf("product=%d",product);
return 0;
}
Output
Enter num1:3
Enter num2:0
Enter num3:-5
Enter num4:2
product=-30

goto statement
➢ C provides the goto statement to transfer the control unconditionally from one
place to another place in the program.(forward or backward irection)
➢ The goto statement requires a label to identify the place to move the execution.
➢ A label is a valid variable name and must be ended with colon.
Syntax goto label;
------------
------------
label:
Staement;

Note : goto statement makes the logic of the program complex and tangled. In modern
programming, goto statement is considered a harmful construct and a bad programming
practice.
Example :
/* This program calculates the average of numbers entered by user. */
// If user enters negative number, it ignores that number and read next input

# include <stdio.h>
int main(){
float num,average,sum;
int i,n;
printf("Maximum no. of inputs: ");
jump:
scanf("%d",&n);
for(i=1;i<=n;++i)
{
printf("Enter n%d: ",i);
scanf("%f",&num);
if(num<0.0)
goto jump; /* control of the program moves to label jump */
sum=sum+num;
}
average=sum/(i-1);
printf("Average: %.2f",average);
return 0;
}

ITERATION (OR) LOOPING STATEMENTS


A loop is defined as a block of statements which are repeatedly executed for certain
number of times.
C supports the following types of loops
1. while statement
2. do-while statement
3. for statement
1. while Statement
➢ The simplest of all the looping structures in C is the while statement.
➢ The statements present inside the while loop are executed repeatedly, until some
condition has been satisfied.
➢ The while loop is also known as entry controlled loop, because the condition is
checked at the entry point of the loop.
Syntax:
while ( condition )
{
body of the loop
}
Statement- x;
➢ The test condition is evaluated first and if the condition is true then the body of the
loop is executed.
➢ After execution of the statements, the test condition is once again evaluated and if it is
true, the statements are executed once again.
➢ This process repeated until the test condition fails.
Flow chart
False
while
(
condition )

True
Statement(s);
Statement - x

//Example program using while loop (program to print the sum of series)
#include<stdio.h>
void main()
{
int i=1, sum = 0;
while (i<= 10 )
{
sum = sum + i;
i++;
}
printf(“\n Sum of squares = %d”,sum);
}

do-while statement
On some occasions it might be necessary to execute the body of the loop before the
test is performed. Such situations can be handled with the help of do - while statement.
Syntax:
do
{
body of the loop;
}while( condition );
statement – x;
➢ On reaching the do statement the program proceeds to evaluate the body of the
loop first.
➢ After the end of the loop, the test condition is evaluated.
➢ If the condition is true the program continues to execute the body of the loop once
again.
➢ This process continues as long as the condition is true.
➢ When the condition fails, the loop will terminate and the control goes to the
statements present after the loop.
➢ The test condition is checked at the bottom of the loop i.e., in the exit point of the
loop.
➢ So the do-while loopm is known as exit controlled loop.
➢ If the control fails in the first step itself then the body of the loop is executed at
least once.
Flow chart

Statement(s);

while
(
condition )
True
False

Statement - x;

Difference between while & do while loops in C:


S.no While do while

1 Loop is executed only when Loop is executed for first time


condition is true. irrespective of the condition. After
executing while loop for first time,

2 Entry Controlled loop Exit Controlled loop.

3 Condition is checked first (at the Body of the loop is executed first and
entry of loop) and then the body then the condition is checked (at the
of the loop is executed. end of the loop).

“for” statement:
➢ Initialization of the control variables.
➢ Control variables are tested using the test condition. If the condition is true the
body of the loop is executed otherwise the loop is terminated.
➢ control variable is incremented using an assignment statement such as i++.

Syntax:
for( initialization ; test condition ; increment or decrement )
{
Statement(s);
}

//Example program using for loop


//Program to find the factorial of given number
#include<stdio.h>
#include<conio.h>
void main()
{
int n,fact=1,i;
clrscr();
printf("\n Enter the number : ");
scanf("%d",&n);
for(int i=1;i <= n;i++)
{
fact=fact*i;
}
printf("\nResult: %d",fact);
getch();
}

Output
Enter the number : 5
Result: 120
// Example program to print the pyramid format:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i=0,k;
clrscr();
printf("\n Enter the number : ");
scanf("%d",&n);
while(i <= n)
{
k = n;
while(k >= i)
{
printf(" ");
k--;
}
for(int j=1;j <= i;j++)
{
printf(" %3c",'*');
}
printf("\n");
i++;
}getch();
}
Output: Enter the number : 5
*
* *
* * *
* * * *
* * * * *
2.9 SOLVING SIMPLE SCIENTIFIC AND STATISTICAL PROBLEMS
//C Program to find area and circumference of a circle
#include<stdio.h>
void main()
{
int radius;
float PI = 3.14, area, circum;
printf("\nEnter radius of circle: ");
scanf("%d", & radius);
area = PI * rad * rad;
printf("\nArea of circle : %f ", area);
circum= 2 * PI * radius;
printf("\nCircumference : %f ", circum);
}`
Output :
Enter radius of a circle : 1
Area of circle : 3.14
Circumference : 6.28

//C Program to calculate gross salary of a person.


#include<stdio.h>
main()
{
int gross_salary, basic, da, ta;
printf("Enter basic salary : ");
scanf("%d", &basic);
da = (10 * basic) / 100;
ta = (12 * basic) / 100;
gross_salary = basic + da + ta;
printf("\nGross salary : %d", gross_salary);
return (0);
}
Output :
Enter basic Salary : 1000
Gross Salary : 1220
// C program to reverse a given number
#include<stdio.h>
void main()
{
int num, rem, rev = 0;
printf("\nEnter any no to be reversed : ");
scanf("%d", &num);
while (num >= 1)
{
rem = num % 10;
rev = rev * 10 + rem;
num = num / 10;
}
printf("\nReversed Number : %d", rev);
}
Output :
Enter any no to be reversed : 123
Reversed Number : 321
//Program to convert temperature from degree centigrade to Fahrenheit
#include<stdio.h>
main()
{
float celsius, fahrenheit;
printf("\nEnter temp in Celsius : ");
scanf("%f", &celsius);
fahrenheit = (1.8 * celsius) + 32;
printf("\nTemperature in Fahrenheit : %f ", fahrenheit);
return (0);
}
Output :
Enter temp in Celsius : 32
Temperature in Fahrenheit : 89.59998
//C Program to find the simple interest
#include<stdio.h>
void main()
{
int amount, rate, time, si;
printf("\nEnter Principal Amount : ");
scanf("%d", &amount);
printf("\nEnter Rate of Interest : ");
scanf("%d", &rate);
printf("\nEnter Period of Time : ");`
scanf("%d", &time);
si = (amount * rate * time) / 100;
printf("\nSimple Interest : %d", si);
}
Output :
Enter Principal Amount : 500
Enter Rate of interest : 5
Enter Period of Time : 2
Simple Interest : 50
/*Write a program to count the number of words, lines and characters in a text or
Program finding number of words, blank spaces, special symbols, digits, vowels using
pointers*/
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<conio.h>
void main()
{
int nob, now, nod, nov, nos, pos ;
char *str;
nob = now = nod = nov = nos = 0;
clrscr();
printf("Enter any string : ");
gets(str);
while (*str != '\0')
{
if (*str == ' ')
{
// counting number of blank spaces.
++now;
}
else if (isdigit(*str)) //counting number of digits.
++nod;
else if (isalpha(*str)) // counting number of vowels
switch (tolower(*str))
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
++nov;
break;
}
// counting number of special characters
if (!isdigit(*str) && !isalpha(*str))
++nos;
str++;
}
printf("\nNumber of words %d", now);
printf("\nNumber of spaces %d", nob);
printf("\nNumber of vowels %d", nov);
printf("\nNumber of digits %d", nod);
printf("\nNumber of special characters %d", nos);
getch();
}
Output :
Enter any string : welcome this session.
Number of words 3
Number of spaces 2
Number of vowels 7
Number of digits 0
Number of special characters 1
// C Program to obtain solution of second order quadratic equation
#include<stdio.h>
#include<math.h>
void main()
{
float a, b, c;
float d, root1, root2;
printf("\nEnter the Values of a : ");
scanf("%f", &a);
printf("\nEnter the Values of b : ");
scanf("%f", &b);
printf("\nEnter the Values of c : ");
scanf("%f", &c);
d = sqrt(b * b - 4 * a * c);
root1 = (-b + d) / (2.0 * a);
root2 = (-b - d) / (2.0 * a);
printf("\nFirst Root : %f", root1);
printf("\nSecond Root : %f", root2);
}
Output :
Enter the Values of a : 1
Enter the Values of a : -5
Enter the Values of a : 6
First Root : 3.000000
Second Root : 2.000000
IMPORTANT QUESTIONS
2 MARKS
1. Give any four features of C language.
• C is a general purpose structured programming language.
• C is powerful, efficient, compact and flexible.
• C is highly portable.
• C is a robust language whose rich set of built in functions and operators can be
used to write any complex program.

2. What is meant by global declaration section?


The variables that are used in more than one function throughout the program are
called global variables and declared outside of all the function that is before main ().
3. What is comment line?
Comment is very helpful in identifying the program features and underlying logic of
the program. This line begins with /* and ends with */. These are not executable by the
complier i.e anything in between /* and */ is ignored.
4. What are the programming rules to be followed while writing the C program?
1. All statements in C program should be written in lowercase letters. Uppercase
letters are only used for symbolic constants.
2. Each statement in C program should end with a semi colon.
3. Blank spaces may be inserted between the words. It is not used while declaring a
variable, keyword, constant and function.
4. The program statement can be written anywhere between the two braces following
the declaration part
5. The user can also write one or more statements in one line separating them with a
semicolon.
5. List out the characteristic of a program.
• Clarity • Efficiency
• Integrity • Generality
• Simplicity

6. Define identifiers.
Identifiers are names given to various program elements such as variable, functions
and arrays etc.

7. Define data types and list out the different data types available in ‘C’.
Data type is the type of the data that are going to access within the program. C
supports different data types each data type may have pre-defined memory
requirement.
There are four basic data types available in ‘C’.
1. int
2. float
3. char
4. double
8. What are Keywords?
Keywords are certain reserved words that have standard and pre-defined meaning in
‘C’. These keywords can be used only for their intended purpose.
Eg: int, float,while
9. What is meant by variables?
A variable is a named memory location. It is used to represent some specified type of
information within a designated portion of the program. A variable can be composed
of letters, digits, and the underscore character.
10. What is meant by local variables?
A variable which are defined inside a function or subprogram are called local
variables.
11. Define constants.
The items whose value cannot be changed during a execution of a program are called
constants. The “const” keyword can be used for defining constant.
12. What are the types of numeric constants?
• Integer constant: Integer constant formed with the sequence of digits. There are
three type of integer constants which forms different number system
• Real constant: Real constant is made up of a sequence of numeric digits with
presence of decimal point. It serves as a good purpose to represent quantities that
vary continuously such as distance, height, temperature etc.
13. Define statements.
Statements can be defined as set of declaration or sequence of action. Statement causes
the computer to perform some action.
14. What is an Operator and Operand?
An operator is a symbol that specifies an operation to be performed on operands.
Example: * , +, -, / are called arithmetic operators.
The data items that operators act upon are called operands.
Example: a+b; In this statement a and b are called operands.
15. What is Ternary operator or Conditional operator?
Ternary operator is a conditional operator with symbols ? and :
Syntax: variable = exp1 ? exp2 : exp3
If the exp1 is true, variable takes the value of exp2.
If the exp2 is false, variable takes the value of exp3.
16. What are the Bitwise operators available in ‘C’?
& - Bitwise AND,
| - Bitwise OR,
~ - One’s Complement,
>> - Right shift,
<< - Leftshift,
^ - Bitwise XOR are called bit field operators.
Example: k=~j; where ~ take one’s complement of j and the result is stored in k.
17. What are the logical operators available in ‘C’?
The logical operators available in ‘C’ are
&& - Logical AND,
|| - Logical OR,
! - Logical NOT

18. What is the difference between ‘=’ and ‘==’ operator?


Where = is an assignment operator and == is a relational operator.
Example : while (i=5) is an infinite loop because it is a non zero value and while
(i==5) is true only when i=5.
19. What are the types of operators?
• Arithmetic operators
• Relational operators
• Logical operators
• Assignment operators
• Increment and decrement operators
• Conditional operators ( Ternary operator )
• Bit wise operators
• Special operators
20. Define expression.
An expression represents data item such as variables, constants and are interconnected
with operators as per the syntax of the language. An expression is evaluated using
assignment operators.
21. What is type casting?
Type casting is the process of converting the value of an expression to a particular data
type.
Example: int x, y; c = (float) x/y; where a and y are defined as integers. Then the
result of x/y is converted into float.

22. What is conversion specification?


The conversion specifications are used to accept or display the data using the
INPUT/OUTPUT statements. It’s also called as the “control string” or”formatted
string”
23. What is the difference between ‘a’ and “a”?
‘a’ is a character constant and “a” is a string.
24. What is a Modulo Operator?
‘%’ is modulo operator. It gives the remainder of an integer division.
Example : a=17, b=6. Then c=a%b gives 5.
Note: float and double values can’t be used for % operator.
25. How many bytes are occupied by the int, char, float, long int and double?
• int - 2 Bytes
• char - 1 Byte
• float - 4 Bytes
• long int - 4 Bytes
• double - 8 Bytes
26. What is the difference between ++a and a++?
++a means do the increment before the operation (pre increment)
a++ means do the increment after the operation (post increment)
Example:
a=5;
x=a++; /* assign x=5* /
y=a; /* now y assigns y=6* /
x=++a; /* assigns x=7* /
27. What is a global variable?
The global variable is a variable that is declared outside of all the functions. The
global variable is stored in memory, the default value is zero. Scope of this variable is
available in all the functions. Life time of variable is till end of the program execution.
28. What are the Escape Sequences present in ‘C’
\n - New Line,
\b – Backspace,
\t - Form feed,
\’ - Single quote,,
\\ - Backspace,
\t – Tab,
\r - Carriage return,
\a – Alert,
\” - Double quotes
29. What are the types of I/O statements available in ‘C’?
There are two types of I/O statements available in ‘C’.
• Formatted I/O Statements( Example: scanf & printf)
• Unformatted I/O Statements( Example: gets, puts,getc ,putc and getche)
30. Define single character input getchar ( ) function.
The getchar ( ) function is written in standard I/O library. It reads a single character
from a standard input device. This function does not require any arguments, through a
pair of empty parenthesis, must follow the statement getchar ( ).
31. Define single character output putchar ( ) function.
The putchar ( ) function is used to display one character at a time on the standard
output device. This function does the reverse operation of a single character input
function.
32. Define scanf ( ) statement.
The scanf ( ) function is used to read information from the standard input device
(key board ). Scanf ( ) function starts with the string argument and may contain
additional argument.
Syntax: scanf(“control string”,&var1,&var2,…..,&varn);
33. Define printf ( ) statement.
Output data or result of an operation can be displayed from the computer to a standard
output device using the library function printf ( ). This function is used to output any
combination of data.
Syntax: printf(“control string”,var1,var2,…..,varn);
34. What is the difference between getchar ( ) and scanf( ) functions for reading
characters?
getchar( ) - To read a single character from stdin, then getchar() is the appropriate.
scanf( ) - scanf( ) allows to read more than a single character at a time.
35. What is the difference between scanf() and gets() function?
In scanf() when a blank space was typed, the scanf() assumes that it is an end of the
input.
gets() :assumes the enter key(\n) as end. It accepts blank space.
36. What is meant by Control String in Input/Output Statements?
Programming in C

Control strings contain the format code characters, specifies the type of data that the
user accessed within the Input/Output statements.
37. Define simple if statement.
Simple if statement is a decision making statement. It is used to control the flow of
execution of the statements and also used to test logically whether the condition is true
or false.
Syntax: if(expression)
{
statements;
}
38. What is meant by looping?
The loop is defined as the block of statements which are repeatedly executed for
certain number of times.
39. Define for loop.
For loop is another repetitive control structure and is used to execute set of instructions
repeatedly until the condition becomes false.
for(initialization ; test condition; increment/decrement counter)
{
Body of the loop;
}
40. What is meant by switch statement?
The switch statement is used to pick up or execute a particular block of statements
from several available blocks of statements. It allows us to make a decision from the
number of choices.
Syntax:
Programming in C

switch (expression)
{
case constant1:
block1;
break;
case constant2:
block2;
break;
.
.
.
default:
default block;
break;
}
Note: the constant value should be int or char only.
41. Define nested for loop.
The loop within the loop is called nested loop. In “nested for” loop one or more “for”
statements are included in the body of the loop. The number of iterations in this type
of structures will be equal to the number of iterations in the outer loop multiplied by
the number of iterations in the inner loop.
42. What is meant by break statement?
The break statement is used to terminate the loop when the keyword “break” is used
inside any loop statement, the control is automatically transferred to the first statement
after the loop. Break is usually associated with switch and looping statements.
Syntax: break;
43. Define goto statement.
The goto statement transfer control unconditionally from one place to another place in
the program.
Syntax:
Programming in C

goto label;
.............
.............
.............
label:
statement;
44. What are the difference between if and while statement?
If While

It is a conditional statement It is a loop control statement


If the condition is true, it executes If the condition is true, it executes the
some statements. statements within the while block repeatedly
until the condition fails.
45. What are the difference between while loop and do…while loop?

S.no While do while

1 Loop is executed only when Loop is executed for first time


condition is true. irrespective of the condition. After
executing while loop for first time,

2 Entry Controlled loop Exit Controlled loop.

3 Condition is checked first (at the Body of the loop is executed first and
entry of loop) and then the body then the condition is checked. (at the
of the loop is executed. end of the loop).
46. What is the difference between while(a) and while(!a)?
while(a) means while(a!=0)
while(!a) means while(a==0)
47. Construct an infinite loop using while.
while (1)
{
}
Here 1 is a non zero, value so the condition is always true. So it is an infinite loop.
Programming in C

48. Differentiate break and continue statement


S.No. Break Continue
1 Exits from current block / loop Exits from current iteration .
2 Control passes to next statement Control passes to next iteration.
3 Used in switch and looping Used only in looping statement.
statements.

49. List the difference between float and double datatype.


S.No. Float Double Float /Double
1 Occupies 4 bytes in memory Occupies 8 bytes in memory

2 Range : 3.4 e-38 to 3.8e+38 Range : 1.7 e-308 to 1.7e+308

3 Format Specifier: % f Format Specifier: % lf


4 Example : float a; Example : double y;
There exists long double having a range of 3.4 e
-4932 to 3.4 e +4932 and occupies 10 bytes in
memory.
Example: long double k;

PART – B
1. Discuss the Programming paradigm (8)
2. List and explain the applications of C language.
3. Explain the structure of a C program. What are the applications of C language ? (16)
4. Explain different data types in C with examples. (8)
5. What are the different types of operators in C ? Explain with examples. (16)
6. Describe the looping statements in C with examples (16)
7. With example describe the structure of (i) if and if-else statement (ii) nested if..else
statement (iii) switch statement in C language (16)
Programming in C

8. Explain with example unformatted and formatted Input and Output statements in C
language (16)
9. Compare while and do…while with an example (4+4)
Programming in C

ARRAYS AND STRINGS


2
Introductioto Arrays – Declaration, Initialization, One dimensional array, Two
dimensional arrays. String operations- Read, write. String Handling Functions –
length, compare, concatenation, copy, Array of String, Enumerated data type.

INTRODUCTION
Definition and Declaration of Arrays:
An array is the collection of similar (homogenous) data types in which each element is
located in separate continuous memory locations.
Syntax:
Data_type Array_name [ size ];
➢ Data type represents the type of data stored in an array.
➢ Array name is any valid variable name.

➢ Size is also called as subscript, which gives the number of elements in an array.
Example
int A[25];
Here the array is of integer type which carries maximum 25 elements.
Memory map of an array is given below

int A[25];

….

a[0] a[1] a[2] a[3] a[24]


Programming in C

Characteristics of arrays

i. An array is the collection of similar data types


ii. All elements of an array share the common name.
iii. It is allocated in continuous memory locations.
iv. Elements can be accessed directly using subscript operator and index
value.

TYPES OF ARRAYS
1. One dimensional array
2. Two dimensional array
3. Multi dimensional array
1. One dimensional array

Any array which have only one subscript is called as one dimensional array.
Array initialization
C allows the initialization of arrays at the time of declaration. The general format of
array initialization is similar to that of the other variables.
Syntax: data_type array_name [size] = { list of values };

Example
int a[7] = { 1,2,3,4,5,6,7};
where the size is optional, in that case the compiler will allocate enough memory.
int a[]={1,2,3,4,5,6,7}
Example program
#include<stdio.h>
#include<conio.h>
void main()
{
int a[7]={1,2,3,4,5,6,7},i;

clrscr();
Programming in C

printf("\n Elements in array are");

for(i=0;i<=6;i++)
{
printf("\n a[%d] = %d",i,a[i]);
}
getch();

}
Output:
Elements in array are
a[0] = 1
a[1] = 2

a[2] = 3
a[3] = 4
a[4] = 5
a[5] = 6
a[6] = 7

Memory map for the above program.

1 2 3 4 5 6 7

a[0] a[1] a[2] a[3] a[4] a[5] a[6]


Dynamic initialization of an array
➢ An array is also initialized dynamically during the run time of the program by
using scanf( ) statement. It is done with the help of for loop.
for(i=0;i<=5;i++)
{
scanf(“%d”,&a[i]);
}

This for loop is used to read 5 values to the array named ‘a’.
Programming in C

//program to print the sum of even numbers in a given list

#include<stdio.h>
#include<conio.h>
void main()
{
int a[20],s=0,n,i;
printf(“enter the size of array”);
scanf(“%d”,&n);
printf(“enter the elements of an array”);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
printf(“the even numbers in the array are:”);
for (i=0;i<n;i++)
{
if (a[i]%2==0)
{
printf(“%d”,a[i]);
s=s+a[i];
}
}
getch();
}
2. Two dimensional arrays
➢ The two dimensional arrays are used when it is required to process matrices,
tabular data etc.,
➢ Two dimensional arrays are stored in row-column matrix.
➢ The left index indicates the row and the right index indicates the column.
The syntax for the two dimensional array:
Programming in C

Data_type array_name [ row-size ] [ column-size ]

Example : int a[3][3];


Memory Representation of 2D
0 1 2

0
a[0][0] a[0][1] a[0][2]

a[1][0] a[1][1] a[1][2]

2
a[2][0] a[2][1] a[2][2]

Initializing two dimensional arrays

➢ Initialization of two dimensional arrays is same as that of one dimensional array.


➢ It is done with the list of initial values enclosed in braces.
For example, consider the following declaration statement.
int A[3][4] = { 0,0,0,0,1,1,1,1,2,2,2,2};
➢ The above statement initializes the first row to 0, the second row to 1 & the third
row to 2
➢ The initialization of an array variable is done in a row by row manner.
The above statement can be rewritten as follows.
int A[3][4] = { {0,0,0,0},
{1,1,1,1},

{2,2,2,2} };
//Example program display the matrix elements
#include<stdio.h>
#include<conio.h>
void main()
{
Programming in C

int a[3][4]={0,0,0,0,1,1,1,1,2,2,2,2};
clrscr();
printf("\n The elements in the matrix are \n");
for(int i=0;i<3;i++)
{
for(int j=0;j<4;j++)
{
printf("%2d",a[i][j]);
}
printf("\n");
}
getch();
}
Output
The elements in the matrix are
0000

1111
2222
Multi Dimensional Array:
An array having more than two dimensions is known as multidimensional array. It is
also called as arrays of array.

Syntax:
int[s1][s2][s3];
s1,s2,s3 are size of an array.
STRING
➢ Group of characters, digits and symbols enclosed within double quotation (“ ”) are
called as strings.
➢ The strings are always declared as the character arrays.
➢ Simply character arrays are called as strings.
Programming in C

➢ Every string is terminated with NULL character ( \0 ).

Declaration and initialization of strings


➢ A string is always declared as an array.
➢ The variable is any valid C variable name.
The syntax for declaring string is given below.
char variable_name[size];

Here size represents the number of characters in the string.


Example:
char name[25];
We can initialize the string in two ways.

• At compile time- at the time of declaring

• At run time - at the time of executing


Compile time initialization:
We can initialize the string at the time of declaration as follows:
char name[5] = “CSE”;
or
char name[5] = {‘C’,’S’,’E’,’\0’};

or
char name[5] = {‘C’,’S’,’E’};
Run time initialization:
We can initialize the string during execution by using the scanf( ).

• It is called as dynamic initialization.

• char name[5];
scanf(“%s”, name);

Note: No need to use the address symbol ‘&’ at the time of reading the string.
Programming in C

OPERATION OF STRING:

String handling functions


➢ C standard library has a number of string handling functions.
➢ String functions used to manipulate on the string.
➢ These string handling functions are available in the header file string.h

String Built-in function

1. strlen()
2. strrev()
3. strcpy()
4. strcmp()
5. strcat()

1. String length function – strlen( )


➢ This function is used to find the length of the string, it takes single argument as a
string and return length.

➢ The length of the string is determined by the number of characters present in that
string.
Syntax:
n = strlen( string_variable);
n is an integer type variable which holds the number of characters in a given string.

Example:
void main()
{
char names[10]=”CSE”;
int n;

n=strlen(s);
printf(“Length of the string is %d”,n);
}
Output:
Programming in C

Length of the string is 3

2. String reverse function – strrev()


➢ The strrev( ) is used to reverse the string, it takes single argument as a string and
return the reverse of string.
Syntax :
strrev( string_variable);

Example:
char dept[10]=”CSE”,*rev;
rev=strrev(dept);
Output:
The reversed string is : ESC

3. String copy function – strcpy( )


➢ This function copies the contents of one string to another.
➢ Here the second string is replace the first string.
➢ The first string is called as the target string and the second string is called as the
source string.

➢ Only the first string changed but the second string remains as it is.
Syntax:
strcpy( target_string, source_string);
Example:
char s1[10]=”cse”,s2[10=”ece”;
strcpy(s1,s2);
Output:
before copy
first string: cse
second string: ece

After string copy


Programming in C

First string is : ece

Second string is : ece


4. String compare function – strcmp( )
➢ This function is used to compare two strings, whether they are same or not.
➢ The comparison is based upon the ASCII values of the characters present in the
string.

➢ It compares the ASCII values of both the strings. If both values are same it returns
the integer 0.
➢ If the first string is alphabetically greater than the second string then, it returns a
positive value.
➢ If the first string is alphabetically less than the second string then, it returns a
negative value.
Syntax:
strcmp( string1, string2);
Example :
#include<stdio.h>
#include<string.h>
void main()
{
char s1[10]=”cse”,s2[10=”ece”;
n=strcmp(s1,s2);
if(n==0)
{
printf("\n The given strings same");
}
else
{
printf("\n The strings are different");
}
}

Output:
The given strings are different
5. String concatenation function – strcat( )
➢ We can add (or) combine two strings by using the strcat( ) function.
Programming in C

➢ In this the second string is combined with the first string.

Syntax:
strcat(s1,s2);
Example:
char s1[10]=”Computer”,s2[10=”Programming”;
strcat(s1,s2);

Output:
The concatenated string s1 is: ComputerProgramming
s2: Programming
Example1:

Program to Check Whether the Given String Is Palindrome or Not


(OR)
Program Using String Functions (STRCPY, STRCMP, STRLEN, STRREV)
#include <stdio.h>
#include<conio.h>
void main()
{
char a[10], b[10];
int n;
printf(“ Enter the string”);
scanf (“%s”, a);
n=strlen(a);
printf(“the length of the string is %d”,n);
strcpy(b,a);
strrev(a);
if(strcmp(a,b)==0)
printf(“the string is palindrome”);
else
Programming in C

printf(“ the string is not a palindrome”);


getch();
}

Other String Function:


➢ strncpy()
➢ strncat()
➢ strncmp()
➢ strcmpi()
➢ sscanf()
➢ sprintf()

strncpy()
strncpy() is used to copy only the left most n characters from source to destination. The
Destination_String should be a variable and Source_String can either be a string constant or a
variable.

Syntax:
strncpy(Destination_String, Source_String, n);
Where n is the no_of_characters.
strncat()
strncat() is used to concatenate only the leftmost n characters from source with the destination
string. The Destination_String should be a variable and Source_String can either be a string
constant or a variable.
Syntax:
strncat(Destination_String, Source_String,no_of_characters);
strncmp()

strncmp() is used to compare only left most ‘n’ characters from the strings.
Syntax:
int strncmp(string1, string2,no_of_chars);

➢ This function returns integer value after comparison.Value returned is 0 if left most ‘n’
characters of two strings are equal.
➢ If the left most ‘n’ characters of first string is alphabetically greater than the left most
‘n’ characters of second string then, it returns a positive value.
Programming in C

➢ If the left most ‘n’ characters of first string is alphabetically less than the left most ‘n’
characters of second string then, it returns a negative value

strcmpi()
strcmpi() function is use two compare two strings. strcmp () function does a case insensitive
comparison between two strings.

The Destination_String and Source_String can either be a string constant or a variable.

Syntax:
int strcmpi(string1, string2);
This function returns integer value after comparison.

sscanf()
This function is used to extract strings from the given string into different variable.
If we want to extract word seperatly ( “Learn”, “C” and “Online” ) in a different variable then
it can be done using sscanf function.
Example :
char *str = "Computer Programming Lnaguage";
char *first, *second, *third;
sscanf(str, "%s %s %s",first,second,third);

“Computer” will get stored in variable first


“Programming” will get stored in variable second
“Lnaguage” will get stored in variable third.

sprintf()
This function is exactly opposite to sscanf() function. Sprint() function writes the formatted
text to a character array.
Syntax:
sprintf (CharacterArray,”Conversion Specifier”, variables);
Example:
char *str;
Programming in C

char *first = " Computer ", *second = "Programming", *third = "Language";


sprintf(str, "%s %s %s",first,second,third);
str will be "Computer Programming Lnaguage";

Array of Strings
Group of strings are stroed under the common name is called Array of Strings. We can easily
store the strings in an array like integer values. For example consider the example given
below
char name[4][5];
The initialization of the sring array can be done as follows.
Char name[4][5] = { “raj”,”priya”,”kumar”,”ramya”};

Example2: program for array of string (or) Sort the given strings in alphabetical order.
#include<stdio.h>
#include<string.h>
void main()
{
int i,j,n;
char str[20][20],temp[20];
puts("Enter the no. of string to be sorted");
scanf("%d",&n);
puts("Enter the string”);
for(i=0;i<=n;i++)
gets(str[i]);
for(i=0;i<=n;i++)
for(j=i+1;j<=n;j++)
{
if(strcmp(str[i],str[j])>0)
{
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
Programming in C

strcpy(str[j],temp);
}
}
printf("The sorted string\n");
for(i=0;i<=n;i++)
printf(“%s”\n” str[i]);
}
Input:
N=3;
The string:
hen

dog
cat
Output:
the ordered string:
cat

dog
hen
MATRIX OPERATION:
//PROGRAM MATRIX ADDITION
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],b[3][3],c[3][3],i,j,row,column;
clrscr();
printf("enter the row and column");
scanf("%d%d",&row,&column);
printf("enter the A matrix");
Programming in C

for(i=0;i<row;i++)
for(j=0;j<column;j++)
scanf("%d",&a[i][j]);
printf("enter the B matrix");
for(i=0;i<row;i++)
for(j=0;j<column;j++)
scanf("%d",&b[i][j]);
// addition operation
for(i=0;i<row;i++)
for(j=0;j<column;j++)
c[i][j]=a[i][j]+b[i][j];
printf("the output c matrix");
for(i=0;i<row;i++)
for(j=0;j<column;j++)
{
printf("%3d",c[i][j]);
}
printf("\n");
getch();
}
Input :

A= 1 2 B= 1 2 OUTPUT: C = 2 4
3 4 3 4 6 8
// PROGRAM MATRIX SUBTRACTION
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],b[3][3],c[3][3],i,j,row,column;
clrscr();
printf("enter the row and column");
Programming in C

scanf("%d%d",&row,&column);
printf("enter the A matrix");
for(i=0;i<row;i++)
for(j=0;j<column;j++)
scanf("%d",&a[i][j]);
printf("enter the B matrix");
for(i=0;i<row;i++)
for(j=0;j<column;j++)
scanf("%d",&b[i][j]);
// subtraction operation
for(i=0;i<row;i++)
for(j=0;j<column;j++)
c[i][j]=a[i][j]-b[i][j];
printf("the output c matrix");
for(i=0;i<row;i++)
for(j=0;j<column;j++)
{
printf("%3d",c[i][j]);
}
printf("\n");
getch();
}
Input :
A= 1 2 B= 1 2 OUTPUT: C = 0 0
3 4 3 4 0 0
//PROGRAM MATRIX MULTIPLICATION

#include<stdio.h>
#include<conio.h>
void main()
{
Programming in C

int a[2][2],b[2][2],c[2][2],i,j,k,r1,r2,c1,c2;
clrscr();
printf("enter the r1 and c1");
scanf("%d%d",&r1,&c1);
printf("enter r2 and c2");
scanf("%d%d",&r2,&c2);
if(c1!=r2)
{
printf("invalid multiplication");
}
else
{
printf("multiplication possiable");
printf("enter the a matrix");
for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
scanf("%d",&a[i][j]);
printf("enter the B matrix");
for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
scanf("%d",&b[i][j]);
// matrix multiplication
for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
{
c[i][j]=0;
for(k-0;k<r2;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
printf("the output matrix")
for(j=0;i<r1;j++)
Programming in C

for(j=0;j<c2;j++)
{
printf("%3d",c[i][j]);
}
printf("\n");
}
printf("the output c matrix");
for(i=0;i<row;i++)

for(j=0;j<column;j++)
{
printf("%3d",c[i][j]);
}
printf("\n");
}
getch();
}
Input :
A= 1 2 B= 1 2 OUTPUT: C = 7 10
3 4 3 4 15 22
//PROGRAM MATRIX TRANSPOSE

#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],t[3][3],i,j,row,column;
clrscr();
printf("enter the row and column");
scanf("%d%d",&row,&column);
printf("enter the A matrix");
Programming in C

for(i=0;i<row;i++)
for(j=0;j<column;j++)
scanf("%d",&a[i][j]);
// transpose operation
for(i=0;i<row;i++)
for(j=0;j<column;j++)
t[i][j]=a[j][i];
printf("the output matrix");
for(i=0;i<row;i++)
for(j=0;j<column;j++)
{
printf("%3d",t[i][j]);
}
printf("\n");

getch();
}
Input :
A= 1 2 OUTPUT: C = 1 3
3 4 2 4
//PROGRAM FOR SUMMATION OF ELEMENTS OF A MATRIX

#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],i,j,row,column , sum=0;
clrscr();
printf("enter the row and column");
scanf("%d%d",&row,&column);
printf("enter the A matrix");
Programming in C

for(i=0;i<row;i++)
for(j=0;j<column;j++)
{
scanf("%d",&a[i][j]);
sum=sum+a[i][j];
}
printf("%d",sum);
}
getch();
}
Input : A= 1 2 sum = 9
3 3

IMPORTANT QUESTIONS
2 marks
ARRAYS AND STRINGS
1. What is an array? Classify it.
An array is a collection of similar data items that are stored under a common name. A
value in an array is identified by index or subscript enclosed in square brackets with
array name.
Arrays can be classified into

• One Dimensional Array

• Two Dimensional Array


Programming in C

• Multi dimensional Array


2. List the characteristics of Arrays.
All elements of an array share the same name, and they are distinguished from one
another with help of an index (element number).
Any particular element of an array can be modified separately without disturbing other
elements.
3. Define Strings.
The group of characters, digit and symbols enclosed within double quotes (“ ”) is called as
String (or) character Arrays. Strings are always terminated with ‘\0’ (NULL) character. The
compiler automatically adds ‘\0’ at the end of the strings.
Example: char name [ ]={‘C’,’O’,’L’,’L’,’E’,’G’,’E’,’\0’};
The characters of a string are stored in contiguous memory locations as follows:

C O L L E G E \0

1000 1001 1002 1003 1004 1005 1006 1007


4. Why is it necessary to give the size of an array in an array declaration?
When an array is declared, the compiler allocates a base address and reserves enough
space in the memory for all the elements of the array. The size is required to allocate
the required space. Thus, the size must be mentioned.

5. List out some features of Array.

• An array is derived data type. It is used to represent a collection of elements of


the same data type.

• The elements can be accessed with base address and the subscripts define the
position of the element.

• In array, the elements are stored in continuous memory location. The starting
memory location is represented by the array name and it is known as the base
address of the array.

• It is easier to refer each one of the array elements by simply incrementing the
value of the subscript.
6. How are multi-dimensional arrays stored in C?
Programming in C

An array having more than two dimensions is known as multidimensional array. It


is also called as arrays of array.
Syntax:
int[s1][s2][s3];
s1,s2,s3 are size of an array.

7. Explain the standard string functions with syntax for string length, copy and
combine?
strlen():-It is used to find the length of the string.
syntax: strlen(string);
strcpy():-It is used to copy one string to another.
syntax: strcpy(string1,string2) ;
strcat():-It is used to combine two strings.
syntax:
strcat(string1,string2);

8. What is null character?


A character constant with ASCII value of zero is known as the null character and is
written as ‘\0’.
9. What are the sorting & searching techniques?
Sorting Techniques:

1.Bubble Sort
2. Insertion Sort.
3. Selection Sort.
4. Quick Sort.
SearchingTechniques:

1. Linear Search
2. Binary Search
10. Write a C program find the length of the string using string function?
Programming in C

String Function:- strlen()

#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{

char name[]=”COMPUTER”;
int len1;
len1=strlen(name);
printf(“The string length of %s is %d”, name,len1);
}

OUTPUT:
The string length of COMPUTER is 8
11. Give the function and syntax for string compare, reverse and conversion of lower,
upper cases?
strcmp():-

It is used to compare two strings.


syntax:
strcmp(string1,string2)
– Returns 0 if two strings are equal.
– Return value <0 if s1 is less than s2.

– Return value >0 if s1 is greater than s2.


strlwr(), strupr():-It is used to change the case of a string.
syntax: strlwr(string); strupr(string);
strrev():- It is used to reverse a string.
syntax: strrev(string);

12. What is NULL string? What its length?


Programming in C

The length of a string can be stored implicitly by using a special terminating character;
often this is the null character (NULL-‘\0’), which has all bits zero. In terminated
strings, the terminating code is not an allowable character in any string. Strings with
length field do not have this limitation and can also store arbitrary binary data.

13. What are the Comparison functions using string functions?

Comparison functions:

strcmp

String Compare
strcoll

String Compare Using Locale-Specific Collating Sequence


strncmp

Bounded String Compare


strxfrm

Transform Locale-Specific String

14. Write a c program to convert the string from lower case to upper case
#include<stdio.h>
int main(){
char str[20];
int i;
printf("Enter any string->");
scanf("%s",str);
printf("The string is->%s",str);
for(i=0;i<=strlen(str);i++){
if(str[i]>=97&&str[i]<=122)
str[i]=str[i]-32;
}
printf("\nThe string in lowercase is->%s",str);
Programming in C

return 0;
}
15. Without using any semicolon (;) in program write a c program which output is:
HELLO WORLD?
void main()
{

If (printf("HELLO WORLD"))
{
}
}
16. What are the advantages of array?

Advantage of using array:


1. An array provides singe name .So it easy to remember the name of all element
of an array.
2. Array name gives base address of an array .So with the help increment operator
we can visit one by one all the element of an array.

3. Array has many application data structure.


PART – B
1. Write a C program to find the sum of two matrices. (16)
2. Write a C program to sort the given numbers in ascending order.(8)
3. Write a C program to count the letters in a sequence of characters. (8)
4. Write a C program to reverse a String (8)
5. Discuss about any eight String built-in functions. (8)
6. Explain the function (i) strlen( ) (ii) strcpy( ) (iii) strcat( ) (iv) strcmp( ) with
example (4+4+4+4=16)
7. What is an array. Explain declaration of two dimensional array and accessing an array
element (8)
8. Write a C program for matrix multiplication (16)

You might also like