Unit 5 : Programming Concept Class 11 Computer Notes | Based On New Syllabus


Chapter 5

Programming concepts and logics

Programming Concept

A program is a set of sequenced instructions which commands the computer to perform a particular operation or a special task. It is written in a programming language which is then translated into machine code by a language processor so that the computer can execute its tasks.  

The thorough understanding regarding the entire process of the development of programs is called programming concept. It includes the overall understanding and applications of different computer programming languages, compiler, interpreter, control structures, program design tools, syntax, semantic, programming techniques and different stages involved in a program development. 

Programming Language

A programming language is a language used by computers by which they understand to do what the program users want. It is a set of codes and written symbols that provide the platform for instructing computers to perform some specified tasks. The process of writing a program is known as coding or programming and the person who writes the program codes is called a programmer.

Programming languages are classified into two categories: Low Level Language (LLL) and High-Level Language (HLL).


Fig: Classification of Programming Language

1) Low-Level Languages (LLL)

A language that is machine dependent and/or that offers few control instructions and data types. Each statement in a program written in low level language usually corresponds to one machine instructions.

Low-level language can be divided into two types:

1.      Machine language (1GL)

2.      Assembly language (2GL)

 

I. Machine language:

The language that is called the language of CPU and is written in binary code (composed of 0 and 1) is called Machine language. In this language, a computer can understand every instructions given only in the form of 0 and 1. All the valid computer operations are performed in terms of binary operation.

 

The advantages of Machine language are:

·         The program written in machine language does not need any translation.

·         Execution time of machine language program is extremely fast.

The disadvantages of Machine language are:

·          Machine language is very machine dependent. The program written for one processor cannot be run in another processor.

·          Programming is very complex and tedious for the programmers.

·          Chances of error are high while writing a program in machine language.

·          It is very difficult to debug the program written in machine language.

·          It is very time-consuming and difficult to solve complex problems under this language.

 

II. Assembly language:

The language in which a program is written in short codes like ADD, MUL or SUB instead of writing instruction in a binary number (0 and 1) is called Assembly language. An assembler converts the assembly language to the machine language to make it understandable by computer hardware because a computer can understand the instruction written only in binary form.

 

Assembly language is not a user-friendly language. This language is also very processor dependent language. A program written for one processor does not work in another processor. Computer viruses are mostly written in this language.

The general of its instructions are shown below:

OPCODE

OPERAND

Comment

ADD

A, B

Add B to A

 

Advantages

·          Assembly language is easier to understand as compared to machine language.

·          Chances of error are less than machine language.

·          In assembly language, program execution time is faster than a program written in any high-level languages.

·          As compared to machine language, assembly language is of a more standard form of language.

·          This language is more efficient in solving hardware interfacing problems.

 

Disadvantages

·          It is a machine dependent language; it requires the knowledge of hardware while writing a program.

·          There is one to one correspondence between the assembly language and machine language instruction

·          Written in this language, a program can be very lengthy and complex for programming.

·          Execution of program is slower and less efficient than machine language.

 

2) High-Level Languages (HLL)

High level language was developed during 1960s to make programming easier and overcome the limitations of low level languages. Which are quite similar to human language such as English. The 1st high-level language was developed by John Backus, in IBM Laboratory, in 1956.

Programs written in high-level languages are translated into machine language by a language translator called a compiler or an interpreter.

High-level languages are of 3 types.

They are:

·          Third Generation Language (3GL)

·          Fourth Generation Language (4GL)

·          Fifth generation language (5GL / Natural Language)

 

Third Generation language

Third Generation language is general-purpose high-level language in which the instructions are expressed in more like English structure and mathematical. It is also known as the Procedural Oriented language because the instructions of language are written in step-by-step sequence of procedure. These are designed to express the logic and the procedure of a problem. Procedural languages are very flexible because they are able to solve a variety of problems. Examples are: FORTAN, Pascal, C, BASIC, etc.

Advantages

·          Easy for programming because the program instructions are quite similar to English like structure and mathematical expressions.

·          It is machine independent language so; we can execute program in any type of computers.

·          Very easy for modifying and finding errors.

·          Programmer does not require depth knowledge about internal hardware while programming.

Disadvantages

·          Program must be translated into machine code so; translation may take extra time.

·          They are less user friendly because mostly they are CUI based.

