Unit I&II Notes (Programming in C)
Unit I&II Notes (Programming in C)
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;
}
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
Create
Compile
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
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.
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
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
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
* / % Multiplication/division/modulus left-to-right
+ - Addition/subtraction left-to-right
|| Logical OR left-to-right
= Assignment right-to-left
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
%= &= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR assignment
<<= >>= Bitwise shift left/right assignment
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
// 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
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
)
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.
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;
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;
}
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;
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);
}
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
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
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
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
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
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];
….
Characteristics of arrays
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
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
1 2 3 4 5 6 7
This for loop is used to read 5 values to the array named ‘a’.
Programming in C
#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
0
a[0][0] a[0][1] a[0][2]
2
a[2][0] a[2][1] a[2][2]
{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
or
char name[5] = {‘C’,’S’,’E’};
Run time initialization:
We can initialize the string during execution by using the scanf( ).
• 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:
1. strlen()
2. strrev()
3. strcpy()
4. strcmp()
5. strcat()
➢ 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
Example:
char dept[10]=”CSE”,*rev;
rev=strrev(dept);
Output:
The reversed string is : ESC
➢ 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
➢ 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
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:
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.
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);
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
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
C O L L E G E \0
• 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
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);
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
#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():-
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.
Comparison functions:
strcmp
String Compare
strcoll
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?