(XI) Ch-5 Programming Language and C Programming

1. Types of Programming Lang. 2. Compiler, Assembler
3. Algorithm, flowchart 4. C preprocessor
5. Data Type 6. C operator
7. Selection statement 8. switch case
9. Looping 10. Nested Loop
11. Jumping statement 12. Array (1-D)
13. Array(2-D) 14. String

5.1.1 Introduction to Programming Language

Language is a means of communication between two people. Human beings use languages such as Nepali, English, French, etc. during communication. A language used by human beings is known as natural language, whereas a language used by a computer is known as programming language or computer language. Programming language helps us to make a common platform for developing programs or applications in a computer. The process of writing a program is known as programming or coding. A person who writes program codes is known as a programmer.

Programming language is defined as a set of rules that provides a platform for instructing computers to perform some specific tasks.

Hundreds of programming languages have been developed in the last fifty years. But, commercially only few of them are popular because of their simplicity, efficiency and compatibility to computer systems. Programming languages are classified into various ways. Based on the nature of languages, they are classified into two categories: general purpose and specific purpose. General purpose programming languages are used for solving almost all types of problems and the specific purpose programming languages are used for solving problems of specific nature.




5.1.2 Low level, High level, 4 GL programming Languages (Types of Programming Languages)

Programming languages are classified into two categories: high level languages (HLL) and low level languages (LLL). Low level languages are closer to the languages that the computer internally uses itself. Machine language and Assembly language belong to this category. The instructions used in the high level language are very close to the English like structure and mathematical expression. Third generation, fourth generation and fifth generation languages belong to this category. The following figure shows the classification of programming languages.



Machine Language

Machine language is the first language of a computer system. It is the language of the CPU till date. In the early days of computing, there was no complex hardware and software, so machine language was used for data input/output and process. It consists of sets of instructions composed with 0s and 1s that represent electrically off state and on state Machine Language pectively in computer systems.

Machine language is the language of CPU which consists of instructions composed of 0s and 1s.

A binary program is a long list of 0s and 1s which are executed by a CPU. Generally, instructions are executed one after another, but there is some mechanism to jump instructions from one line of instruction to another. Note that each computer has its own set of machine language instructions based on its architecture. Therefore, machine language differs from one computer to another. For example: a machine language instruction to calculate the sum of two numbers for an IBM machine would be 10000001. The machine code for the same purpose would be different for a UNIVAC machine. It is the only one language still being used by digital computers.

Advantages of Machine Language
  • Machine language does not require a translation process because it is the language of CPU, so it does not require a translator program.
  • Execution time of a machine language program is extremely fastest.
Disadvantages of Machine Language
  • Programming is a complex and tedious job for the programmers.
  • Machine language program can support only specific hardware; therefore it is machine dependent.
  • It is time consuming for programming and it is not possible to solve the complex problem.
  • It is difficult for finding errors and modification of the program.
Assembly Language

During the 1950s, some standard programming languages were developed to reduce programming complexity of machine languages. Bob Nevelen, Jack Powell, Clement and Michael worked together in the development of assembly language in IBM laboratory.

Programming could easily be done by using alphanumeric symbols instead of 0s and 1s. Meaningful and easily memorable symbols are selected for this purpose. For example: ADD for addition, SUB for subtraction, MUL for multiplication, COM for comparison etc. Such symbols are known as mnemonics. A program written using mnemonics is called an assembly language program.

Assembly language is a special type of low level language which consists of a set of alphanumeric instructions, called mnemonics.

The general format of assembly language instructions is shown in the following example. ADD is a keyword for addition, A and B are common register variables in the processor and comment has no effect in the program.

Assembly language instruction format
OPCODE OPERAND Comment
ADD A,B ;Add B to A

The set of original program instructions is known as source code. A translator program must translate the assembly codes into equivalent machine codes before execution. Machine code is known as object code. The translation is done by a special translation program called assembler. Moreover, assembler automatically traces the errors in assembly program codes and gives messages about the causes of errors. Assembly language allows programmers to interact directly with the hardware. So, it is a more efficient and powerful language for solving hardware interfacing programs.

Advantages of Assembly Language
  • It is easier to understand than machine language.
  • It is a more standard form of language as compared to machine language.
  • It consumes very less memory so; it executes very fast as compared to high level languages.
  • It is more efficient for solving hardware interfacing problems. For example: operating system kernel, programming language, utility software, virus, etc. 
  • It is easier to find the errors because the translator program itself identifies errors.
Disadvantages of Assembly Language
  • Different computer systems have their own assembly languages, so they are not compatible with others. They are still being machine dependent.
  • A program written in assembly language is very lengthy and complex for programming.
  • Programmers should have in- depth knowledge about the computer hardware during programming.
  • Program execution is slower and less efficient than machine language.
Third Generation Language (3GL)

High level languages were developed during the 60s to make programming easier and overcome the limitations of low level languages. General purpose first high level language is known as third generation language. In 1956, FORTRAN (Formula Translation) was the high level language developed by John Backus in IBM laboratory. The instructions of high level language are called statements which are expressed like human language such as English. More mathematical and logical expressions (True / False) are used to form statements.

Third generation language is general purpose high level language in which the instructions are expressed in more like English structure and mathematical expressions

Mostly, they are general purpose and machine independent languages. Examples of third generation languages are: FORTRAN, BASIC, Pascal, C, etc. They are also known as procedural languages because the instructions of language are written in step by step sequence of procedures. For example, consider a BASIC program to calculate the area of a rectangle in figure below. The first two statements of the program store the values 5 and 6 into the variables L and B respectively. The third statement defines a new variable AREA and it stores the product and finally prints the output on screen.

QBASIC program to calculate area of rectangle
L=6 B=5 AREA=L*B PRINT AREA END ---------------------------- OUTPUT : 30

Even though the high level languages have a number of significance, the instructions must be translated into machine language before execution. The translation process may take some extra processing time. The translation is performed by a language translator program such as interpreter or compiler. Most of the third generation languages are general purpose therefore they are not considered as efficient and reliable programming languages than fourth generation programming languages.

Advantages of 3GL
  • It is easy for program development because the program instructions are quite like English like structure and mathematical expressions.
  • It is a machine independent language, so we can execute programs on any type of computer.
  • It is easy for modifying and finding errors (debugging).
  • Programmers do not require in- depth knowledge about the internal hardware while programming.
Disadvantages of 3GL
  • Program must be translated into machine code.So, the translation process may take extra time.
  • Mostly, they are general purpose languages, so they cannot solve complex and specific types of real-world problems.
  • They are mostly CUI (Character User Interface) based languages. so, they are less user friendly languages.
  • They are less efficient languages as compared to fourth generation languages.
Fourth Generation Language (4GL)

Problem oriented specific purpose high level languages are called fourth generation Languages. They are specially developed for solving specific types of problems such as database problems, web-based problems, application development etc. Mainly they are GUI (Graphical User Interface) based languages which help to make an attractive interface to access databases. More powerful and efficient mathematical and logical expressions are also incorporated. They are easier for programming than any other programming languages.

A programmer can use either a text environment just like a third generation or graphical environment, also commonly known as visual environment. In a text environment, programmers use English like structures or mathematical expressions just like 3GL. In a visual environment, a single line of instruction may perform the same task as many lines of source code in third generation languages.

Fourth generation language is specific purpose high level language in which the instructions are expressed by using graphical components and English like structures.

Moreover, in a visual environment, a programmer uses a toolbar to drag and drop various graphical components or objects like form, button, text box, list box, radio button, file browser box, etc. in order to create visual definition of an application. Moreover, a programmer can assign various actions to these objects on screen. For example: a program may place a button on screen and assign an action to close the application.

Fourth generation languages are further classified into the following subcategories:

  1. Database and Query Processing Languages : They allow users to maintain database management systems. They also help to generate customized forms and reports of the database. A form is an interface to enter data into a database. A report is simply information from a database for printing purposes. Examples: DBase, Sybase, DB2, MySQL , MS Access, MS SQL server, Oracle etc.
  2. Application Generator Languages : They allow programmers to make any kind of application software as well as system software. Such languages are popular too. Examples: Visual.net , Visual InterDev, Visual C++, Java, C# etc.
  3. Web Based Scripting Languages : They allow programmers to develop web based applications. They are not considered as complete programming languages. They are only used to place the information in web sites and help for accessing databases of a server. Examples: HTML, XML, JavaScript, VBScript, ASP, PHP, JSP, etc.
Advantages of 4GL
  • It is an efficient and user-friendly language.
  • It helps for rapid application development. Programmers can design, create and debug an application in a very short period of time.
  • Integrated Development Environment (IDE) approach helps developers to include powerful features of different programming languages into one application.
  • Most of the fourth generation languages are platform (operating system) independent.
Disadvantages of 4GL
  • Program written in 4GL requires more memory and disk storage therefore, it takes more execution time.
  • It is not suitable for solving hardware interfacing problems.
Fifth Generation Language (5GL)

Fifth generation languages are still in the developing stage. It is also known as a natural language. Natural languages such as English, Nepali language would be used in computers because they make computers more intelligent and user friendly. They are used particularly in the areas of robotics, artificial intelligence and expert systems. Countries like the USA and Japan are still trying to make these kinds of languages.

Fifth generation language is a special type of future generation language in which the statement will be expressed more like human language.

The high level languages like PROLOG and LISP have been used as fifth generation languages. Some of the characteristics of fifth generation language are as follows:

  • Natural languages make humans and machines closer than before.
  • They are designed to allow the computer to become more natural and intelligent.
  • They are used in the areas of research, robotics, defence system, and different expert systems.
Assignment XI - Ch 5(1) 1. Draw classification chart of programming languages. 2. Compare program and programming language. 3. List any five third generation languages. 4. List any five fourth generation languages. 5. List any three research areas of fifth generation languages.


5.1.3 Compiler, Interpreter and Assembler (Language Translator)

A language translator is a special type of system software that converts a program written in any programming language (except machine language) into machine language program. It is also known as a language processor. A program code written using any programming language is called source code. A program code obtained after converting source code by using language translator is called object code or machine code. Mainly, there are types of language translators: assembler, compiler and interpreter.


Assembler

Assembler is defined as a language translator which translates assembly language programs into machine language programs. As computers understand only machine language, assembly language programs must be translated into machine language programs before execution. Otherwise, computer does not understand the codes. The original assembly language program codes are known as source codes and after translation, the final machine language program codes are known as object codes. The job of assembler is shown in the following figure.


Interpreter

An interpreter is a language translator which translates a high level language program into machine language program one instruction at a time. Unlike a compiler, it translates one statement of a program, executes the statement immediately and moves to the next statement. When an error is encountered in the program, the process of translation is halted and an error message is displayed. Programming languages such as QBASIC, LISP etc use interpreters. The job of interpreter is shown in the following figure.

Compiler

A compiler is a language translator which translates a high level languages program into machine language program. The original code of high level language is called source code and after translation, the final machine language program code is known as object code. While translating the program, it checks the syntax that means grammar of the source code of a high level language program and translates it into machine language program code at single attempt. If there is a syntax error on source code then the compiler produces syntax errors and causes of the errors. The source code file must be free from syntax errors for the complete compilation process. Compiler is more efficient and faster than the interpreter.

For each high level language, a separate compiler is required. For example: a C language compiler cannot translate a program written in JAVA programming languages. Programming languages such as C, C++, C# and Visual Basic, etc. use compiler. Java has both a compiler and interpreter.

Difference between compiler and interpreter

Compiler Interpreter
i) It translates a high level language program into a machine language program at a single attempt. (i) It translates a high level language program into a machine languages program by one instruction at a time.
(ii) It finds the syntax errors after compiling the whole program. (ii) It finds the syntax errors after translating a line of the program at a time.
(iii) It is difficult to trace errors and causes of the errors. (iii)It is easy to trace errors and causes of the errors.
(iv) The compiling process is faster than the interpreter. (iv) The interpreting process is slower than the compiler.
(v) It is more efficient than an interpreter. (v) It is less efficient than a compiler.
(vi) It creates the object code. (vi) It doesn’t create object code.
(vii) Examples: C,C++, Visual Basic etc. (vii) Examples: BASIC, LISP etc.

5.1.4 Syntax, Semantic and Runtime Errors

Syntax of a programming language defines the grammatical rules to construct an instruction in a program. Moreover, it also defines the alphabets, numbers, operators, expression and structure of an instruction. This is the fundamental rule that must be followed by a programmer. Otherwise, the language does not understand the codes of a program. If it is syntactically correct, then the source codes are translated into machine code.

A semantic of a programming language defines the logical meaning of an instruction. Compiler does not identify the semantic of a program. So, it is difficult to identify the semantics of a program. To identify the semantics of a program, a programmer might take some sample data to verify the outputs. We can consider the following English statement to know the idea of syntax and semantics.

Examples Description
I eat rice. Syntactically and semantically correct
I eat chairs. Syntactically correct but semantically incorrect
I eats chairs. Syntactically and semantically incorrect

Syntax defines grammatical rules for the language whereas semantic defines the logical meaning of any programming language.

A program is never 100% correct throughout its life span. But we assume that a program should be almost 100% correct, otherwise a program does not fulfil the actual requirements of users. There might be some mistake due to the violation of rules of programming language, called errors or bugs. The process of finding bugs is called debugging. Mainly, there are three types of errors in the program: syntax errors, logical (semantics) errors and runtime errors.

(i) Syntax Error

A syntax error has occurred due to the violation of syntax of a programming language. The key words (reserved words by the programming language) and the structure of the instructions must be in the correct form. A syntax error is easy to debug because the compiler itself detects syntax error and describes the causes of the errors. So, a programmer does not need to trace the errors in a program.