·          Mostly they are general purpose language so, they cannot solve complex problems.

·          They are less efficient languages as compared to 4GL.

Fourth Generation Language (4GL) :

Fourth generation language is specific purpose high level language in which the instructions are expressed by using graphical components and English like structure. It is also known as Problem oriented specific purpose language because they are developed for solving specific types of problems such as database problems, web-based problems, application development etc. 

A programmer can use either GUI environment or CUI environment for the programming. In this language more powerful and efficient mathematical and logical expressions are incorporated. Examples are: C++, Java, C#, PHP, Visual Basic, My SQL, Oracle etc.

Advantages

·          It is efficient and user-friendly language.

·          Increase the program development speed.

·          Reduce the chances of errors while writing programs.

·          Integrated Development Environment (IDE) approach helps to developer to include powerful features into an application.

·          Most of the 4GL are platform independent.

 

Disadvantages

·          Program written in 4GL requires more memory and disk storage.

·          Take more time to execution.

·          It is not suitable for solving hardware interfacing problem.

 

Fifth Generation Language (5GL)

Fifth generation language are still in the developing stage. It is also known as Natural Language, such as English, Chinses, Japanese, Nepali language would be used in computer because they computer more intelligent and user friendly. They are mainly used in the field of Robotics, AI and expert system. The high-level language PROLOG and LISP have been used as fifth generation language.  

Some of its characteristics are:

·          More user friendly.

·          Machine independent.

·          Make computers more intelligent and natural.

·          Make human and machine closer than before.

·          They are used in the areas of research, robotics, defense system and different types of expert systems.

·          It requires more memory and more time to execute.

 

Language Translator

Language translator is a program which is used to translate instructions that are written in the high-level language (source code) to Machine code (object code) i.e. from high-level language or assembly language into machine language. There are 3 types of language translators, they are:

 

1.    Assembler:

Assembler is the language translator designed to translate assembly language program (source codes) into machine language program (object codes). The original assembly language program codes are called source codes and after translation, the final machine language program codes are called object codes.


Fig. Assembler

2.    Compiler:

A compiler is a language translator that translates high-level languages program to machine language program. While translating, it checks the syntax (grammar of the source code) and translates it into object code at a single attempt. If any error is found, the compiler produces syntax errors with causes of the errors. The source code file must be syntax error-free for complete compilation process.


Fig. Compiler

3.    Interpreter:

The interpreter is the language translator designed to translate high-level language program into machine language program, one instruction at a time. Unlike the compiler, it translates and executes one statement at a time before moving to another. If any error is encountered, the translation is halted and an error message is displayed.

 


 Figure: Interpreter

 

Differences between Compiler and Interpreter: (IMP)

Compiler

Interpreter

It translates a complete high-level language program into machine language at once.

It translates high-level language program into machine language line by line.

It finds the syntax errors after compiling the whole program.

It finds the syntax errors after translating each line of the program.

The compiling process is faster than the interpreter.

The interpreting process is slower than a compiler.

The debugging process is complicated in a compiler.

Debugging process is easy in the interpreter.

It creates object code.

It does not create object code.

Compiler demands more resources (memory, CPU time etc) than interpreter.

Interpreter requires low resources.

Example: C, C++, Visual Basic, java, etc.

Example: BASIC, LISP etc.

 

Introduction to C Language


C programming was introduced by Denis’s rich in 1972 at 80 and TS bills laboratory. it is popular because of its simplicity reliability and easy to use. tablet good programming efficiency as compared to the machine-oriented language.


Features of C Language:

a.       It is case sensitive language show the meaning of application lowercase are different.

b.      It is structured programming language that we can break large program into different part by using function.

c.       It has 32 keyboards.

d.      program develop on C are easy to develop.

e.      It includes the feature of DMA recursive and pointer.

f.        It is the mid-level programming language in the sense of that it combines the feature of high level with the functionality of assembly level language.

g.       It is used to develop system program. program develop and C are portable.

h.      It is robust language.

Advantage of C language:

a.       C is portable language.

b.      It is free form language show problem can start from any line and column.

c.       A lot of libraries are return in she as compared to previous programming language.

d.      C is a building block for many other currently non languages.

e.      C language is the fundamental programming language also known as the mother of all other modern languages.

Disadvantage of C language

a.       C does not have the concept of name space.

b.      C does not have the concept of constructor and destructor.

c.       it is not design or entered.

d.      hard to run in latest operating system.

e.      it is case sensitive language show mixing of cases make difficult while programming.

f.        there is no strict type checking.


Basic structure of C program

1.      header file

2.      main function

3.      variable declaration

4.      input statement

5.      processing statement

6.      output statement


Example:

#include <stdio.h>                                          

//header file

Int main()                                                       

{

//main function

int a,b,c;

//variable decleration

printf(“Enter any two number:\n”);            

//input statement

scanf(“%d %d”,&a,&b);                                

//input statement

c=a+b;                                                           

//processing statement

printf(“Sum : \t”,c);                                       

//output statement

}

 


Header file:
It consist of the function definition of the library function. they are return at the top of the program. from up the commonly used header file are: 

·          #include<stdio.h>

·          #include<conio.h>

·          #include<string.h>

·          #include<math.h>

C Processor: (IMP)

The C preprocessor is a macro processor that is used automatically by the C compiler to transform your program before actual compilation. It is called a macro processor because it allows you to define macros, which are brief abbreviations for longer constructs.

Operators:

C program consists of different kinds of character set and symbols which has some special meanings. Operators are the symbols used  in  between  the  operands  in-order  to  perform  some  specific  task  such  as mathematical or logical operations.

There are various types of operators available in C and some of frequently used operators are:

a) Arithmetic operator

It is used to perform some basic arithmetic operations such as addition, subtraction, division, multiplication between numbers of operands. They are:

Operator

Name

Example

+

Addition

a+b

-

Subtraction

a-b

*

Multiplication

a*b

/

Division

a/b

%

Modulus division

a%b

 

b) Relational operator

It is used to create a relationship between  operands i.e. they are used to  compare values of  the  given operands. It may provide either TRUE value (1) or FALSE value (0), depending upon the values of the operands. The relational operators are described in following table.

Operator

Name

Example

> 

Greater than

a > b

< 

Less than

a < b

>=

Greater than or equal to

a >= b

<=

Less than or equal to

a <= b

= =

Equal to

a = = b

!=

Not equal to

a != b

 

c) Logical operator

It is used to create a logical relationship between operands. These operators are used to combine two or more than two expressions. Some logical operators are given below.

Operator

Name

Example

&&

Logical AND

a  > b && a > c

||

Logical OR

a > b || a > b

!

Logical NOT

a ! b

 

 

d) Increment / Decrement operator

The increment and decrement operators are unary operators, which takes only one operand.  The increment operator (++) adds the value 1 to the current value of the operand and the decrement operator (- -) subtracts the value 1 from the current value of the operand. These operators are extensively used in loop control structures in C. Further, the increment and decrement operator are divided into categories:

postfix and prefix increment / decrement operator. 

             Postfix increment (operand ++)

             Prefix increment (++operand)

             Postfix decrement (operand - -)

             Prefix increment (- -operand)

 

e) Assignment operator (=)

It is used to assign value to an operand as well as is used to copy value of an operand to another operand. There may be one or more operands right (after) to the assignment operator but only one operand left (before) to the assignment operator. Let us consider:

x = 100;     // value 100 is assigned to variable x

y = x;          // the value of x is copied or assigned to variable y

z = x + y;    // first the value of x and y are added, then only the added value is assigned to variable z.

 

Invalid assignment operators x + y = z;
100 = x;

 

f)  Compound operator

Compound operators are combination of arithmetic and an assignment operator. Generally, it is used to write short, concise and more efficient codes in the program.  Some compound operators and its meanings are:

Operator  

Expression                 

Meanings

+ =       

             a + = 10                      

         a = a + 10

- =        

            a - = 10                       

         a = a – 10

* =       

             a * = 10                      

         a = a * 10

/ =       

             a / = 10                       

         a = a / 10

% =       

            a % = 10                      

        a = a % 10

 

g) Conditional operator (? :)

Conditional operator is a ternary operator which requires three expressions as operands. It is denoted by? and: symbol.

Syntax:      test condition? True expression: False expression

E.g.            a > b? a: b

In such expression, firstly the test condition is evaluated, if the condition is satisfied then TRUE expression is evaluated, otherwise FALSE expression is evaluated.

 

h) sizeof( ) operator

It is a unary operator. This operator gives the size of its operand in terms of bytes  occupied  in  the memory. The operand can be a variable, constant or any data type: int, float, char, etc. Example:   result = sizeof(x);