(ii) Logical Error

A logical error occurs due to the violation of semantics of a programming language. It is also called semantics errors. Meaningless instructions cause the logical errors so the wrong logic must be carefully removed from the program. A compiler does not detect the logical errors, therefore they are very difficult to find out. The actual output does not come as per the given data therefore, sample data is supplied to the program to examine the logic errors.

(iii) Runtime Error

A runtime error occurs during the running time of the software. It occurred due to the problem of system or mishandling of the software. Run time error might occur anytime while running a program. So, a good programmer must handle the errors using different error handling mechanisms during software development time.

Assignment XI - Ch 5(2) 1. List any three language translators. 2. List any three interpreted programming languages. 3. List any three compiler-based programming languages. 4. Compare between compiler and interpreter. 5. Draw figures of assembler, interpreter and compiler. 6. Compare syntax and semantics of a programming language. 7. Give an example of run time error.


5.1.5 Program Design Tools- Algorithm, Flowchart and Pseducode

A program is developed to solve our real-world problem. The program development process has mainly three phases: analysis, design and development. During the analysis phase, the detailed study of the problem must be done. After the analysis phase, the problem is designed by using different programming tools such as algorithms, pseudo codes, flowchart, etc. During this period, input, process and output of the problem are determined. The good program design makes efficient and faster development of program. After designing, it is ready for development i.e. programming the problem.

Algorithm

Algorithm is one of the most basic tools used for solving problem. It is defined as the finite sequence of instructions for solving a problem. It consists of stepwise list of English statements making sequential procedure. The number of instructions should be minimized to increase the speed of the algorithm.

Algorithm is a finite sequence of instructions for solving a problem.

There are not any specific rules for designing algorithms however, designing an algorithm requires a clear understanding of a problem. Before writing an algorithm, a designer should have knowledge about the input, output and process of a problem. The instructions are written in simple informal English statements. Some of the major guidelines while writing an algorithm are as follows:

  • The number of instructions should be finite.
  • Each instruction should be in simple language and no ambiguous instructions should be included. 
  • It should have an input, process and desire output after executing the algorithm.
  • It should not depend on any language or computer.

Algorithm for calculating simple interest

Step 1: Start
Step 2: Input Principal, Rate and Time
Step 3: Multiply Principal , Rate and Time and Divide by 100
Step 4: Store the result in Simple Interest
Step 5: Output Simple Interest
Step 6: Stop

Advantages of algorithm:

  • It is simple and easy to understand.
  • It has no hard and fast rules for writing an algorithm. 
  • It does not require prior knowledge of programming during writing algorithms. 

Disadvantages of algorithm:

  • It is more difficult to translate algorithms into program codes. 
  • It is not considered as a standard tool for program designing.

Flowchart

When an algorithm is expressed in pictorial form, then it is called flowchart. It is defined as a pictorial representation of an algorithm that describes the procedure to solve a problem. lt shows the order of instructions and relationship between them. The purpose of constructing flowchart is to help for the programmer for understanding the logic of a problem.

Flowchart is a pictorial form of an algorithm. It uses meaningful symbols to represent different types of instructions.

It uses different meaningful symbols to solve a problem. It is useful tools when an algorithm is short and fits conveniently on one page. Moreover, it also helps for the solutions of mathematical and logical problems. It defines the sequence and the flow of operations of a problem. It clearly explains the input, process and output of a problem. It shows the internal relationship between the instructions. Some of the major features are as follows.

  • It is only suitable for small logical or mathematical problems.
  • It cannot solve complex and lengthy problems.
  • It can only solve procedural types of problems.
  • Designers should have knowledge about the symbols of flowchart.

Symbols used in Flowchart

Symbols used in Flowchart


Flowchart for calculating Simple Interest

Flowchart to calculate simple interest

Advantages of Flowchart

  • It is very efficient tool for solving logical and mathematical problems.
  • It shows the types of instruction whether; an instruction is input/output, process or logical.
  • It is easy for converting flowchart into program codes.
  • It is easy for testing and maintenance.

Disadvantages of Flowchart

  • It is difficult for solving large and complex problem.
  • It is time consuming for designing a flowchart.
  • It is difficult for modifying and updating the flowchart.
  • Designer should be familiar with different symbols and their respective meanings.

Pseudo Code

Pseudo code is a kind of  algorithm for solving a problem. The instructions of pseudo code are written by using English phrase and mathematical expressions. It is also known as structured English. It has no specific rules for writing instructions, but the instructions are very closer to high level language instructions. Designer should have basic knowledge about high level language instructions before writing pseudo code. It is independent of any programming languages.

Pseudo code is a kind of algorithm in which the instructions are expresses in more English like structure and mathematical expression. The instructions of pseudo code are similar to the program instructions.

Pseudo Codes for calculating simple interest

Start
Input P,T and R
Calculate SI=(P*T*R)/100
Output SI
Stop

Advantages of Pseudo Code:

  • Complex and lengthy problems can be easily solved by using pseudo code.
  • It is easy for converting pseudo code into program codes.
  • It is easy for testing because it can be tested by using computer aided tools.
  • It is independent of any programming languages.

Disadvantages of Pseudo Code:

  • Designer should have prior knowledge of programming while writing pseudo code.
  • It is more complex than algorithm.

Control Structure

A control structure is the most powerful tool in any high level language which is used to control the flow of instructions in a program. Moreover, it is used to develop program logic for the solution of a problem. It is also known as control statement. The main components of control structure are sequence, selection and repetition / iteration / looping.

A control structure is major component of a high level language that helps to control the flow of instructions in a program.

Sequence

A sequential control structure is a linear structure. It executes statements one after another in a sequence. There is no mechanism for choosing alternate paths in statements flow. It executes one statement then automatically moves to next statement and so on.

Algorithm Syntax of Sequence:

Start
Statement 1
Statement 2
..................
..................
Statement N
End

Flowchart of Sequence:


Example of Sequential Control Structure
Write an algorithm and a flowchart to calculate area of rectangle.
Algorithm to calculate area of rectangle
Step 1: Start
Step 2: Input L,B
Step 3: Calculate A=L*B
Step 4: Output A
Step 5: Stop

Flowchart to calculate area of rectangle

Ch 5 Assignment 3

  1. What are the three states of program development?
  2. List any three program design tools.
  3. Write an algorithm to calculate area of square.
  4. Write an algorithm to calculate area of a circle.
  5. Write an algorithm and a flowchart to calculate to calculate simple interest.

Selection

A selection structure is known as branching statement. It has the decision-making capabilities based on given conditions. It allows alternative paths for the instructions of a program based on given conditions. If the condition is true, one set of instructions will be executed otherwise, another set of instructions will be executed. Mainly, there four categories of selection structures such as if else, if else if, nested if else and switch case structure. Let us discuss simple if else structure here and we will be discussed the other categories of selection structures later in C programming.

Simple if else structure is the basic type of selection structure. If a given problem has one condition with respective two actions: true/false, then we can use simple if else structure. We should consider either true or false part. If the given condition is true, then the statement 1 will be executed, otherwise the control moves to else part i.e. statement 2 will be executed. In this case, the else part is optional so, if we remove else part then it will become simple if statement.

Algorithm syntax of if else

if(condition)
statement 1;
else
statement 2;

Simple if statement
if(condition)
statement

Flowchart of if else statement




Example of Selection Control Structure

Write an algorithm and a flowchart to find the greater number among two numbers.

Algorithm to find the greater number among two numbers

Step 1: Start
Step 2: Input A,B
Step 3: if(A>B)
Output A is greater.
else
Output B is greater.
Step 4: Stop

Flowchart to find the greatest number among two numbers

Ch 5 Assignment 4

  1. What are the three major components of selection structure?
  2. List four types of selection structures.
  3. Write an algorithm and a flowchart to check the number is positive or negative.
  4. Write an algorithm and a flowchart to check the number is odd or even.
  5. Write an algorithm and a flowchart to check the number is divisible by 5.

Iteration / Looping

Iteration is commonly known as looping or repetition. In iteration process, an instruction or group of instructions is repetedly executed until some condition has been satisfied. Every loop has three fundamental components: intilialization, condition and counter. An intialization statement defines the starting point of the loop. The condition defines the stopping point of the loop and finally the counter counts the number of iterations. The increment and decrement operations are used as counter. If the condition of a loop is always true, then the loop will be executed infinite times and such loop is called infinite loop. There are three types of loops: while, do while and for loop.

Let us consider simple while loop. In this loop, computer first checks the condition, if the condition is true, then it executes the statements inside loop. The process is repeated and the value of increment or decrement operator is also changing. When the condition is false the loop stops. If the given condition is intially false, then the loop will not execute further.

Algorithmic Syntax of while loop
intialization;
while(condition)
{
statements
..........
..........
increment/decrement;
}

Flowchart of while loop

Flowchart of while loop


Example of Looping | Iteration Control Structure

Write an algorithm and a flowchart to print 1 to 10.

Algorithm to print 1 to 10

Step 1: Start
Step 2: i=1
Step 3: while(i<=10)
{
Output i
i++
}
Step 4: Stop

Flowchart to print 1 to 10


Flowchart to print 1 to 10



A computer understands only binary numbers in the form of two electronic states: high voltage(1) and low voltage (0). Such binary notations are further derived into different standard codes. Such codes are used to represent the data for convenience to the users. Different data representation codes are used in computer system. Some of the popular codes are as Absolute Binary, BCD, ASCII, EBCDIC, Unicode etc.

Absolute Binary

We use plus sign + and minus - sign to represent positive and negative numbers respectively. In computer system, such mechanism is not employed. In absolute binary method, 0 is placed before the binary number to represent positive number and 1 is placed before the binary number to represent negative number. The binary number is expresses in 8-bits,16-bits,32-bits or 64-bits format on the basis of word length of processor. The most significant bit denotes the sign bit and the rest of the bits represent the actual number. For examples: To represent +12, in 8 bit absolute binary number is 00001100, similarly for -12, the absolute 8 bits binary number is 10001100.

BCD

The binary coded decimal code is used to represent numeric data in computer. It uses 4 bits to represent a single digit decimal number. For examples: BCD code for 7 is (0111) and BCD code for 15 is (0001 0101).

ASCII

The American Standard Code for Information Interchange is the standard code to represent data in computer. It assigns numeric value for each character, number and symbol. It is extensively used in most of the computers, peripherals and soft wares. It is 8-bits code which represents 256 characters or symbols. For examples: ASCII code for A-65,B-66,C-67,a-97,b-98 etc.

EBCDIC

It stands for Extended Binary Coded Decimal Interchange Code. It is an eight bits code, which defined 256 different characters or symbols. It is mostly used in IBM mainframe and other minicomputers. It is not used in personal computer.

Unicode

Unicode Worldwide Character Standard is a character set which provides 16 bits codes to represent 65536 different character, numbers, symbols etc. It includes characters of all the languages of the world. It also includes all characters from ASCII character set. A newer version of Unicode has 32 bits character set which represents more than 4 billion different character or symbols from the world.

Ch5 Assignment 5

  1. What are the three components of a loop?
  2. What happens when the condition is always true in the loop?
  3. Write an algorithm and a flowchart to print 100,99,98,...1.
  4. Write an algorithm and a flowchart to print 1   3   5   .....N
  5. Write an algorithm and a flowchart to display multiplication table of 5.
  6. Write the full form of BCD, ASCII, EBCDIC and Unicode.

5.2.1 Introduction of C

The C language is one of the most powerful languages.The C language is a highly efficient programming language and easy to understand. It has both the properties of high level language and low level language, so it is also termed as Middle Level Language or intermediate language between high level language and low level language. It is a very powerful programming language because it is used to prepare system software as well as application software. It is a kind of general purpose, structured programming language. It has large numbers of vocabularies and simple syntax to write a program.

C is a general purpose programming language. C language was designed and developed by Dennis Ritchie at Bell Laboratories in 1972. It is an offspring of the "Basic combined programming language" called BCPL developed in the year 1967 at Massachusetts Institute of Technology. This language is associated with the UNIX operating system. The source code for the UNIX operating system is coded in C.

C is general purpose, portable, compact, simple and flexible programming langauge.

Features of C Language

C Language is a very popular language because it has large numbers of features for programmers to write medium types of programs. Some basic features of C language are given below.
  • It is powerful and highly portable Language
  • It is a structured programming language because the program is divided into a number of functions.
  • It is a general purpose high level programming language.
  • It is an internationally standardized programming language.
  • It has both the features of high level languages as well as low level languages.

Advantages of C Language

  • It is easy for debugging, testing and maintaining.
  • It is a portable programming language. This means a program written for one computer may run successfully on another computer.
  • It is fast for executing. This means that the executable program obtained after compiling and linking runs very fast.
  • It is a compact programming language. The statements in C language are generally short but very powerful.
  • It has only 32 Keywords so that's easy to remember.
  • Its compiler is easily available.
  • It has the ability to extend itself. Users can add their own functions to the C library.

Disadvantages of C Language

C programming language has no strong disadvantages. But it has some negligible disadvantages that are given below.
  • There is no runtime checking.
  • There is no strict type checking (for example we can pass an integer value for the floating data type).
  • As the program extends it is very difficult to fix the bugs.
  • It may compile time overhead due to the misplacing and excessive use of pointers.
  • It does not support modern programming approaches like object oriented programming.

5.2.2 Structure of C Program