Here sizeof() operator calculates the memory space occupied by variable x and is assigned to variable result.

Control Structure

Control structure is the set of instructions which are used to monitor, regulate or control the flow of instructions in the program. There are three types of control structures used in C programming. They are:



a. Sequential structure

b. Selection structure

c. Iteration structure

 

Sequential structure

The sequential structure consists of a sequence of programming statements (instructions) which are executed one after another in a linear order. In this structure, the first statement is executed first, after completion of the statement; second statements are executed and so on all the statements of the program are executed in their turn. The sequential order is described in following flowchart and algorithm

Syntax:


Statement 1
Statement 2
Statement 3
…………………..
…………………..
…………………..

Statement N 



 

//Program to calculate simple interest and mixed amount

 

#include<stdio.h>

void main()

int p;

float t,r;

printf("\n Input Principal Amount:- "); 

scanf("%d", &p);

printf("\n Input Time Period:- "); 

scanf("%f", &t);

printf("\n Input Rate of Interest:- "); 

scanf("%f", &r); 

i=(p*t*r)/100; 

printf("\n Simple interest = Rs %f",i); 

}

 

Selection Control Structure

The decision-making structure is also called selective structure.  In this structure either certain block of statements is executed or skipped according to the set of condition applied. In C language there are four keywords: if, if-else, if-else if and switch-case for selection control structure and those are discussed in following section.

 

a)   if statement

It is simplest form of selection. In this structure only single condition is applied but its alternative is not mentioned. The block of statements associated with the if are executed in sequential order if the given condition has been satisfied otherwise those statements are skipped and the immediate next statements are executed. The syntax and flowchart are shown as below.

 

Syntax:

if (test_condition)

{

Statement 1; 

Statement 2; ……………...

………………

Statement N;

}

 

Example:

void main()

{

int salary;  

float bonus;  

printf(“Input Salary:- );  

scanf(“%d”, &salary); 

if(salary>10000)

{

bonus=salary*0.10; 

printf(“Bonus = %f”, bonus);

}

b)  if-else statement

If a given problem has one condition and two alternative actions, then we can use if else statement. If the given condition is true, statement 1 will be executed otherwise statement 2 will be executed.

Syntax:

if (test_condition)

{

Statement 1; 

}

else

{

Statement 2;

}

 


Nested if-else statement

An entire if else statement written with in the body of if or else part of another if else statement is called nested if else statement. It is used when condition is to be checked inside another condition at a time in the same program to make decision.

 

Syntax:

if(condition 1)

{

    if(condition 2)

       {

          Statement 1;

        }      else 

     {

         Statement 2;

       }

}

else

{

Statement 3;

}

 



c) if-else if……. else statement

It is used for multiple conditions. It is also known as multi-way if else or if else ladder. If any one condition among all of them is true then rest of all will be false. Then if all of the given condition are not true, then the else statement will be executed.

The general format of nested if-else is:

 

Syntax;

if (contion1)

{

Statement 1; 

}

else if (condtion2)

{

Statement 2; 

}

 

…………………..

…………………..

else if (condition n-1)

{

Statement n-1; 

}

else

Statement n; 

}

 


 

d) switch case statement

The control statement that allows us to make a decision from a number of choices is called a switch. Switch is a mechanism of jumping into a series of statements, the exact starting point depending on the value of the expression. The switch expression is evaluated, and then the flow of control jumps to the matching expression case. The case expressions are typically numeric or character constants. If no match is found, the statements following the default are executed.

 

Syntax:

switch(expression) {

case value 1:

Block of statements;

break;

case value 2:

Block of statements;

break;

.......

case value n:

Block of statements;

break;

default: Statement;

} 

Example:

#include<stdio.h>

void main()

{

int choice;

printf("Input Your Choice:"); 

scanf("%d", &choice);

switch(choice)

{

case 1:

printf(“Sunday”);

break;

case 2:

printf(“Monday”);

break;

case 3:

printf(“Tuesday”);

break;

case 4:

printf(“Wednesday”);

break;

case 5:

printf(“Thursday”);

break;

case 6:

printf(“Friday”);

break;

case 7:

printf(“Saturday”);

break;

default:

printf(“Invalid Choice”);

}

}

 

Looping Control Structure

The mechanism which repeats some portion of instructions either a specified numbers of times or until a certain condition has been satisfied is called loop. This repetitive operation is done through a loop control structure.

There are three methods through which we can repeat a part of program. They are:

a.       for loop

b.      while loop

c.       do…. while loop

 

for loop

It is a pre-test or entry control loop, in which a statement or block of statements are executed for certain number of times. A for loop allows us to specify three things about a loop in a single line and they are:

  • Loop’s initial value i.e., to set loops starting value.
  • Test condition i.e., to determine the number of repetitions
  • Increment or decrement value (loop update)

 

In this structure, the condition is tested at first, if it is satisfied then only the block of statements associated with the loop are executed till the given condition has been true, otherwise those statements are skipped and the control is automatically transferred to the next immediate statement after the loop. The syntax and flowchart is shown as below.

 

Syntax:

for (initial value; test condition; loop update)

{

Statement 1; 

Statement 2;

……………

……………

……………

Statement N;

}


 

 

Example:

 

#inclue<stdio.h>

void main( )

{

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

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

}

 

Output:

0 1 2 3 4

 

while Loop

It is used to repeat a statement or number of statements for specified number of times or certain condition has been satisfied. The statements within the while loop gets executed till the condition remains true. When the condition becomes false, the control is passed to the first statement out of the loop. It is also known as entry control or pre-test loop because the condition is applied at the top of the loop before the control enters or passes inside the body of the loop. It will not execute its statements if the condition fails for the first time. The execution of a while loop is shown in following figure.


 

 

Syntax:

Initial value of loop;

while (test_condition)

{

Statement 1; 

Statement 2;

……………

……………

…………… 

Statement N; 

Loop Update;

}

 

Example:

/*Illustration of while loop*/

#include<stdio.h>

void main()

int i=1;

while(i<=10)

{

printf("%d \t",i); i=i+1;

}

}

Output:

1   2   3   4   5   6   7   8   9   10

do ….. while loop 

 It is also used to repeat a statement or number of statements for specified number of times or certain condition has been satisfied. The statement within the do-while loop gets executed till the condition remain true.  When the condition becomes false, the control is passed to the first statement out of the loop.  The minor difference between while and do-while loop is- placement of the condition. In dowhile loop the condition is placed at the bottom of the loop and it is tested after the statements have been executed. This means that do-while loop will execute its statements at least once, even if the condition fails for the first time. So, it is known as exit control loop. 


 

Syntax:                                                                                                                              

Initial value of loop; 

do

{

Statement 1; 

Statement 2; 

……………

…………… 

Statement N; 

Loop Update;

} while (test_condition);

 

Example:

 

/*Illustration of do-while loop*/

#include<stdio.h>

void main() 

{

int i =1 ;
do

{

printf("%d \t",i); i=i+1;

} while(i<=10);

}

 

Output:

1   2   3   4   5   6   7   8   9   10

 

Loop Interruption:

Loop interruption is a process of skipping a part of the loop or quite the loop abnormally while executing. There are two keywords: break and continue used to interrupt the flow of a loop. 

 

The Break Statement:

The break statement allows us to exit a loop from any point within its body i.e., abnormal termination of the loop.  When the break statement is encountered inside a loop, the loop is immediately terminated, and program control is transferred to the next statement after the loop. 

Example:

 

#include<stdio.h>

void main()

{

             int i;

             for(i=1; i<=5; i++)

            {

             if(i==3)

             break; 

             printf("%d \t", i);

            }

}

 

Output:

1   2

 

The continue Statement:

The continue statement in C programming works somewhat like the break statement. Instead of forcing termination, it forces the next iteration of the loop to take place, skipping any code in between.

 

#include<stdio.h>

void main()

{

             int i;

             for(i=1; i<=5; i++)

            {

             if(i==3)

             continue;          

             printf("%d \t", i);

            }

}

 

Output:

1   2   4   5   

 

 

Difference between while loop and do while loop (imp)

while

do while

It is entry-controlled loop or pre-tested loop.

It is exit controlled loop or post tested loop.

It checks the condition first then executes the loop body.

It executes the loop body first then checks the condition.

It uses keyword while.

It uses keyword do and while.

It is not terminated by semicolon.

It is terminated by semicolon. 

Syntax:

 while (condition) {

             statements;

}

 

Syntax:

do {

  statements

} while (expression);

 

Example:

 