Every C program contains a number of several building blocks known as functions. Each function performs tasks independently. The structure of C program is given below.
    Preprocessors and Header files
    main()
    /* Comments*/
    {
    	Declaration Part
    	Executable Part
    } 

Pre-processor and Header files

Pre-processor directive is special type of program that processes the code before it passes through the compiler. The common pre-preprocessor directive is #include which helps to include the necessary header files for further execution. The header file is the main file of c compiler that contains inbuilt library functions. For example : #include<stdio.h>

main() function

Every c program must contain the main () function. The main () is the starting point of every C program. The instructions are written inside the scope { } i.e. area of the main function. Manily it has two parts: declaration part and executable part. The declaration part declares the varaibles or constant, etc. The actual program codes are written in the executable part.

Comments

The comments are not the internal part of the program codes. It is optional but writing comments helps to understand the flow of programs and good practice for internal documentation of programmer. It is also useful for furhter modification and program testing.

Example Program to print Hello World on screen.
 /* This program is Written By 
   Er. Purushottam Lal Karn */	
 #include<stdio.h>	
 // Pre-processor and Header file
 main()	
 // main function
 {		
 // Scope Start
	printf("Hello World!"); 
    // Output function to print
 }		
 // Scope End

Compiling Process

The completion process is the process of converting source file(program codes) into executable file(machine codes or object codes). This is automatically peformed by the c compiler. The compilation process is explained in the following figure:

Step 1
Use a text editor like notepad to write your source code and save the file with extension dot c. For example: abc.c ,Generally we prefer to use Dev C++

Step 2
Compile the program using a compiler. It converts into machine codes called object code.

Step 3 Link the program using a linker. If no errors occur, the linker produces an executable program located in a disk file with dot exe extension and the same name as the object file (for example, test.obj is linked to create test.exe)

Step 4
Execute the executable program.



Figure: Compiling process of C Program

Ch 5 Assignment 6

  1. Who developed C language and when?
  2. List out any four major features of C language.
  3. List out the four major components of C program.
  4. Draw a figure of compilation process in C programming.
  5. Compare source file, object file and executable file.

C Pre-processor and Header Files

Header Files are standard files of C-programming language. It contains the function definition of library functions. They are written at the top of the program. Some header files are given below.

  • #include<stdio.h> : It is a standard input output header file. It contains the function definition of input output functions such as scanf(), printf() etc.
  • #include<conio.h>: It is a header file which is included in the program. This is used for  clrscr(), getch(), etc. We do not need to include this file in the C program. It is necessary for C++ programs. conio stands for CONsole Input Output header file. The clrscr() helps to clear the screen.
  • #include<math.h>: This header file is used for mathematical functions such as pow(), sqrt(), sin(), tan() , cos() etc. >
  • #include<string.h> :It is string header file. It contains the function definition of string processing functions such as strlen(), strcat(), strcpy() etc.

C Preprocessor

Preprocessor is a program that processes the code before it passes through the compiler. It operates under the control of preprocessor command lines and directives. Preprocessor directives are placed in the source program before the main line, before the source code passes through the compiler. It is examined by the preprocessor for any preprocessor directives. If any appropriate actions are taken then the source program is handed over to the compiler.

Preprocessor directives follow the special syntax rules and begin with the symbol # and do not require any semicolon at the end. A set of commonly used preprocessor directives are:

DirectiveFunction
#define Defines a macro substitution and symbolic constant
#include Specifies a file to be included in the program


Character Set used in C