Example:

**Example write yourself.

 

Nested for loop

C allows loops to be nested, that is one for loop present inside another for loop is called nested for loop.

Syntax:

for(initial_value; test_condition; loop_update)

{

                for(initial_value; test_condition; loop_update)

            {

             Statements;

}

}

 

Example 1:

 

#include<stdio.h> void main()

{

             int i, j;

             for(i=1; i<=5; i++)

            {

                         for(j=1; j<=i; j++)

                        {

                                     printf("%d", j);

                        }

                         printf("\n");

            }

}

Output:

1

12

123

1234

12345

 

Example 2:

 

#include<stdio.h>

void main()

{

            int i, j;  for(i=1; i<=5; i++)

            {

                         for(j=5; j>=i; j--)

                        {

                                     printf("%2d", j);

                        }

                         printf("\n");

            }

}

 

Output

5 4 3 2 1

 5 4 3 2

 5 4 3

 5 4

 5

Array and Strings

Introduction:

Array by definition is a variable that hold multiple elements which has the same data type in a continuous memory location. An array is also known as a subscripted variable.

 

Types of arrays:

There are two types of arrays:

a.       One dimensional array (1D array)

b.      Two-dimension array (2D array)

 

1-D Array and Declaration

In this structure arrays are stored either in row or column i.e., either in X-direction or Y-direction. 1D array has only a single subscript.

 

1-D array should be declared before using it and we can declare an array by specifying its data type, name and the fixed number of elements the array holds between square brackets immediately following the array name.

 

Syntax: Data_type array_name [size]; 

Example: int marks[5];

 

Note: The size of an array must be pure positive integer value. Followings are invalid in the case of defining size of an array.

•       We can’t use floating point.

Example: int marks[5.5]; · We can’t use characters. Example: int marks[five];

•       We can’t use any special symbols

Example: int marks[%];

•       We can’t use negative value

Example: int marks[-5];

 

Memory arrangement:

1001

1003

1005

1007

1009

Memory address

2001

167

231

11223

19803

Element

Num[1]

Num[2]

Num[3]

Num[4]

Num[5]

Index number

Fig: Memory Allocation of 1-D Array

 

Initialization of Arrays:

If the array elements are not given any specific values, they are supposed to contain garbage values. The values are managed to store values in them during program execution. The process of defining initial values to the array is known as initialization of 1-D array.

 

Syntax:

Data_type array_name [size] = {Elements}; Example:

int marks[5] = { 50, 65, 34, 45, 85};

Memory arrangement:

1001

1003

1005

1007

1009

Memory address

50

65

34

45

85

Element

Num[1]

Num[2]

Num[3]

Num[4]

Num[5]

Index number

Fig: 1-D Array Initialization

 

Accessing of 1-D Array elements:

Once the array is declared, we have to access those array elements for our requirements. Array elements are accessed with its subscript, the number in the brackets followed in the array name i.e.  through its index number.  This number specifies the elements position in the array.  All the array elements are numbered, starting with 0 and ending with size – 1, where size is the total size of the array. Generally, a single for loop is associated with 1-D array while entering data into an array or reading elements from the array. This is illustrated in following program.

#include<stdio.h>

void main()

{

int i, num[5];

printf("Input any five numbers: - ");           /* entering elements into an array*/

for(i=0;i<5;i++) scanf("%d", &num[i]);      /*Reading elements from array and displaying to the monitor*/

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

printf("%d \t",num[i]);

}

 

Multidimensional (2-D) Arrays:

The data in 2-D array are arranged in tabular form i.e., in number of rows and columns. It consists of two subscripts in which first gives the number of rows size and the second number gives the column size. The number of elements that a two-dimensional array is defined as the product of row size and column size Declaration of 2D array:

Syntax:

Data_type array_name [row_size][column_size]; 

Example:

int num[3][4]; 

 

Initialization of 2D array:

Syntax:

Data_type array_name [row_size][column_size] = { Elements };

Example:

 int num[3][4] = {  

{ 10, 12, 34, 40 },

{ 23, 21, 01, 10 },

{100, 91, 83, 49}

}; 

Or

even we can initialize 2-D array as:

 

int num[3][4] = { 10, 12, 34, 40, 23, 21, 01, 10, 100, 91, 83, 49};

 