The characters are used to form words, numbers and expressions depending upon the computer on which the program runs. The character set in C language can be grouped into the following categories.

  • Letters: uppercase A to Z and lower case a to z
  • Digits: 0 to 9
  • Special Characters: listed in the table
  • Special Characters used in C programming
    ,Comma &Ampersand
    .Period ^Caret
    ;Semicolon *Asterisk
    :Colon -Minus
    ?Question Mark+Plus
    'Apostrophe<Opening Angle (Smaller than)
    "Quotation Mark>Closing Angle(Greater than)
    !Exclamation Mark(Left Parenthesis
    |Vertical Bar)Right Parenthesis
    /Slash[Left Bracket
    \Back slash]Right Bracket
    ~Tilde{Left Brace
    _Under Score}Right Brace
    $Dollar Sign#Hash
    %Percentage Sign White space

    Use of Comments

    Comments are very useful components of a program and they have no effect on the program. They help programmers for description of the program codes. Having good comments throughout our code will make it much easier to remember what specific parts of your code do. Comments can be written in two forms:

    1. // Single Line Comments
    2. /* Multi-Line
      .................
      .................
      .................
      comments */

    5.2.6 Identifiers, Keywords and Tokens

    C Tokens

    The smallest part of C programming language is called C tokens. C programs are written using these tokens. There are six types of C tokens that are given below.

    Tokens are fundamental parts of the C program from which other parts are formed.
    1. Keywords eg: int, float
    2. Operators eg: + - * /
    3. Identifiers  eg: roll, name
    4. Constants  eg: fullmarks=100
    5. Strings eg: "ALEX" , "Ba. Pa. 02-021 6319"
    6. Special symbols eg: { } [ ] ( ) ?

    Keywords

    There are certain words which are reserved by the C compiler. These words are known as keywords. They cannot be used as identifiers in the program. Mainly there are 32 keywords used in standard C language.

    Keywords are reserved words that are per-defined in C programming language.
    autodoubleintstruct
    breakelselongswitch
    caseenumregistertypedef
    charexternreturnunion
    constfloatshortunsigned
    continueforsignedvoid
    defaultgotosizeofvolatile
    doifstaticwhile


    Identifiers

    Identifiers are the names given to program units such as variable, structure, function etc. They are not defined in the programming language but are used to define by the programmer. Some basic rules to define identifiers are given below.

    • First character must be an alphabet or (underscore)
    • It must consist of only letters, digits and underscore.
    • Any standard C language keyword cannot be used as an identifier name.
    • It should not contain a white space.
    • It allows both upper case and lower case characters.
    Identifiers are the names of program units. The rules of identifiers are used to define program units such as variable, constant, function, structure etc.

    Valid Indetifiers:
    A1     B34    First_Name    x_1
    Invalid Identifiers
    1A    34AB    int   void    First-Name    x.1

    Ch5 Assignment 7

    1. List any four header files and two pre-processor directives.
    2. What is character set?
    3. Write the types of comments.
    4. Write six types of tokesn used in c langugage.
    5. Compare indentifiers and keywords.

    Goto Top
    Basic Data Types in C

    C language provides us the way to hold any type of data in it. It is called data type. In C language data types classified into two categories:-

    Data types of C language are primary and secondary. They are mainly used to define the type and nature of data such that the compiler detects and proceeds.

    Primary Data Types

    The fundamental data types are called primary data types. They are also used to build other data types. The fundamental data types are given in the following table.

    Variable Type Keyword Storage Range
    Character char 1 byte -128 to 127
    Unsigned character unsigned char 1 byte 0 to 255
    Integer int 2 byte -32768 to 32767
    Short integer short int 2 byte -32768 to 32767
    Long integer long int 4 byte -2,147,483,648 to 2,147,483,647
    Unsigned integer unsigned int 2 byte 0 to 65535
    Unsigned short integer unsigned short int 2 byte 0 to 65535
    Unsigned Long integer unsigned long int 4 byte 0 to 4,294,967,925
    Float float 4 byte 1.2 E-38 to 3.4E+38
    Double double 8 byte 2.2E-308 to 1.7 E+308
    Long double long double 10 byte 3.4 E-4932 to 1.1 E+308

    signed/unsigned and long/short prefix are used before primary data types. A Signed data type defines both positive and negative values. For example: signed int x; //it holds both positive and negative numbers unsigned int x; // it holds positive numbers The long data type helps us to maximize the range of values and the short data type minimizes the range of values for basic data types. short int x; //it minimizes the range of values than ordinary integer value long int x; // it maximizes the range of values than ordinary integer value. You will study later in chapter about secondary data types.

    Variables and Constants

    Variable

    A variable is a value that can change any time. It is a memory location used to store a data value. A variable name should be carefully chosen by the programmer so that its use is reflected in a useful way in the entire program. Any variable declared in a program should confirm to the following:

    • They must always begin with a letter, although some systems permit underscore as the first character.
    • White space is not allowed.
    • A variable name should not be a keyword.
    • It should not contain any special characters.

    Examples of invalid variable names are 

    123  (area) 6th             % abc

    Examples of valid variable names are 

    Sun number Salary Emp_name averagel 


    Types of Variable 

    • Numeric variable: The variable that stores numeric data only is called numeric variables. The numeric data may be whole numbers or fractional numbers. Examples of numeric variables are: integer, floating point and double. 

    • String variable: The variable that stores character data only is called string variable. The string data may be single character or string. Examples of string variables are: character, array of character (string), table of strings.


    POINTS TO REMEMBER


    Variables are simply names that can change the value while executing a program. It allocates memory space inside the memory of the computer. 

    What is the purpose of variable declaration? 

    The purpose of variable declaration is to allocate memory space inside a memory of the computer. Declaration does two things: 

    • It tells the compiler what the variable name is. 

    • It specifies what type of data the variable will hold. 

    Syntax of variable declaration 

    data_type v1, v2, v3, . vn; 

    Where v1, v2, v3, .. vn are the names of valid variables. 

    Examples 

    int a,b;

    float c;

    char d;


    Variable Declaration

    This diagram describes that when the variables are declared, the spaces in memory are allocated according to size. In this example, a and b are integer, allocates 2 byte memory each, c is floating, allocates 4 byte memory, d is character, allocates 1 byte memory.


    Constant 

    A constant value is the one which does not change during the execution of a program. C supports several types of constants. These constants are given below: 

    • Integer Constants

    • Floating Constants 

    • Character constants 

    • String Constants 

    • Symbolic Constants 

    • Escape Sequence Constants 


    POINTS TO REMEMBER


    Constant value is a value that is never changed during the execution of a program.


    Integer Constant 

    An integer constant is a sequence of digits. There are 3 types of integers namely decimal integers, octal integers and hexadecimal integers. These constants are given below.

    Decimal Integers: 123 -31 0 +78

    Octal Integers: O26 O O347 O676

    Hexadecimal integer: 0X2 OX8C OXbcd Ox


    Character Constant 

    A character constant stores only a single character. It is enclosed by a single quotation mark. Examples of character constants are:

     ‘A’ ‘B’ ‘h’ ‘2’ ‘6’


    String Constant 

    A string constant is a set of characters enclosed in double quotation marks. The characters in a string constant sequence may be an alphabet, number, special character and blank space. Example of string constants are 

    “ALEX” “1234” “God Bless” “!.......?”


    Symbolic Constant 

    A symbolic constant is a type of constant that substitutes the value or expression to constant name. It is defined by using the pre-processor  #define. 

    Syntax:

    #define constant_name constant_value 

    Example 

    #define PI 3.14 

    #define teachername     “PLK Computer SIR" 

    #define area  100 


    Escape Sequence Constant 

    The non printing characters started with backslash(\) are called escape sequence constant. They are special characters used in output functions. Although they contain two characters they represent only one character. Given below is the table of sequence and their meanings.

    POINTS TO REMEMBER


    Escape sequence always starts  with \ and used in the output function.


    Escape Sequence

    Meaning

    \a

    Audible Alert(Bell)

    \b

    Backspace

    \n

    New Line

    \r

    Carriage Return

    \t

    Horizontal Tab

    \v

    Vertical Tab


    Difference between Variables and constants 

    Variables

    Constants

    (i) It is a name whose value can be changed during the execution of a program

    (i) It is a name whose value cannot be changed during the execution of a program

    (ii) The purpose of variable declaration is to allocate memory space inside a memory of a computer. 

    (ii) The purpose of constant declaration is to allocate memory space inside a memory computer and assign value in it. 

    (iii) Syntax: 

           data_type variable name;

    (iii) Syntax:

           Data_type constant name=value;

    (iv) e.g.

           int a;

           float b;

    (iv) eg.

              int a=5;

              float b=10.9 ;


    Goto Top

    5.2.9 Type of Specifier

    It is also known as a format specifier. Type of specifier controls the type and format of the value to be printed or entered. Each conversion specification begins with % sign and ends with a conversion character. The conversion character defines the data type of the corresponding argument.

    single character: %c
    Decimal integer: %d
    floating point value without exponent form: %f
    singed decimal integer : i
    octal iteger without leading zero : o
    srting : %s
    hexadecimal integer without leading zero: %x
    Long integer: %ld
    

    Ch5 Assignment 8

    1. List any four primary data types and four secondary dtat types.
    2. How much memory required to hold charactr, integer, float and double dta types?
    3. Compare variable and constant.
    4. List any five types of constants.
    5. List any five escape sequence constants.
    6. List any five type specifier characters.

    5.2.4 Statements: Simple and Compound Statements

    Statement causes the computer to carry out some action. It is terminated by semicolon. The statements are categorized into two types: simple statement and compound statement.

    Simple statement:

    A simple statement consists of an expression followed by a semicolon. The execution of a simple statement causes the expression to be evaluated.
    Example:
    b=5;
    c=d+e;
    printf("Enter a number");

    Compound statement:

    A compound statement consists of several individual Statements enclosed in a pair of braces { } . It provides capability for embedding Statements within other statements.
    Example:
    {
    r=5;
    area=3.14*r*r;
    }
    It shows a compound statement to calculate the area of the circle.

    5.2.11 Operators and Expressions

    An operator is defined as a meaningful symbol which helps to carry out specific calculations or logical comparision. An operand is termed as variable or constant that holds data operation. An expression is defined as the combination of operators and operands. C language provides wide variety of operators which are as follows:

    1. Arithmetic operators(Binary operators)
    2. Relational operators(Comparision operators)
    3. Logical operators(Boolean operators)
    4. Assignment operators
    5. Unary Operators(Increment/decrement)
    6. Ternary Operators(Conditional Operators)
    7. The Comma Operator

    1. Arithmetic Operator

    All the basic arithmetic operations can be carried out in C. It can perform simple arithmetic calculations such as addition, subtraction, multiplication etc. It uses two operands so that it is also called a binary operator. The types of arithmetic operators are given below.

    Suppose a=10 and b=3
    Operator Meaning Examples
    +
    (Plus)
    Addition a+b
    =10+3=13
    -
    (Minus)
    Subtraction a-b
    =10-3=7
    *
    (Asterisk)
    Multiplication a*b
    =10*3=30
    /
    (Slash)
    Division a/b
    =10/3=3.333333
    %
    (Percentage)
    Modulus
    (Remainder)
    a%b
    =10%3=1

    2.Relational Operators

    It is required to compare the relationship between operands and bring out a decision accordingly. It is also called a comparison operator because it is used to compare any two expressions. C supports the following relational operators.

    Operator Meaning Examples
    < is less than a<b
    <= is less than or
    equal to
    a<=b
    > is greater than a>b
    >= is greater than or
    equal to
    a>=b
    == is equal to a==b
    != is not equal to a!=b

    3. Logical Operators

    Logical operators are used to give logical value either true or false. C has the following logical operators; they compare or evaluate logical and relational expressions.

    Operator Meaning Examples
    && Logical AND (a>b)&&(a>c)
    || Logical OR (a>b)||(a>c)
    ! Logical NOT !(a==b)

    4.Assignment Operators

    The assignment operator is used to assign the value of expression into a variable. It is written in the form:
    variable = expression

    Example:
    x = a + b
    Where x is a variable and a+b is an expression. Here the value of a + b is evaluated and substituted to the variable x.
    There are other forms of assignment operators which are listed in table
    `
    Operators Statement with operator Equivalent to
    += a+=1 a=a+1
    -= a-=1 a=a-1
    *= a*=1 a=a*1
    /= a/=2 a=a/2
    %= a%=b a=a%b

    5. Unary Operators

    The increment and decrement operators are very useful operators in C language. They are extensively used in loops. The syntax of the operators is given below:

    1. + + variable name(increment prefix)
    2. variable name+ + (increment postfix)
    3. - - variable name(decrement prefix)
    4. variable name- - (decrement postfix)

    The increment operator ++ adds the value 1 to the current value of operand and the decrement operator - - subtracts the value 1 from the current value of operand. ++ variable name and variable name ++ mean the same thing when they form statements independently, they behave differently when they are used in expression on the right hand side of an assignment statement.

    Consider the following
    m=5;
    y = ++m; //prefix operation (first increment then assignment)
    In this case the value of y and m would be 6.
    Suppose if we rewrite the above statement as,
    m=5;
    y = m++; //postfix operation (first assignment then increment)
    Then the value of y will be 5 and that of m will be 6.
  • A prefix operator first adds 1 to the operand and then the result is assigned to the variable on the left.
  • On the other hand, a postfix operator first assigns the value to the variable on the left and then increments the operand.

  • 6. Ternary Operator (?:operator)

    Ternary operator is also known as a conditional operator as it checks the condition to make decisions. It uses two symbols: the question mark (?) and the colon (:) but not together as In >= ,<= etc. This is the only operator used in C that takes three operands so it is named as ternary operator.

    Syntax:
    (condition)?statement1:statement2

    In this operator, the first condition is checked and if it is found true then statement1 will be executed otherwise statement2 will be executed which is similar to the working style of if-else statement.

    Example:
    #include<stdio.h>
    main()
    {
    	int a,b,x;
     	a=10;
    	b=15;
    	x=(a>b) ? a : b;
    	printf("Value of x=%d",x);
    }

    Here x will be assigned to the value of b. The condition follows that the expression is false therefore b is assigned to x.


    7. The Comma Operator

    The comma operator can be used to link related expressions together. Comma-linked lists of expressions are evaluated left to right and value of right most expression is the value of the combined expression.

    Example:
    value = (x = 10, y = 5, x + y);
    First assigns 10 to x and 5 to y and finally assigns 15 to value. Since comma has the lowest precedence in operators the parenthesis is necessary.

    ****Precedence and Associativety in not in syllabus****

    Precedence and Associativity

    Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator. Associativity refers to the direction of processing of an expression.
    For example x= 7+3*2, where 13 is assigned to x, not 20 because operator * has higher precedence than + so it first gets multiplied with 3*2 and then adds into 7.

    Here operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

    `
    Category Operator Associativity
    Postfix () [] Left to right
    Unary ++ -- Right to left
    Multiplicative * / % Left to right
    Additive + - Left to right
    Relational < <= > >= Left to right
    Equality == != Left to right
    Logical AND && Left to right
    Logical OR || Left to right
    Conditional ?: Right to left
    Unary = += -= *= Right to left
    Comma , Right to left

    Ch5 Assignment -9

    1. Compare simple statement and compound statement.
    2. List out any five types of operators of c language.
    3. List any five arithmetic operators and any five relation operators.
    4. List any three logical operators.

    Expressions

    An expression is a combination of variables, constants and operators written according to the syntax of C language. In C, every expression evaluates to a value that is, every expression results in some value of a certain type that can be assigned to a variable. Some examples of C expressions are shown in the table given below.

    An expression is a combination of variables, constants and operators written according to the syntax of C language. In C every expression evaluates to a value .
    `
    Algebraic Expression C Expression
    a x b -c a*b-c
    (m+n) (x+y) (m+n)*(x+y)
    (ab/c) a*b/c
    3x2+2x+1 3*x*x+2*x+1
    (x/y)+c x/y+c

    Type casting and Conversions

    C permits mixing of constants and variables of different types in an expression. C automatically converts any intermediate values to the proper type so that the expression can be evaluated without losing any significance. This automatic type conversion is known as implicit type conversion.

    The process of converting one type of data into another type is called type conversion.
    Example of Implicit type conversion
    #include<stdio.h>
    main()
    {
    float c;
    int a=5,b=2;
    c=a/b;
    printf("Output is %0.2f" ,c);
    }
    
    Output is 2.00

    Explicit type conversion

    Many times there may arise a situation where we want to force a type conversion in a way that is different from automatic conversion. The process of such a local conversion is known as explicit conversion or casting a value.

    The general form is:
    (type_name) expression ;
    Example of Explicit type conversion
    #include<stdio.h>
    main()
    {
    float c;
    int a=5,b=2;
    c=(float)a/b;
    printf("Output is %0.2f" ,c);
    }
    
    Output is 2.50

    Introduction to Library Functions

    The functions that are pre-defined in programming language are called library functions. Some library functions are used for input/output operations, some are string processing operations, some are for mathematical operations and so on. Each library function can perform specific tasks and return specific values. Some library functions are given below in tabular form. Library functions are stored in respective header files.

    The special functions that are well defined in C programming languages are called library functions such as printf(), scanf(), strlen(), sqrt() ete.
    `
    Library Functions Meanings
    sqrt(d) return the sqaure root of d
    exp(d) raise e to the power d
    abs(d) return the absolute value of d
    log(d) return the logarithm of d
    pow(d1,d2) return d1 raised to the power d2
    printf(...) displays data to standard output device
    scanf(...) enter data items from standard input device
    getchar() enter a character from the standard input device
    putchar() display a character to standard output device
    sin(d) return sine angle of d
    cos(d) return cos angle of d
    tan(d) return tangent of d
    toascii() convert into ascii code
    tolower() convert letter to lowercase
    toupper() convert letter to uppercase

    Ch5 Assignment -10

    1. Compare operator and expressions.
    2. What is operand?
    3. Compare implicit type casting and explicit type casting.
    4. List any five library functions of c language.

    Input/ Output Functions

    Like other languages, C does not have any built-in input/output statements as part of its syntax. All input/output operations are carried out through printf() and scanf() function. There exist several functions that have more or less become standard for input and output operations in C. These functions are collectively known as the Standard I/O library because it can take or accept any type of data.

    Each program that uses a standard input/output function must contain a statement #include<stdio.h> at the beginning. The instruction #include<stdio.h> tells the compiler to search for a file named stdio.h and place its contents at this point in the program. The contents of the header file become part of the source code when it is compiled. C language consists of some I/O functions like getchar(), putchar(), scanf() gets(), puts(), getch(), putch(), getche() etc.

    Input / Output Functions

    The printf() and scanf() functions are known as formatted I/O functions because they can take any type of format of data from the I/O devices.

    printf() can be used to display some conversion characters along with some unchanged characters. Such conversion characters may include format specifiers or escape sequences.

    Syntax:
    printf( "control string", arg1, arg2, ......);

    Here control string may consist of any simple characters or format conversion specifiers or escape sequences and arg1, arg2,.... are arguments (variables) that represent the individual data item.

    Example 1
    printf("Hello");

    Here, the statement consists of simple characters without arguments and will display output 'Hello'.

    Example 2
    int a=5; printf("%d",a);

    Here, printf() statement contains a format conversion specifier “%d”  and an argument ‘a’ which will display output 5

    Example 3
    float a=0.5; float b=987.8145; printf(“ \n here are two values %f and %.3f ”, a, b);

    Here, printf() statement contains characters "here are ...” , format  conversion specifiers “ %f ”, “ %.3f ”, escape sequence ‘\n’ and arguments ‘a’, ‘b’ which will display Output: "here are two values 0.500000 and 987.814".

    scanf() can be used to get inputs from the user.

    Syntax:
    scanf (" control string " , argl, arg2,....)

    Here control string may consist of any format conversion specifiers and arg1, arg2,.... are arguments specifying the address of locations where the data is stored. Control string and arguments are separated by commas. For example, if ‘k’ is a variable or argument then '&k' is its address. So, it must be written as &k with scanf function.

    Examples:
    int a; float b; char c; scanf("%d%f%c",&a,&b,&c);

    If input is 4,0.8 and m then values of a, b and c are respectively 4,0.800000 and m.

    Differentiate between printf() and scanf() statements

    printf() scanf()
    1. It is used to display contents(text/number). 1. It is used to get inputs from the user.
    2. It contains any simple characters, format conversion specifiers or escape sequence and arg1, arg2,... arguments(variables) 2. It does not contain simple characters, it contains format conversion specifier and arg1,arg2,..... arguments(variables).
    3.
    Syntax: printf(“control string”, arg1,arg2,....); Here, control string may consist of simple string or format conversion specifiers and arg1,arg2,.... are arguments.
    3.
    Syntax: scanf(“control string”,arg1,arg2); Here, control strings may consist of format conversion specifiers and arg1,arg2,... are arguments.
    4.
    Example: main() { float a=9861.492492; printf("\n %.3f",a); }
    4.
    Example: main() { int a; printf(“Enter a number”); scanf("%d",&a); }
    Program-1 Write a program to find the sum of two numbers.
    #include<stdio.h> main() { int a,b,c; printf("\n Enter first number "); scanf("%d",&a); printf("\n Enter second number "); scanf("%d",&b); c=a+b; printf("Sum is %d" ,c); }
    Program-2 Write a program to find the square of a number.
    #include<stdio.h> main() { int a,b; printf(" Enter a number "); scanf("%d",&a); b=a*a; printf("Square = %d" ,b); }
    Program-3 Write a program to calculate simple interest using si=(p*t*r)/100.
    #include<stdio.h> main() { float p,t,r,si; printf(" Enter Principal, Time and Rate"); scanf("%f%f%f",&p,&t,&r); si=(p*t*r)/100; printf("Simple Interest = %f" ,si); }

    Other Input/Output Functions

    1. getchar () and putchar():

    The getchar() function is used to read (or accept) a single character. It can not take more than one character.

    Syntax for getchar():

    variable_name = getchar();
    Here variable_name is a valid C name that has been declared as char type.

    The putchar() function is used to display the character contained in the variable name at the output screen / terminal.

    Syntax for putchar():

    putchar(variable_name);
    Where variable_name is a type char containing a character.

    Example of getchar() and putchar()

    #include<stdio.h>
    main()
    {
    char ch;
    printf("Enter a character ");
    ch=getchar();
    putchar(ch);
    }

    In the above example, getchar() function accepts a character which stores in a variable 'ch' and putchar() used to display stored character.

    2. gets() and puts():

    The gets() function is used for a completely different purpose. It reads a string (group of characters) from the standard input and stores it in the given variable. It reads a whole line of input until a newline.

    Syntax for gets():

    gets(variable);

    Example for gets():

    char name[25]; // here varaible name is string a group of characters with size 25
    gets(name); // it will ask the user for a name and save the name into name string variable.

    The puts() function is used to display text in the monitor which is stored in the variable. But variable is always string data type.

    Syntax for puts():

    puts(variable);
    or
    puts("string");

    Example for puts():

    char name[25]={"Alex"};
    puts(name);
    This example will display name "Alex".
    Program-4 Write a program to enter full name and print it on screen.
    #include<stdio.h> main() { char name[100]; puts("Enter your full name "); gets(name); puts("Your name is : "); puts(name); }
    Program-5 Write a program to input name, age and salary and print them on screen.
    #include<stdio.h> main() { char name[50]; int age; float salary; printf("Enter name "); gets(name); printf("Enter age "); scanf("%d",&age); printf("Enter salary"); scanf("%f",&salary); printf(" Name=%s ",name); printf("\n Age=%d \n Salary=%.2f",age,salary); }

    Worked Out Examples

    Program-6 Write a program to input two numbers and print remainder and quotient.
    #include<stdio.h> main() { int a,b,c,d; printf(" Enter two numbers "); scanf("%d%d",&a,&b); c=a/b; d=a%b; printf(" Quotient=%d ",c); printf("\n Remainder=%d ",d); }
    Program-7 Write a program to input seconds and convert it into hour, minutes and seconds.
    #include<stdio.h> main() { int s,h,r,d,m,a; printf(" Enter seconds "); scanf("%d",&s); h=s/3600; // for hour r=s%3600; m=r/60; // for minutes d=r%60; // for seconds printf(" hour=%d minutes=%d seconds=%d",h,m,d); }
    Program-8 Write a program to calculate area of a circle.
    #include<stdio.h> main() { float r,a; printf(" Enter radius "); scanf("%f",&r); a=3.14*r*r; printf(" area =%.2f ",a); }

    Ch 5 Assignment 11

    1. List out any three input functions and output functions.
    2. Write syntax and example for functions: scanf() and printf().
    3. Write syntax and example for functions: getchar() and putchar().
    4. Write syntax and example for functions: gets() and puts().

    Introduction to Control Statement

    In most of the programs, the program statements were executed in the same order in which they are written. Each instruction was executed only once. This is not enough in programming. Sometimes we may have to execute program statements based on the given condition, sometimes we may have to execute program statements repeatedly, sometime we may have to choose an option and perform the task accordingly. To carry out all these tasks and other similar tasks, program statements must be executed in a controlled way and it can be done using control structure.
    Control structure is also known as control statement. It is defined as the group of statements or function that helps to control the flow of instructions in a program. It allows programmer to control the flow of program statements execution in a program. It also specifies the order of statements in program. If there are no control statements, the statements are executed in sequential manner, commonly known as sequential statements.
    Mainly controls structures are classified into the following three categories:
    • Branching Statements(Selective)
    • Looping Statements(Iterative or Repetitive)
    • Jumping Statements(Unconditional)
    Control Structures are those programming constructs which control the flow of program statements execution in a program. It also specifies the order of statements in the program.

    Branching Statements

    In branching control structure, selection is made on the basis of condition. We have options to go when the given condition is true or false. The flow of program statement execution is totally directed by the result obtained from the checking condition. Hence, program statements using selective control structures are also called conditional Statements. This type of control structure is mainly used for decision making. It can mainly be categorized into two types.
    • Conditional Branching Statement
    • Switch Case Statement

    Conditional Statement

    It is the most common decision making control structure which controls the flow of program statement execution based on the condition checked. It can be used in different forms as:
    • if statement
    • if else statement
    • if else if statement (if-else ladder)
    • nested if else statement

    if statement

    It is the simplest form of conditional statement in which statements are executed if the test expression (condition) is true. When the condition is false there is no option to go within this structure; in such a situation control must out from the structure and statements outside this structure will be executed.

    Syntax for if statement

    if(condition)
    {
    statements;
    }

    Braces are optional for only one statement as shown below:
    if(condition)
    statements;

    Flowchart for if statement



    Program-9 Write a program to demonstrate the use of if statement
    #include<stdio.h> main() { int n; printf("\n Enter a number"); scanf("%d",&n); if(n>0) printf("\n Entered number is positive"); }

    if else statement

    It is another form of selective control structure which can handle both expected as well as unexpected situation. In this control structure, statements written in the body part of if are executed if the condition is true otherwise statements written in body part of else are executed. This is appropriate when we must check only one condition.

    Syntax of if else statement:

    if(condition)
    statement1;
    else
    statement2;
    In this case if the condition is true then statement1 is executed otherwise statement2 is executed. The else portion of the if-else statement is optional.

    Flowchart of if else statement:

    Program-10 Write a program which reads any two numbers and display the larger one.
    #include<stdio.h> main() { int a,b; printf("Enter two numbers "); scanf("%d%d",&a,&b); if(a>b) printf("%d is larger ",a); else printf("%d is larger",b); }

    if else if statement (if-else ladder)

    When we have two or more conditions to be checked in a series, we can use if-else if statement. It is also known as multiple conditional statement / multipath conditional statement / if-else ladder.

    Syntax of if-else if statement

    if(condition1)
    statement1;
    else if(condition2)
    statement 2;
    ...............
    ...............
    else if(condition n-1)
    statement n-1;
    else
    statement n;
    In this statement, conditions are checked from the top of the ladder to downwards. As soon as the true condition is found, the statement associated with it are executed and the control is transferred to outside of the ladder skipping the remaining part of the ladder. When most of the conditions (condition1 to condition n-1) are evaluated false then statements associated with the else part will be executed.
    Program-11 Write a program to find the largest number among three numbers given by the user.
    #include<stdio.h>
    main()
    {
    int a,b,c;
    printf("Enter three numbers ");
    scanf("%d%d%d",&a,&b,&c);
    if(a>b && a>c)
    printf("%d is largest",a);
    else if(b>a && b>c)
    printf("%d is largest",b);
    else
    printf("%d is largest",c);
    }

    Nested if else statement

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

    Syntax of if-else if statement:

    if(condition1)
    {
    if(condition2)
    statement1;
    else
    statement2;
    }
    else
    statement3;
    Program-12 Write a program that reads marks of six subjects and calculates total marks and percenatge. Also awards the division based on following criteria.
    Distinction (p>=75)
    First Division (p>=60 and <75)
    First Division (p>=45 and <60)
    Third Division (p>=35 and <45)
    Otherwise, Failed.
    [Hints: Pass marks and full marks for each subject are 35 and 100 respectively.]
    #include<stdio.h>
    main()
    {
    int eng,nep,comp,acc,eco,social,total;
    float per;
    printf("Enter marks of Eng, Nep, Comp, Acc, Eco and Social ");
    scanf("%d%d%d%d%d%d",&eng,&nep,&comp,&acc,&eco,&social);
    total=eng+nep+comp+acc+eco+social;
    per=(float)total*100/600;
    printf("\n Total marks obtained=%d ",total);
    printf("\n Percentage=%.2f",per);
    if(eng>=35&&nep>=35&&comp>=35&&acc>=35&&eco>=35&&social>=35)
    {
    if(per>=75)
    printf("\n Distinction");
    else if(per>=60)
    printf("\n First Division");
    else if(per>=45)
    printf("\n Second Division");
    else
    printf("\n Third Division");
    }
    else
    printf("\n You are failed. So division can't be awarded.");
    }

    Switch Case Statement

    C switch case statement is a multipath decision-making statement that allows selection and execution of a particular block of statements from several blocks of statement based upon the value of expression which is included within the switch statement and branches accordingly . The expression must be of an integral value or character constant. The same task can be performed using an if-else ladder as well but as the number of alternatives increases, the selection process becomes more complex (more time consuming).
    The main difference between if else ladder and switch statement is - In if-else ladder selection of appropriate option is made in serial fashion whereas in switch-case statement it is done in parallel fashion. So switch statement is much faster than if-else ladder.
    The switch statement body consists of a series of case labels and an optional default label. The default label can appear only once and anywhere in the body of the switch statement.
    Syntax of switch statement
    switch(expression)
    {
    case constant 1:
    statement 1;
    break;
    case constant 2:
    statement 2;
    break;
    .......
    case constant n:
    statement n;
    break;
    default:
    statement;
    }
    Syntax description of switch case statement
    • When the switch statement is executed, the value of expression is compared with the value of case constant (constant 1 , constant 2...) 
    • Then the block of statements associated with the case whose value is matched with expression will be executed. 
    • break statement at the end of block indicates the end of the particular case and cause an exit from switch statement and control will be transferred to statements following with switch.
    • If none of the case match with the value of the expression, then the block of statement under default is executed.
    Program-13 Write a program which reads any two integer values from the user and calculates sum, difference and product using switch statement.
    #include<stdio.h>
    main()
    {
    int a,b,choice,ans;
    printf("Enter any two numbers ");
    scanf("%d%d",&a,&b);
    printf("\n 1. Sum");
    printf("\n 2. Difference");
    printf("\n 3. Product");
    printf("\n Enter your choice(1-3): ");
    scanf("%d",&choice);
    switch(choice)
    {
    case 1:
    ans=a+b;
    printf("\n Sum of two numbers=%d ",ans);
    break;
    case 2:
    ans=a-b;
    printf("\n Difference of two numbers=%d ",ans);
    break;
    case 3:
    ans=a*b;
    printf("\n Product of two numbers=%d ",ans);
    break;
    default:
    printf("Wrong choice! Enter 1/2/3 only ");
    } }

    Ch5 Assignment 12

      if statement
    1. Write a C program to check whether the given number is positive.
    2. Write a C program to check whether the given number is odd.
    3. Write a C program to check whether hte given number is divisible by 5.
    4. if else statement
    5. Write a program to check whetehr the given number is odd or even.
    6. Write a program to check whether the given number is positive or negative.
    7. Write a program to check whether the given number is divisible by 5 and not divisible by 10.
    8. if else if statement
    9. Write a program to find the largest number among four numbers given by the user.
    10. Write a program to find the smallest number among five numbers given by the user.
    11. Write a program to check tje given number is positive, negative or zero.
    12. nested if else statement
    13. Write a program to find the largest number maong two positive numbers.
    14. Write a program to find the largest number among three positive numbets using nested if else statement.
    15. Write a program to find the given number is divisible by 5 and not by 10 using nested if else statement.
    16. switch statement
    17. Write a program to display the name of hte day in a week, depending on the number entered through the keyboard using the switch statement.
    Goto Top
    Looping

    Looping is the process of executing the same program statement or block of program statements repeatedly for a specified number of times or till the given condition is satisfied. Loop structure is used to carry out looping.

    For example, if we want to display "C is the best" 10 times, one way to get the desired output is - we type printf("C is the best"); 10 times, which is time consuming hence not preferable. Another way to perform this is - use of loop structure. With loop structure we don't need to type the same program statement again and again. Loop structure is also known as repetitive control structure or iterative control structure

    A control structure that executes the same program statement or block of program statements repeatedly for a specified number of times or till the given condition is satisfied is called Loop.

    Mainly there are three types of loop:
    1. while loop
    2. do while loop
    3. for loop
    while loop

    It executes the program statements repeatedly until the given condition is true. It checks the condition at first; if it is found true then it executes the statements written in its body part otherwise it just gest out from the loop structure. It is also known as entry control or pre-test loop.

    Syntax of while loop:
    initialization;
    while(condition)
    {
    statements;
    increment/decrement;
    }
    where initialization means starting point, condition means stopping point and increment/decrement means counter.
    Flowchart of while loop
    Program 14 Write a program to display “C is the best” 10 times using a while loop.
    #include<stdio.h>
    main()
    {
    int i=1;
    while(i<=10)
    {
    printf(" C is best\n ");
    i++;
    }
    }
    Program 15 Write a program to display numbers from 1 to 10 using a while loop.
    #include<stdio.h>
    main()
    {
    int i=1;
    while(i<=10)
    {
    printf(" %d\t ",i);
    i++;
    }
    }
    Program 16 Write a program to calculate and display sum of the numbers from 1 to 10 using a while loop.
    #include<stdio.h>
    main()
    {
    int i=1,sum=0;
    while(i<=10)
    {
    sum=sum+i;
    i++;
    }
    printf(" Sum of numbers between 1 to 10 is %d ",sum);
    }

    Assignment 13
    Write programs using while loop to:
    1. Display your name 10 times on screen
    2. Display the series:
       10    9   8 ..... to 1.
    3. Calculate and display sum of odd natural numbers up to n.
    do while loop

    It also executes program statements repeatedly until the given condition is true. It executes the program statements once at first then only condition is checked. If a condition is found true then it executes the program statements again, otherwise it gets out from the loop structure. As it checks the condition at last it is also known as the post-test loop or exit control loop.

    Syntax of do while Loop:
    initialization;
    do
    {
    statements;
    increment/decrement;
    }while (condition);
    Flowchart of do while Loop:
    do while loop flowchart
    Program 17 Write a program to display the series:
    1 6 11 16 ... 101
    #include<stdio.h>
    main()
    {
    int i=1;
    do
    {
    printf("%d\t",i);
    i=i+5;
    }while(i<=101);
    }
    Program 18 Write a program to display the series:
    5 9 13 ... to 10th terms.
    #include<stdio.h>
    main()
    {
    int i=1,a=5;
    do
    {
    printf("%d\t",a);
    a=a+4;
    i++;
    }while(i<=10);
    }
    Program 19 Write a program to display a multiplication table of 6.
    #include<stdio.h>
    main()
    {
    int i=1,ans;
    do
    {
    ans=6*i;
    printf("6 × %d = %d\n",i,ans);
    i++;
    }while(i<=10);
    }

    Assignment 14
    Write programs using do while loop to:
    1. Calculate and display the series:
    1 8 27 ... to 10th terms.
    2. Display the series:
    15 9 ... to 20th terms.
    3. Display the multiplication table of any number given by the user.

    Difference between while and do while loop
    while loop do while loop
    (i) In the while loop, condition is checked in the beginning. (i) In the do while loop, condition is checked at the end.
    (ii) It is also known as a pre-test or entry control loop. (ii) It is also known as post-test or exit control loop.
    (iii) It is not terminated with a semicolon. (iii) It is terminated with a semicolon.
    (iv) In the while loop, statements are not executed if the condition is false. (iv) In the do while loop, statements are executed once even the condition is false.
    (v) It uses the keyword ‘while’. (v) It uses two keywords ‘do’ and ‘while’.
    (vi) The syntax of while loop is as follows: initialization; while(condition) { statements; increment/decrement; } (vi) The syntax of do-while loop is as follows: initialization; do { statements; increment/decrement; } while(condition);
    (vii) The operation of while loop can be represented using flowchart as follows: (vii) The operation of do while loop can be represented using flowchart as follows: do while loop flowchart
    (viii) Example of while loop: #include<stdio.h> main() { int i=1; while(i>=10) { printf("I love my country"); i++; } }
    Output: This program displays nothing as output; as condition is evaluated false in the beginning.
    (viii) Example of do while loop: #include<stdio.h> main() { int i=1; do { printf("I love my country"); i++; }while(i>=10); }
    Output: This program displays "I love my country" as output at once.

    for loop

    It is the most common type of loop which is used to execute a program statement or block of program statements repeatedly for a specified number of times. It is a definite loop. Mainly it consists of three expressions: initialization, condition and increment / decrement. The initialization defines the loop starting point, condition defines the loop stopping points and counter helps to increment and decrement the value of counter variable.

    Syntax of for loop:
    for(initialization;condition;increment/decrement )
    {
    statements;
    }
    Flowchart of for loop
    Program 20 Write a program to calculate and display the value of y raised to power x. (z=yx)
    #include<stdio.h> main() { int x,y,i,z=1; printf("Enter the value of y and x"); scanf("%d%d",&y,&x); for(i=1;i<=x;i++) { z=z*y; } printf("%d raised to %d = %d",y,x,z); }
    Program 21 Write a program to calculate and display factorial of 5.
    The product of a given positive integer multiplied by all lesser positive integers: The quantity five factorial (5!) = 5x4 x 3 x 2 x 1 = 120.
    #include<stdio.h> main() { int i,f=1; for(i=5;i>=1;i--) { f=f*i; } printf("Factorial of 5 = %d",f); }
    Goto Top
    Nested Loop

    We can write an entire loop structure inside another loop structure. So a loop inside another loop is called a nested loop.

    Nested for loop Syntax:
    for(initialization; condition ; increment/decrement)
    {
    for(initialization; condition ; increment/decrement)
    {
    statements;
    }
    }
    Program 22 Write a program to display the following: 1 1 2 1 2 3 Answer: #include<stdio.h> main() { int i,j; for(i=1;i<=3;i++) { for(j=1;j<=i;j++) { printf("%d",j); } printf("\n"); } }
    Goto Top


    Practice Programs for Nested Loop by PLK compouter SIR:

    Algorithm to solve nested loop

    1. Write Outer Loop by making pattern of change value
    2. Write inner loop using the pattern generated with above outer loop reference
    3. Print matter
      3.1 Horizontal change- Inner Loop
      3.2 Horizontal not change- Outer Loop
      3.3 Everywhere same (*)- Print the repeating item
    4. Print New Line - after inner loop
    Nested Program-1 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 Pattern Analysis: 1-1 1-2 1-3 1-4 1-5 #include <stdio.h> main() { int i,j; for(i=1;i<=5;i++) { for(j=1;j<=i;j++) { printf(" %d ",j); } printf("\n"); } }
    Nested Program-2 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 Pattern Analysis: 1-1 1-2 1-3 1-4 1-5 #include <stdio.h> main() { int i,j; for(i=1;i<=5;i++) { for(j=1;j<=i;j++) { printf(" %d ",i); } printf("\n"); } }
    Nested Program-3 5 5 4 5 4 3 5 4 3 2 5 4 3 2 1 Pattern Analysis: 5-5 5-4 5-3 5-2 5-1 #include <stdio.h> main() { int i,j; for(i=5;i>=1;i--) { for(j=5;j>=i;j--) { printf(" %d ",j); } printf("\n"); } }
    Nested Program-4 5 4 4 3 3 3 2 2 2 2 1 1 1 1 1 Pattern Analysis: 5-5 5-4 5-3 5-2 5-1 #include <stdio.h> main() { int i,j; for(i=5;i>=1;i--) { for(j=5;j>=i;j--) { printf(" %d ",i); } printf("\n"); } }
    Nested Program-5 * * * * * * * * * * * * * * * Pattern Analysis: 1-1 1-2 1-3 1-4 1-5 #include <stdio.h> main() { int i,j; for(i=1;i<=5;i++) { for(j=1;j<=i;j++) { printf(" * "); } printf("\n"); } }
    Nested Program-6 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Pattern Analysis: 1-1 1-2 1-3 1-4 1-5 #include <stdio.h> main() { int i,j,p=1; for(i=1;i<=5;i++) { for(j=1;j<=i;j++) { printf("%5d",p); p=p+1; } printf("\n"); } }
    Nested Program-7 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 Pattern Analysis: 1-1 1-2 1-3 1-4 1-5 #include <stdio.h> main() { int i,j,p=2; for(i=1;i<=5;i++) { for(j=1;j<=i;j++) { printf("%3d",p); p=p+2; } printf("\n"); } }
    Nested Program-8 1 2 3 4 5 1 2 3 4 1 2 3 1 2 1 Pattern Analysis: 1-5 1-4 1-3 1-2 1-1 #include <stdio.h> main() { int i,j; for(i=5;i>=1;i--) { for(j=1;j<=i;j++) { printf("%3d",j); } printf("\n"); } }
    Nested Program-9 5 5 5 5 5 4 4 4 4 3 3 3 2 2 1 Pattern Analysis: 1-5 1-4 1-3 1-2 1-1 #include <stdio.h> main() { int i,j; for(i=5;i>=1;i--) { for(j=1;j<=i;j++) { printf("%3d",i); } printf("\n"); } }
    Nested Program-10 5 4 3 2 1 5 4 3 2 5 4 3 5 4 5 Pattern Analysis: 5-1 5-2 5-3 5-4 5-5 #include <stdio.h> main() { int i,j; for(i=1;i<=5;i++) { for(j=5;j>=i;j--) { printf("%3d",j); } printf("\n"); } }
    Nested Program-11 1 1 1 1 1 2 2 2 2 3 3 3 4 4 5 Pattern Analysis: 5-1 5-2 5-3 5-4 5-5 #include <stdio.h> main() { int i,j; for(i=1;i<=5;i++) { for(j=5;j>=i;j--) { printf("%3d",i); } printf("\n"); } }
    Nested Program-12 * * * * * * * * * * * * * * * Pattern Analysis: 1-5 1-4 1-3 1-2 1-1 #include <stdio.h> main() { int i,j; for(i=5;i>=1;i--) { for(j=1;j<=i;j++) { printf(" * "); } printf("\n"); } }
    Nested Program-13 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 Pattern Analysis: 1-5 1-4 1-3 1-2 1-1 #include <stdio.h> main() { int i,j,p=15; for(i=5;i>=1;i--) { for(j=1;j<=i;j++) { printf("%3d",p); p=p-1; } printf("\n"); } }
    Nested Program-14 1 2 3 2 3 4 3 4 5 4 5 6 5 6 7 Pattern Analysis: 1-3 2-4 3-5 4-6 5-7 #include <stdio.h> main() { int i,j; for(i=1;i<=5;i++) { for(j=0;j<=2;j++) { printf("%3d",i+j); } printf("\n"); } }
    Nested Program-15 1 2 3 ... N 2 4 6 ...2N 3 6 9 ...3N ------------ N 2N 3N ...NN Pattern Analysis: 1 - N 1 - 2N 1 - 3N ----- N - NN #include <stdio.h> main() { int i,j,n; printf("Enter the value for n: "); scanf("%d",&n); for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { printf("%3d",i*j); } printf("\n"); } }

    Goto Top
    Infinite Loop

    A loop which never terminates is called infinite loop that is it executes the program statements repeatedly which doesn’t meet any ending point.

    Example of infinite loop:
    #include<stdio.h> main() { int i; for(i=1;i>=0;i++) { printf("%d",i); } }
    Goto Top
    Jumping Statement

    Jumping statements are particularly used to jump execution of program statements from one place to another place inside a program. These statements may execute the same program statement repeatedly or skip some program statements. Following are the jumping statements defined in C programming language.

    • break
    • continue
    • goto
    break statement

    As its name implies, it is used to break the normal flow of program statement execution in loop and switch case statement. It allows us to exit from the innermost enclosing loop or switch statement as soon as certain condition is satisfied.

    When ‘break’ is encountered in the program (loop body/switch statement), the remaining part of the loop/switch statement is skipped and control will be passed to the next statement after loop; terminating the loop/switch statement. For example, while searching a number in a set of 100 numbers; when the required number is found it is obvious to get terminated from the loop. In such cases a break statement is used to do so.

    Example of break statement:
    #include <stdio.h> main() { int i; for(i=1;i<=5;i++) { if(i==4) break; printf(" %d\t ",i); } }

    When the value of i becomes 4 then break is encountered and control is passed to outside the loop structure.

    The output of this program is : 1 2 3

    continue statement

    As its name implies, it is used to continue the normal flow of program statement execution in loop; skipping particular iteration in the loop as soon as certain condition is satisfied. When 'continue' is encountered in the program (loop body) then that particular iteration is skipped and the loop will be continued with the next iteration.

    Example of continue statement:
    #include <stdio.h> main() { int i; for(i=1;i<=5;i++) { if(i==4) continue; printf(" %d\t ",i); } }

    When the value of i becomes 4, 'continue' is encountered then that iteration for which i equals 4 is skipped and it continues with i equals 5.

    The output of this program is : 1 2 3 5

    Goto Top

    Differences between break and continue statement break statement
    break statement continue statement
    (i) When a break statement is encountered the entire loop or switch statement is terminated. (i) When continue statement is encountered the entire loop is not terminated; only that particular iteration is skipped.
    (ii) It is used with loop and switch case statements. (ii) It is used only with loop structure.
    (iii) It uses a keyword break (iii) It uses a keyword continue
    Example Program using break:
    #include <stdio.h> main() { int i; for(i=1;i<=5;i++) { if(i==4) break; printf(" %d\t ",i); } }

    Output:

    1 2 3
    Example Program using continue:
    #include <stdio.h> main() { int i; for(i=1;i<=5;i++) { if(i==4) continue; printf(" %d\t ",i); } }

    Output:

    1 2 3 5

    goto statement

    When a goto statement is encountered in a program then it transfers the control of the program statements execution unconditionally to the location specified by the goto statement within a current function.

    Syntax of goto statement:
    goto label;

    where the label is an identifier that is used to label the target statement to which the control is transferred. Control may be transferred to anywhere within the current function. The target statement must be labeled, and a colon must follow the label. Thus the target statement will appear as

    label: statement;

    Each labeled statement within the function must have a unique label, that is, no two statements can have the same label.

    Program 23 Write a program to display numbers from 1 to 10 using goto statement.
    #include<stdio.h> main() { int i=1; label1: printf("%d\n",i); i++; if(i<=10) goto label1; }

    Assignment 15
    1. Write a program to display multiplication table of given number
    2. Write a program to display the multiplication table with NxN terms.
    3. Write a program to display the odd series 1 3 5 ..... N using continue statement.
    4. Write a program to show an infinite loop.
    5. Write a program to display the following output. 3 3 3 2 2 1
    Goto Top

    Program 24 Write a program to display the following Fibonacci series: 1 1 2 3 5 ... to nth terms

    [An integer in the infinite sequence 0,1, 1, 2, 3, 5, 8, 13, … of which the first two terms are 0 and 1 and each succeeding term is the sum of the two immediately preceding is called Fibonacci Series.]

    #include<stdio.h> main() { int a=1,b=1,c,n,i; printf("Enter any number : "); scanf("%d",&n); for(i=1;i<=n;i++) { printf("%d\t",a); c=a+b; a=b; b=c; } }
    Program 25 Write a program to calculate and display sum of digits present in the given number.[123=1+2+3=6]
    #include<stdio.h> main() { int num,sum=0,r; printf("Enter any number : "); scanf("%d",&num); while(num!=0) { r=num%10; sum=sum+r; num=num/10; } printf("Sum of digits is %d",sum); }
    Program 26 Write a program to check if the given number is palindrome or not.

    [ If the reverse of the given number is the same as number , then it is said to be palindrome. Example: 121 is palindrome number]

    #include<stdio.h> main() { int num,sum=0,r,n; printf("Enter any number : "); scanf("%d",&num); n=num; while(num!=0) { r=num%10; sum=sum*10+r; num=num/10; } if(n==sum) printf(" %d is Palindrome number",n); else printf("%d is not palindrome",n); }
    Program 27 Write a program to convert from decimal number system into binary number system.
    #include<stdio.h> main() { int num,r,i=1,sum=0; printf(" Enter decimal number :"); scanf("%d",&num); while(num!=0) { r=num%2; sum=sum+r*i; num=num/2; i=i*10; } printf(" Binary Equivalent is %d ",sum); }
    Program 28 Write a program to convert the given binary number into equivalent decimal number.
    #include<stdio.h> #include<math.h> main() { int num,r,i=0,sum=0; printf("Enter Binary number : "); scanf("%d",&num); while(num!=0) { r=num%10; sum=sum+pow(2,i)*r; num=num/10; i++; } printf("Decimal Equivalent is %d",sum); }
    Program 29 Write a program to check whether the given number is prime or composite. [Prime numbers are those whole numbers which have only two factors i.e. one and itself. Example: 19 is prime number because it has only two factors 1 & 19]
    #include<stdio.h> main() { int num,i,count=0; printf("Enter any number : "); scanf("%d",&num); for(i=1;i<=num;i++) { if(num%i==0) count++; } if(count==2) printf("%d is prime number",num); else printf("%d is composite number",num); }
    Program 30 Write a program to display all prime numbers from 1 to 100.
    #include<stdio.h> main() { int i,j,count; for(i=1;i<=100;i++) { count=0; for(j=1;j<=i;j++) { if(i%j==0) count++; } if(count==2) printf("%d\t",i); } }
    Goto Top
    5.2.15 Definition of Array

    It may be convenient to store a collection of similar data elements in different separate variables. For example, if the age of 100 persons were to be stored in variables with unique names, it certainly would be difficult, that means 100 variables needed for assigning the individual values. So an array certainly solves this problem because basically the variable name is the same. We differentiate among the values in an array by its unique subscripts with defined size.

    An array is a collection of similar types of data items treated as a single unit. It acts to store related data under the same name with an index, also known as a subscript which helps to access individual array elements. Array data type may be int, float, char etc, depending upon the nature of problems.

    Characteristics of Array

    • All the array elements share the common name.
    • The elements of the array are stored in contiguous memory locations.
    • By declaring or using an array, the program becomes short and simple which handles a large volume of similar kinds of data items.
    • We put the array size of fixed length as required that means once the size is declared then the size will be fixed at the execution time of the program, so called static type.
    • We can randomly access to every element using numeric index, index starts from 0 and ends at size-1.

    Advantages of Array

    • It is easier for handling similar types of data in a program.
    • It is efficient for solving problems like sorting, searching, indexing etc
    • It is very close to matrix, therefore it is easy for solving matrix related problems
    • Graphic is an array of pixels, so graphics manipulation can be easily done using an array.

    Disadvantages of Array

    • It is not possible to hold a dissimilar type of data in an array.
    • It is difficult to visualize the multi-dimensional array.
    • It is static in nature so it is difficult to define the size of array during running time.
    Types of Array

    There are two types of array which are as follows.

    1. One Dimensional Array: An array which has only one subscript is named as one dimensional array, a subscript is a number of large brackets in which we put the size of the array.
    2. Multi Dimensional Array: An array which has more than one subscript is named as a multi dimensional array, subscripts define each dimension of the array.
    Declaration of One Dimensional Array:

    Like any other variable, we have to declare array before they are used. The general form of one dimensional array declaration is,

    Syntax:
    Data_type array_name[array_size];

    As in above syntax, the data_type refers to the type of array elements, array the name of the array variable and the array size indicates number of elements that can be stored inside the array, Hence if the size of array is n, for example: a[n], a[0] is the first element and a[n-1] is the last element of the array.

    Example 1

    int a[5];

    In this example, the variable a is an array of integer with size five elements.

    Example 2

    float weight[100];

    In this example, the variable weight is an array of floating point numbers having size 100.

    Example 3

    char temp[10];

    In this example, temp variable is an array of characters with size 10 and it is also known as string.

    Initialization of an Array

    We can initialize arrays at the time of declarations. The initial value must appear which will be assigned to the individual array elements, enclosed within the brace and separated by commas.

    Syntax
    data_type array name [size] = {val1, val2, val3,..valn};

    Here val1 is the value for the first array element, val2 is the value for the second array element, val3 is the value for the three array element and valn is the value for the last array element.

    Example of an Array Initialization:
    int marks[4]={50, 60, 65, 70};

    Here the number of subscripts determines the dimension of array ; that is one dimensional array means here is only one subscript. The value in the bracket is the size of the array. marks[0] is the first element of the array where 0 is the starting index of array.

    marks[0] marks[1] marks[2] marks[3]
    50 60 65 70
    index 0 index 1 index 2 index 3

    The values to the array elements can be assigned as follows:

    marks[0]=50;
    marks[1]=60;
    marks[2]=65;
    marks[3]=70;
    Other Examples:

    int a[]={6,7,8,9,10}; //default size is 5 float x[5]={70.5,45.75,85.97,78.87,66.33}; char name[10]={‘n’,‘e’,‘p’,‘a’, ‘l’};

    Program 31 Write a program to input 5 numbers in an array and display them. [NEB 2075 Set B]
    #include<stdio.h> main() { int i,num[5]; for(i=0;i<5;i++) { printf("Enter num[%d] : ", i+1); scanf("%d",&num[i]); } printf("Array elements are:\n "); for(i=0;i<5;i++) { printf(" num[%d] = %d\n ",i+1,num[i]); } }
    Program 32 Write a program to input 5 numbers with constant values initialization in array and display their sum.
    #include<stdio.h> main() { int i,sum=0; int num[5]={100,30,55,60,75}; printf(" The five numbers of array are: "); for(i=0;i<5;i++) { printf(" %d ", num[i]); sum=sum+num[i]; } printf("\n Sum of five numbers is : %d ", sum); }
    Program 33 Write a program to input the age of 20 students and count the number of students having age in between 20 to 25.
    #include<stdio.h> main() { int age[20],i,count=0; for(i=0;i<20;i++) { printf("Enter age[%d] : ",i+1); scanf("%d", &age[i]); } for(i=0;i<20;i++) { if(age[i]>=20 && age[i]<=25) count++; } printf("Total number of students having age in between 20 to 25 is %d ", count); }
    Program 34 Write a program to find the largest number among ‘n’ numbers.
    #include<stdio.h> main() { int num[100],i,n,largest; printf("Enter array size not more than 100 : "); scanf("%d",&n); for(i=0;i<n;i++) { printf(" Enter num[%d] : ", i+1); scanf("%d", &num[i]); } largest=num[0]; for(i=0;i<n;i++) { if(num[i]>largest) largest=num[i]; } printf(" Largest number is %d ",largest); }
    Program 35 Write a program to input ‘n’ numbers and search whether it is in the list or not.[Program for sequential search]
    #include<stdio.h> main() { int n,num[100],i,searchnum; printf(" Enter array size not more than 100 : "); scanf("%d",&n); for(i=0;i<n;i++) { printf("Enter num[%d] :", i+1); scanf("%d", &num[i]); } printf("Enter a number to be searched "); scanf("%d",&searchnum); for(i=0;i<n;i++) { if(searchnum==num[i]) { printf("%d is in the list", searchnum); break; } } if(n==i) printf(" %d is not in the list", searchnum); }
    Program 36 Write a program to input ‘n’ numbers and sort them in ascending order.
    #include<stdio.h> main() { int n,num[100],i,j,temp; printf("Enter array size not more than 100 : "); scanf("%d",&n); for(i=0;i<n;i++) { printf("Enter num[%d] : ", i+1); scanf("%d",&num[i]); } for(i=0;i<n-1;i++) { for(j=i+1;j<n;j++) { if(num[i]>num[j]) { temp=num[i]; num[i]=num[j]; num[j]=temp; } } } printf("Numbers in Ascending order\n"); for(i=0;i<n;i++) { printf("%d\n",num[i]); } }
    Goto Top
    NEB Past Questions Answers from 1-D Array
    NEB 2075 Set A Write a program to input 10 integer numbers into an array and display the sum of the numbers. [10] OR
    Write a program to input any 10 integer numbers in an array and find the total. [10] NEB 2074 Supp.
    #include<stdio.h> main() { int num[10],i,sum=0; for(i=0;i<10;i++) { printf("Enter num[%d] : ",i+1); scanf("%d", &num[i]); } for(i=0;i<10;i++) { sum=sum+num[i]; } printf(" \n The sum is %d ", sum); }
    [HSEB 2062-10 Mark] Write an algorithm and C Program to read salaries of 200 employees and count the number of employees getting salaries between 5,000-10,000.

    Algorithm:

    Step 1: Start Step 2: Set I =0 and count=0 Step 3: Check is I<200 3.1: If Yes, Input Salary and go to step 4 3.2: If No, goto step 5 Step 4: Calculate I=I+1 and go to step 3 Step 5: Set I =0 Step 6: Check is I<200 6.1: If Yes, Check is salary between 5000 to 10000. If yes increase the value of count by 1, If no, goto step 7 6.2: If No, goto step 5 Step 7: Calculate I=I+1 and go to step 6 Step 8: Display the count Step 9: Stop C Program: #include <stdio.h> main() { int salary[200],i,count=0; for(i=0;i<2;i++) { printf("Employee no . %d Salary = ", i+1); scanf("%d",&salary[i]); } for(i=0;i<2;i++) { if(salary[i]>=5000 && salary[i]<=10000) count++; } printf("Number of employee getting salary between 5000 to 10000 is %d ", count); }
    [HSEB 2063-10 Mark] Write a C program to read the age of 40 students and count the number of students of the age between 15 to 22.
    #include <stdio.h> main() { int age[40],i,count=0; for(i=0;i<40;i++) { printf("Student No. %d age ",i+1); scanf("%d", &age[i]); } for(i=0;i<40;i++) { if(age[i]>=15 && age[i]<=22) count++; } printf(" \n The number of students having age in between 15 to 22 is %d ", count); }
    [HSEB 2068-10 Mark] Write a C Program to read salaries of 300 employees and count the number of employees getting salaries between 10,000 to 15,000.
    #include <stdio.h> main() { int salary[300],i,count=0; for(i=0;i<300;i++) { printf("Employee No. %d salary ",i+1); scanf("%d", &salary[i]); } for(i=0;i<300;i++) { if(salary[i]>=10000 && salary[i]<=15000) count++; } printf(" \n The number of Employee getting salary between 10000 to 15000 is %d ", count); }
    [HSEB 2070-10 Mark] Write a C Program to read salaries of 25 employees and count the number of employees getting salaries between 30,000 to 40,000.
    #include <stdio.h> main() { int salary[25],i,count=0; for(i=0;i<2;i++) { printf("Employee No. %d salary ",i+1); scanf("%d", &salary[i]); } for(i=0;i<2;i++) { if(salary[i]>=30000 && salary[i]<=40000) count++; } printf(" \n The number of Employee getting salary between 30000 to 40000 is %d ", count); }
    [NEB 2076- 2+4+4] Define array. Write a program to input any 10 numbers in an array and display it. Find the biggest number among the input numbers.
    C program to display 10 numbers using array #include <stdio.h> main() { int num[10],i; for(i=0;i<10;i++) { printf(" Enter %d number ", i+1); scanf("%d", &num[i]); } printf("Entered ten numbers are : \n "); for(i=0;i<10;i++) { printf(" %d ",num[i]); } } Also,biggest number among ten numbers #include <stdio.h> main() { int num[10],i,big; for(i=0;i<10;i++) { printf(" Enter %d number ", i+1); scanf("%d", &num[i]); } big=num[0]; for(i=0;i<10;i++) { if(num[i]>big) big=num[i]; } printf("Biggest number is %d ",big); }
    [NEB 2073- 10 Marks] Write a C program to read five positive numbers using an array and find out the smallest among them.
    #include <stdio.h> main() { int num[5],i,smallest; for(i=0;i<5;i++) { printf("Enter %d number ", i+1); scanf("%d", &num[i]); } smallest=num[0]; for(i=0;i<5;i++) { if(num[i]<smallest) smallest=num[i]; printf("smallest number is %d ", smallest); }
    [NEB 2074 , 2077 - 10 Marks] Define array. Describe the syntax of array. Write a program to sort ten integer numbers in ascending order.
    #include <stdio.h> main() { int num[10],i,j,temp; for(i=0;i<10;i++) { printf("Enter %d numebr ",i+1); scanf("%d", &num[i]); } for(i=0;i<9;i++) { for(j=i+1;j<10;j++) { if(num[i]>num[j]) { temp=num[i]; num[i]=num[j]; num[j]=temp; } } } printf(" Array in Ascending Order \n"); for(i=0;i<10;i++) { printf(" %d ", num[i]); } }
    Ten integers in Descending order:
    #include <stdio.h> main() { int num[10],i,j,temp; for(i=0;i<10;i++) { printf("Enter %d number ", i+1); scanf("%d",&num[i]); } for(i=0;i<9;i++) { for(j=i+1;j<10;j++) { if(num[i]<num[j]) { temp=num[i]; num[i]=num[j]; num[j]=temp; } } } printf("Ten integers in Descending order\n"); for(i=0;i<10;i++) { printf(" %d ",num[i]); } }
    Goto Top
    Multi Dimensional Array

    Multi dimensional arrays are defined the same as one-dimensional arrays, except that it consists of more than one pair of square brackets that are subscripts. Thus a two dimensional array will require two square brackets, one for row size and other for column size. The  maximum capacity of elements of an array is the product of row size and column size. A three dimensional array will require three square brackets, and so on.


    In general terms, a multidimensional array definition can be written as data_type array_name [expression1] [expression2] ..... [expression n];

    In two dimensional array declaration we write,
    data_type array_name [row_size] [column_size];

    As in above syntax, the data_type refers to the type of array elements, array_name is the name of the array variable and row_size, column_size are the number of array elements associated with each subscript that can be stored inside the array.

    For example, a[m][n] is a 2 dimensional array in which the starting element of array is a[0][0] and the last element of array is a[m-1][n-1]. Here, in a[m][n], m denotes the row size and n denotes the column size in array.


    Initialization of 2-D Array

    If we have m*n array, it will have m*n elements and will require m*n element size bytes of storage. To allocate storage for an array you must reserve this amount of memory. The elements of a two dimensional array are stored row wise.

    In two dimensional array (suppose 3x3 matrix), data items are stored in memory below:

    Column 0
    [0][0]
    Column 1
    [0][1]
    Column 2
    [0][2]
    Row 0 100 200 300
    [1][0] [1][1] [1][2]
    Row 1 200 150 50
    [2][0] [2][1] [2][2]
    Row 2 350 500 600

    As in above example, two dimensional array consist of 3 rows and 3 columns, the starting array element is 100 that is stored in position matrix[0][0] and the last array element is 600 that is stored in position matrix[2][2].

    This means,

    int matrix[3][3]={100, 200, 300, 200, 150, 50, 350, 500, 600};

    matrix[0][0]= 100; matrix[0][1]= 200; matrix[0][2]= 300; matrix[1][0]= 200; matrix[1][1]= 150; matrix[1][2]= 50; matrix[2][0]= 350; matrix[2][1]= 500; matrix[2][2]= 600;

    Differentiate between one dimensional and two dimensional array:

    One Dimensional Array Two Dimensional Array
    (i) It consists of only one subscript. (i) It consists of two subscripts.
    (ii) Maximum size will be the size of the array which we define in the program. (ii) Maximum size will be the product of row and column size of array which we define in the program.
    (iii) It stores data either row wise or column wise. (iii) It stores data in matrix form that is row wise and column wise.
    (iv) Syntax:
    Data_type array_name[array_size];
    (iv) Syntax:
    Data_type array_name[row_size][column_size];
    (v) Example: int num[5]; (v) Example: int matrix[2][2];
    (vi) Program:
    #include <stdio.h> int main() { int num[4]={1,2,3,4},i; for(i=0;i<4;i++) { printf("%3d",num[i]); } }
    (vi) Program:
    #include <stdio.h> main() { int matrix[2][2]={1,2,3,4},i,j; for(i=0;i<2;i++) { for(j=0;j<2;j++) { printf("%3d",matrix[i][j]); } printf("\n"); } }
    Program 37 Write a program to store 9 numbers with constant values in 2 dimensional array that is 3x3 matrix and print in matrix form.
    #include <stdio.h> main() { int matrix[3][3]={1,2,3,4,5,6,7,8,9},i,j; printf("The given matrix is \n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { printf("%d\t",matrix[i][j]); } printf("\n"); } }
    Worked out Examples on 2-D Array
    Program 38 Write a program to input data in two dimensional array for example 3x3 matrix and display in matrix form.
    #include <stdio.h> main() { int matrix[3][3],i,j; for(i=0;i<3;i++) { for(j=0;j<3;j++) { printf("Enter matrix[%d][%d] element:",i+1,j+1); scanf("%d",&matrix[i][j]); } } printf("The given matrix is \n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { printf("%d\t",matrix[i][j]); } printf("\n"); } }
    Program 39 Write a program to input two matrices. Add two matrices and display in proper format.
    #include <stdio.h> main() { int m1[5][5],m2[5][5],m3[5][5],i,j,r,c; printf("Enter the row and column size : "); scanf("%d%d",&r,&c); for(i=0;i<r;i++) { for(j=0;j<c;j++) { printf("Enter first matrix [%d][%d] : ",i+1,j+1); scanf("%d",&m1[i][j]); } } for(i=0;i<r;i++) { for(j=0;j<c;j++) { printf("Enter second matrix [%d][%d] : ",i+1,j+1); scanf("%d",&m2[i][j]); } } for(i=0;i<r;i++){ for(j=0;j<c;j++){ m3[i][j]=m1[i][j]+m2[i][j]; } } printf("Sum of two %d*%d matrices is \n",r,c); for(i=0;i<r;i++) { for(j=0;j<c;j++) { printf("%d\t",m3[i][j]); } printf("\n"); } }
    [CDC Model Set 2077 - 8 marks]Write a program to input the elements of 4 x 3 matrix and prints its elements properly using array.
    #include <stdio.h> main() { int matrix[4][3],i,j; for(i=0;i<4;i++) { for(j=0;j<3;j++) { printf("Enter matrix[%d][%d] element:",i+1,j+1); scanf("%d",&matrix[i][j]); } } printf("The given matrix is \n"); for(i=0;i<4;i++) { for(j=0;j<3;j++) { printf("%d\t",matrix[i][j]); } printf("\n"); } }
    [NEB Question - 2074 ] Write a program to find addition of any two matrix of size 2*2 using array. [10]
    #include <stdio.h> main() { int m1[2][2],m2[2][2],m3[2][2],i,j; for(i=0;i<2;i++) { for(j=0;j<2;j++) { printf("Enter [%d][%d] elements of First Matrix " , i+1,j+1); scanf("%d",&m1[i][j]); } } for(i=0;i<2;i++) { for(j=0;j<2;j++) { printf("Enter [%d][%d] elements of Second Matrix " , i+1,j+1); scanf("%d",&m2[i][j]); } } for(i=0;i<2;i++) { for(j=0;j<2;j++) { m3[i][j]=m1[i][j]+m2[i][j]; } } printf("Sum of given matrix is \n"); for(i=0;i<2;i++) { for(j=0;j<2;j++) { printf("%d\t",m3[i][j]); } printf("\n"); } }
    [NEB Question 2073 Supp ] Write a program to enter elements into 4*4 matrix and find the sum of the elements of the matrix. [5+5]
    #include <stdio.h> main() { int m1[4][4],m2[4][4],m3[4][4],i,j; for(i=0;i<4;i++) { for(j=0;j<4;j++) { printf("Enter first matrix [%d][%d] : ",i+1,j+1); scanf("%d",&m1[i][j]); } } for(i=0;i<4;i++) { for(j=0;j<4;j++) { printf("Enter second matrix [%d][%d] : ",i+1,j+1); scanf("%d",&m2[i][j]); } } for(i=0;i<4;i++){ for(j=0;j<4;j++){ m3[i][j]=m1[i][j]+m2[i][j]; } } printf("Sum of two 4*4 matrices is \n"); for(i=0;i<4;i++) { for(j=0;j<4;j++) { printf("%d\t",m3[i][j]); } printf("\n"); } }
    C Program to find multiplication of two matrices of size 2x2.
    #include<stdio.h> int main() { int i,j,k,a[2][2],b[2][2],c[2][2]; for(i=0;i<2;i++) { for(j=0;j<2;j++) { printf("Enter a[%d][%d] : ",i,j); scanf("%d",&a[i][j]); } } for(i=0;i<2;i++) { for(j=0;j<2;j++) { printf("Enter b[%d][%d] : ",i,j); scanf("%d",&b[i][j]); } } for(i=0;i<2;i++) { for(j=0;j<2;j++) { c[i][j]=0; for(k=0;k<2;k++) { c[i][j]=c[i][j]+a[i][k]*b[k][j]; } } } printf("\n Multiplication of given matrix \n"); for(i=0;i<2;i++) { for(j=0;j<2;j++) { printf("%d\t",c[i][j]); } printf("\n"); } return 0; }
    Goto Top

    Definition of String:

    String is the set of characters,digits and symbols. We can also define string as the array of characters. The end of the string is marked with a special character , the ‘\0’ that means Null character. The size in a character string represents the maximum number of characters that the string can hold.

    A string is an array of characters. It contains characters, symbols, numbers etc.
    Syntax of string:
    char string_name[string_size];

    As in above syntax, char refers to the character data type that will be stored in the array, string_name is the name of the string variable and string_size indicates the number of characters that can be stored inside the array.

    Example
    char name[10];
    char address[10];

    This declares the name as a character array (string) variable that can hold a maximum of 10 characters.

    String is simply a sequence of characters, so to declare a string, we have to put data type char with string name with square brackets.


    Initialization of Strings
    Let us take a string:
    char name[5]={‘a’, ‘l ’, ‘e’, ‘x’,‘\0’};
    or second method
    char name[5]= “alex” ;
    Each character is treated as an element of the array name and is stored in the memory as follows:
    name[0] name[1] name[2] name[3] name[4]
    'a' 'l' 'e' 'x' '\0'
    Index 0 Index 1 Index 2 Index 3 Index 4

    When the compiler sees a character string, it terminates it with an additional null character means empty. Thus, the element name[4] holds the null character ‘\0’ at the end. When declaring a character array, we must always allow one extra element space for the null terminator.

    Program 40 Write a program to input a string from user and display it.
    #include<stdio.h> main() { char name[10]; printf("Enter your name : "); scanf("%s",name); printf("Your name is : %s",name); }
    Program 41 Write a program to find the length of given string.[No. of characters in a string]
    #include<stdio.h> main() { char str[100]; int i; printf("Enter a string: "); scanf("%s",str); for(i=0;str[i]!='\0';i++); // no body part of the loop, so we use semicolon on the loop printf("Length of string is %d",i); }
    String Handling Functions

    The C library supports a large number of string handling functions that can be used to carry out many of the string manipulation. The header file #include<string.h> is used for string manipulation functions. Some of the common string manipulation functions are:

    1. strlen() function

    The strlen() function returns the length of a string which takes the string name as an argument.

    Syntax:
    l=strlen(str);

    where, str is the name of string and l is the length of the string, returned by function.

    Program 42 Write a program to find the length of a string.
    #include<stdio.h> #include<string.h> main() { char str[100]; int l; printf(" Enter a string : "); scanf("%s",str); l=strlen(str); printf(" The length of string is %d ",l); }
    2. strrev() function

    The strrev() function is used to reverse the given string.

    Syntax:
    strrev(str);
    where str is string to be reversed.
    Program 43 Write a program to reverse the given string.
    #include<stdio.h> #include<string.h> main() { char str[100]; printf(" Enter a string : "); scanf("%s",str); strrev(str); printf(" Reverse of the given string is %s ",str); }
    3. strcpy() function

    The strcpy() function is used to copy one string into another string.

    Syntax:
    strcpy(destination,source)
    or
    strcpy(strl,str2);
    where strl,str2 are two strings.
    The content of string str2 is copied on string strl.
    Program 44 Write a program to copy one string into another string.
    #include<stdio.h> #include<string.h> main() { char str1[100],str2[100]; printf(" Enter a string : "); scanf("%s",str1); strcpy(str2,str1); printf(" After copying the string is %s ",str2); }
    4. strcat() function

    The strcat() function is used to join or concatenate one string into another string.

    Syntax:
    strcat(strl,str2);

    where str1,str2 are two strings. The content of string str2 is concatenated with string str1.

    Program 45 Write a program to concatenate two strings into one string.
    #include<stdio.h> #include<string.h> main() { char str1[100],str2[100]; printf(" Enter First string : "); scanf("%s",str1); printf(" Enter Second string : "); scanf("%s",str2); strcat(str1,str2); printf(" After concatenating the two string is %s ",str1); }
    5. strcmp( ) function

    The strcmp() function is used to compare two strings, character by character and stops comparison when there is a difference in the ASCII value or the end of any one string and returns ASCII difference of the character that is integer.

    Syntax:
    v=strcmp(strl,str2);

    Where, str1 and str2 are two strings to be compared and v is a value returned by the function which is either zero(equal), positive value(descending) or negative value(ascending).

    Program 46 Write a program to compare two strings
    #include<stdio.h> #include<string.h> main() { char str1[100],str2[100]; int v; printf(" Enter First string : "); scanf("%s",str1); printf(" Enter Second string : "); scanf("%s",str2); v=strcmp(str1,str2); if(v==0) printf(" Both strings are same. "); else if(v>0) printf(" %s comes after %s ",str1,str2); else printf(" %s comes before %s ",str1,str2); }
    6. strlwr() function

    The strlwr() function is used to convert upper case characters of string into lower case characters.

    Syntax:
    strlwr (str);
    where str is string to be converted into lower case characters.
    Program 47 Write a program to convert the given string into lower case.
    #include<stdio.h> #include<string.h> main() { char str[100]; printf(" Enter a string : "); scanf("%s",str); strlwr(str); printf(" The string in lowercase is %s ",str); }
    7. strupr() function

    The strupr() function is used to convert lower case characters of string into upper case characters.

    Syntax:
    strupr (str);
    where str is string to be converted into upper case characters.
    Program 48 Write a program to input string in array and display them.
    #include<stdio.h> #include<string.h> main() { char str[100]; printf(" Enter a string : "); scanf("%s",str); strupr(str); printf(" The string in uppercase is %s ",str); }
    Array of String

    A two dimensional array of characters is called an array of strings. It is also known as a table of strings. It is very useful for solving string sorting problems. In other words, an array of strings can be declared and handled like a two dimensional array.

    Syntax:
    char string_name[RSIZE][CSIZE];

    As in above syntax, char refers to character data type, string_name is the name of the string variable and in two dimensional array, [RSIZE] indicates the number of strings and [CSIZE] indicates the maximum number characters associated with string.

    Example
    char name[5][10];

    In this example, the array is initialized with five character strings with maximum size ten.

    Program 49 Write a program that takes 5 strings and display them.
    #include<stdio.h> main() { char str[5][10]; int i; for(i=0;i<5;i++) { printf("Enter str[%d] : ",i+1); scanf("%s",str[i]); } printf(" The strings are :\n"); for(i=0;i<5;i++) { printf("%s\n",str[i]); } }
    Program 50 Write a program to input strings and sort them in alphabetical order.
    #include<stdio.h> #include<string.h> main() { char str[50][30],temp[30]; int i,j,n; printf("How many strings ? "); scanf("%d",&n); for(i=0;i<n;i++) { printf("Enter str[%d] : ",i+1); scanf("%s",str[i]); } for(i=0;i<n-1;i++) { for(j=i+1;j<n;j++) { if(strcmp(str[i],str[j])>0) { strcpy(temp,str[i]); strcpy(str[i],str[j]); strcpy(str[j],temp); } } } printf("The sorted strings are:\n"); for(i=0;i<n;i++) { printf("%s\n",str[i]); } }
    End of Chapter-5