Note:  In case of initialization of 2-D array the order of row is optional but the order of column is compulsory. Following initialization process is invalid in 2-D array

             int num[3][ ] = { 10, 12, 34, 40, 23, 21, 01, 10, 100, 91, 83, 49};

             int num[ ][ ] = { 10, 12, 34, 40, 23, 21, 01, 10, 100, 91, 83, 49};

 

                

Memory management                     

Col[0]   Col[1] Col[2]           Col[3]

 

Col[1]

Col[1]

Col[1]

Col[1]

Row [0]

10

12

34

40

Row [1]

23                 

21                  

1                  

10

Row [2]

100

91

83

49









Fig: Memory Arrangement of 2-D Array

 

Accessing of 2-D Array:

#include<stdio.h>

void main()

{

int i,j, num[10][10];

//entering the array elements to the matrix

printf("Input the elements of 3 X 3 matrixes :- ");  

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

                {

for(j=0;j<3;j++) scanf("%d", &num[i][j]);

}

/* Displaying the matrix*/

printf(" The Given matrix is:\n");

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

{

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

                {

  printf("%d \t",num[i][j]);

                }

printf("\n");

}

}

 

Output:

Input the elements of 3 X 3 matrixes: - 1      2     3     4     5     6     7     8     9

The Given matrix is:

1 2 3

4 5 6

7 8 9

Introduction to String

Collection of interrelated characters i.e.  arrays of characters are known as string.  Such character arrays or string are used by programmer in the programming language to manipulate text such as word, sentence or paragraphs.

A string consonant is a 1-D array of characters terminated by a null (“\0”) character. For example:

char name [ ] = { ‘C’, ‘O’, ‘M’, ‘P’, ‘U’, ‘T’, ‘E’, ‘R’, ‘\0’ };

or

char name [ ] = “COMPUTER”; 

Each character in an array occupies 1 byte of memory space and the last character is always the null character, which denotes the end of character.  The following figure shows the way a character array is stored in contiguous memory locations.  

1000

1001

1002

1003

C

O

D

E

Fig : Memory arrangement of string

 

Manipulation of string

Let us consider following program.

#include<stdio.h>

void main()

{

int i=0;

char name[]="COMPUTER"; while(i<8)

{

printf("%c", name[i]);

i++;

}

Output: COMPUTER

 

In above program we have initialized a character array, and then we have printed the strings using while loop. This method is not very much applicable because we can’t write the while loop without using the final value 8 i.e., we can’t determine the length of string in advance, so it is impractical. As we know that each character array always ends with a “\0”. Following program shows this process.

 

#include<stdio.h>

void main()

{

int i=0;

char name[]="COMPUTER";

while(name[i]!='\0')

printf("%c",name[i]);  

i++;

}

}

 

Output:

COMPUTER

Above program does not depend on the length of the string to print the contents of the string. So it is more general than the earlier program.

Even we can refer to the elements of a character array using printf() function ( it doesn’t print the “\0”) with %s format specifier. The same specifier is also used to receive a string form the keyboard. This is illustrated in following program

 

#include<stdio.h>

void main()

{

int i=0;

char name[20];

printf("\n Input any string :- ");

scanf("%s", name);

printf("%s", name);

}

 

Output:

Input any string: - COMPUTER

COMPUTER

In above program a character array name[20] is declared which reserves  20 bytes space in memory. The scanf() function accepts the characters entered through the keyboard and stores in the array until the enter key is pressed by the user. Once the enter key has been pressed the scanf() function places the null character (“\0”) in the array. But the scanf() function has limitations.  i.e. scanf() function can’t receive multiple word strings.

Such limitation is eliminated by gets() function. The working mechanism of gets() and puts() function is illustrated in following program.

 

#include<stdio.h>

void main()

{

char name[50];

printf("Input your name:");

gets(name);

puts(name); 

}

 

Output:

Input your name: -Galaxy

Galaxy

 

Note:  gets() function: gets() function is used to scan or  read string or a line of text from a standard input device and store it in the String variable. 

Syntax:

gets(argument);

 puts() function: puts() function is used to write string or a line to the output screen.

Syntax:

puts(argument);

String related functions

In C compiler there are many useful string manipulating library functions. Some of the main functions are described below.

 

1.   strlen()

             This  function  is  used  to  count  the  number  of  characters  present  in  a  string  (including  number  of spaces present in the string, excluding null character).

             It takes single argument as an input.

             It returns pure positive integer value.

Syntax:           strlen(argument);

Example:        strlen(“Computer”);

Output:          8

 

The use of strlen() function is illustrated in following program. 

#include<stdio.h>

#include<string.h>

void main()

{

char string[50];  

int length; 

printf(" Input any string: ");

gets(string);

length=strlen(string);

printf("There are %d characters in input string", length);

}

 

Output:

Input any string: - Galaxy Secondary School

There are 23 characters in input string

 

2.   strcpy()

             This function is used to copy the contents of one string to another string.

             It takes two arguments. The base address of the source string (from which we want to copy) and the destination string (into which we want to copy) is supplied to this function.

·         It returns the array of characters.

Syntax:           strcpy(destination, source);

Example:        strcpy(string, “Computer”);

Output:          Computer

 

The use of strcpy() function is illustrated in following program.

 

#include<stdio.h>

#include<string.h>

void main()

{

char source_string[50], target_string[50];

printf("Input any string:");

gets(source_string);

strcpy(target_string, source_string);

printf("\n The source string is %s", source_string);

printf("\n The Copied string is %s", target_string);

3.   strcmp()

             This function is used to compare two strings to find whether they are identical or not.

             It takes two arguments.

             The two  strings  are  compared  character  by  character  (i.e.  the first  character  of  the  first  string  is compared to the first character of second string, if it matches then the second character of the first string is compared with the second character of the second string and so on) until the end of one of the strings is reached or until there is a mismatch between the strings, whichever comes first. The function returns an integer value.

             The  function  returns  a  zero  value  when  both  strings  are  identical  otherwise  it  returns  numeric difference between the ASCII values of the first non-matching pair of characters.

Syntax:           strcmp(text1, text2);

Example:        strcmp(“Computer”, “Computer”);

Output:          0

 

The use of strcmp() function is illustrated in following program.

 

#include<stdio.h>

#include<string.h>

void main()

{

char text1[50],text2[50];

int difference;

printf("Input first string:");

gets(text1);

printf("Input second string:");

gets(text2);

difference=strcmp(text1,text2);

if(difference==0)

printf("Both strings are identical");

else printf("Both strings are non-identical");

}

 

4.   strlwr()

             This function is used to convert any upper-case text of a string into its equivalent lower case.

             It takes only one argument as an input.

             It returns single argument into its equivalent lower case.

Syntax:           strlwr(argument);

Example:        strlwr(“COMPUTER”);

Output:          computer

 

The use of strlwr() function is illustrated in following program.

#include<stdio.h>

#include<string.h>

void main()

{

char string[50];

printf("Input any string:");

gets(string);

strlwr(string);

printf("The lower case is %s", string);

}

5.   strupr()

             This function is used to convert any lower-case text of a string into its equivalent upper-case text.

             It takes only one argument as an input.

             It returns single argument into its equivalent upper case.

Syntax:           strupr(argument);

Example:        strupr(“computer”);

Output:          COMPUTER

 

The use of strupr() function is illustrated in following program.

 

#include<stdio.h>

#include<string.h>

void main()

{

char string[50];

printf("Input any string:");

gets(string);

strupr(string);

printf("The upper case is %s",string);

}

6.   strcat()

·         This function is used to concatenate the source string at the end of the target string (without space between source and destination string).

·         It takes two arguments.

·         It returns a concatenated string.

Syntax:           strcat(argument1,argument2);

Example:        strcat(“Computer”, “Science”);

Output:          ComputerScience

 

The use of strcat() function is illustrated in following program.

 

#include<stdio.h>

#include<string.h>

void main()

{

char string1[50], string2[20];

printf("Input First string: "); gets(string1);

printf("Input Second string:"); gets(string2);

strcat(string1,string2);

printf("The complete string is %s",string1);

}

 

7.   strrev()

             This function is used to reverse the characters in the string.

             It also takes one argument

             It returns single argument is reverse of the given string.

Syntax:           strrev(argument);

Example:        strrev(“Computer”);

Output:         retupmoC

 

The use of strrev() function is illustrated in following program.

#include<stdio.h>

#include<string.h>

void main()

{

char string[50];

printf("Input any string: - ");

gets(string); strrev(string);

printf("The reverse string is %s", string);

}

Getting Info...

Post a Comment

Please do not enter any spam link in the comment box.
Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.