Introduction:
As we know every computerized device does not work by itself. They needed to be given some sort of command that makes computer work. These commands helps to instruct computer and program specific action required by the user. Since the command are given in the form of computer language, we need programming language are used to write the set of instruction which commands the computer to perform certain action collectively called programs. These programs are again integrated in order to make a complete software. Simply software is the collection of different interrelated program which performs specific function.
Program Written in any type of programming language are not understood by the computer hence we need some sort of language translator or processor such as assembler, complier and interpreter which has the basic function of converting program written in any type of language into machine level language.
The program written by the programmer is known as source program. After converting it becomes program.
Qualities of good programs.
- It should be easily understood.
- A program should be correct; it should be error free.
- It should be reliable.
- It should have easily understandable user interface.
- It should be portable and flexible.
Programming Language:
In order to make communication between user and computer, we need a computer language that helps user to generate commands to perform as per the requirement. This language with which we can give instruction to the computer is known as programming language. Programming language are the set of different keywords, variables, operators, loops, and other entities using different character sets including numbers, special symbol and alphanumeric values.
Hence, the process of writing the programming language is known as programming and the person who writes program is programmers.
Types of Programming Language
There are several types of programming language which can be categorized as follows:
- Low level language: Low level language are the machine dependent language which means program written for one type of system cannot be run in another system. Developer should have detail analysis and knowledge about the system for which s/he is going to write a program for. Hence, programming in low level language is very much difficult and time consuming. Different types of programming language are:
a. Machine level language(1GL): This language consists a sequence of 0’s and 1’s to generate instruction. Since, it uses binary numbers, this type of language is directly understood by processor. So, it has higher execution speed. It is also a machine dependent language in which programmers should have detailed knowledge of the system.
Advantage:
- It is directly understood by the processor so execution speed is relatively high.
- Language translator or processor is not needed.
- They can be used to program specific purpose computer.
Disadvantage:
- It is difficult and time consuming to develop and debug program.
- It is machine dependent language. So, program developed for one system cannot be operated in another system.
- All the syntax and commands are in the form of binary numbers which is difficult to remember.
- Programmers should have detail knowledge about particular system and its architecture.
b. Assembly language(2GL): Assembly language are also an example of low-level language. In this language, instead of writing instruction in the series of 0’s and 1’s we can use mnemonics (symbolic instructions) like ADD, SUB, RST, DIV, MOD and so on. Since it is closer to machine level language, a programmer should have detailed knowledge about computer internal architecture. This language is faster in comparison to high level language. Since, this language is not directly understood by the computer, we need language translator like assembler to convert it into machine level language.
Advantage:
- It is easier to write, debug and understand programming written in assembly level language compared to machine level language.
- Program execution is higher compared to high level language,
- Since they are machine dependent, they are used to develop different device drivers.
Disadvantage:
- It is machine dependent language, i.e. program made for one processor doesn’t run in another processor.
- Use of mnemonics code makes assembly language much more complex.
- Program development and debugging is more difficult and time consuming compared to high level language.
2. High level language: This language is close to English language. High level language code is written in English like structure using mathematical notation. Since it is similar to English language, it is easier to develop and debug the program. It is machine independent language (i.e. program developed for one processor can work on another processor). Since HLL (high level language) are not directly understood by the computers, we need language processor or translator such as complier and interpreter for converting program written in high level language to machine level language. FORTAN (Formula Translator) introduced on 1956 A.D is the first high level language. Nowadays there are many high-level languages like C, C++, python, JavaScript, etc.
Advantage:
- Since it is closer to English language, program written in this language is easier to write, debug and understand.
- Since it is machine independent, program written for one processor can work in another processor.
- Programmer doesn’t have to remember large number of mnemonics and other unusual codes.
- Program development is faster and requires less effort than other language.
Disadvantage:
- Computer doesn’t understand high level language directly. So the program needs conversion before execution.
- Program execution is slower compared to low level language.
High level language can further be classified into:
a. Procedural oriented Language(3GL): This type of language is high level language which primarily focuses on procedure rather than on data. Hence, they are used to express the logic and the procedure of the program. Since it focuses only on procedure, it is complex and time consuming to write a large program. This type of language follows top to bottom approach i.e. main function is written at the bottom of the program. This type of language doesn’t pose important and powerful feature like data encapsulation, data inheritance, data extraction and so on. So, this type of language has less security compared to object-oriented language. Because of their flexibility, procedure language is able to solve verities of problem. Examples: C, FORTAN, QBasic, etc.
Advantage:
- Program development and debugging is easier compared to low level language.
- More advance and user-friendly software can be developed.
- It is also a machine independent language.
- It is used as general purpose programming.
Disadvantage:
- Language translator or processor is required to execute the program.
- Program execution is slower.
- Data security is less in comparison to other high-level language.
b. Problem/object Oriented Language(4GL): This is the advance form of high-level language which primarily focuses on data rather than procedure. It allows the user to specify what the output should be without describing all the detail (i.e. procedure) of how the data should be manipulated. This type of language follows bottom up approach. That means all main function are written at the bottom of the program whereas classes and object are described at top of the program. Since it has several powerful features such as data encapsulation, data extraction and inheritance, the data are more secure compared to procedure language. Examples: C#, C++, Java, etc.
Advantage:
- Web based application and software can be developed.
- More advance and user-friendly software can be developed.
- It is also machine independent language.
Disadvantage:
- Language translator is required to execute the program.
- Program execution is slower.
- It is difficult to develop hardware-oriented language.
c. Natural Language (5GL): Natural language uses simple statement of common communication language where we could write statements that would look like normal sentences. It is still in developing stage; computer scientists are working hard for developing such language. However, programming language like PROLOG (programming logic) is currently in use. For example: – instead of writing some unusual code, programmers would write: “who are the salesmen who has sold more than 30,000 products last month?”
Advantage:
- It will be even easier to develop and debug the program.
- It will also be machine independent language.
- More advance and user-friendly program will be made.
Disadvantage:
- Language translator is required to execute the program.
- Program execution is slower
- It is difficult to develop hardware-oriented language.
Language translator/processor:
Language translator is that system development software which helps to convert program written in assembly or high-level language (source program) into machine level language (object program). Since it is difficult and incontinent to write a program in machine level language, language developer uses several assemblies and high level language which are not directly understood by the computer. Hence, we use different types of language processor to convert and make machine understandable. There are different types of language translators.
- Assembler: These language translator/processor converts program written in assembly level language (source program) into machine understandable language (object language) Since assembly level language are closer to machine level language, the conversion taken by assembler is relatively less. It converts program at once into machine level language.
- Compiler: Those language processors which helps to convert program written in high level language (source program) into machine level program (object program). It converts whole program into machine level language at once. It is the largest method of translating a program in which debugging is complex and time consuming. Programming languages like C, C++, Java, etc. use complier
- Interpreter: This is the type of language which converts program written in high level language (source program) into machine level language (object program). It converts one statement at a time so its debugging can be easier and less time consuming. Its program execution is slower than that of compiler. Most of the new programming language use interpreter which allocate less memory space. Programs like BASIC, C#, Php, etc. use interpreter for conversion.
Difference between compiler and interpreter:
S.N. | Compiler | Interpreter |
1 | It translates the whole program into object code at a time. | It translates one line or a single statement of a program into object code at a time. |
2 | It finds out the error after compiling the complete program. | It finds out the error after translating a line of the program at a time. |
3 | The translating process is incredibly faster. | The translating process is slower. |
4 | Compiler based program is difficult to code and debug. | Interpreter based program is easy to code and debug. |
5 | It is usually a large program and requires larger memory space. | It is usually a smaller program and requires less memory space. |
6 | New programming language don’t use complier. | New programming language use interpreter. |
7 | For e.g.: C, C++, java, FORTAN etc. | For e.g.: BASIC. C#, PHP etc. |
- Syntax and Semantics:
As we know programming language helps the user to communicate with the computer. User is governing by several set of codes which instruct computer to perform some specific task. This set of codes and its structure is known as syntax. In addition, semantics is the meaning attached to individual word or symbol in programming language. For example:
In q basic:
Print” This is programming”; P
Here, Print is Semantics and whole line is Structure (syntax)
- Error (BUG):
There may be several errors inside a program which stops program from being executed. Thus, an error in a program is known as a bug. This type of error in a program may arise by not following proper rules given by the programming language due to poor problem analysis or maybe due to hardware failure. Error in the program may five ambiguous (not accepted/false) result. The process of removing error from a computer program is known as debugging. There are three types of error:
- Syntax error: the error which may arise due to not following proper rules or format given by the programming language. Every programming language have their own vocabulary, punctuation and structure. Programmers need to follow every detail while programming. This type of error can be detected by language processor such as compilers and interpreter. For e.g. In C, every statement should end with semi-colon at the end of the statement then the errors encounter is syntax error.
- Logical error: Logic refers to idea or concept used to solve a specific problem. If the problem is poorly understood than it may hamper while solving the problem. The error that is encountered due to poorly developed logic is called logical error. This type of error is not detected by language processor. For example: In order to calculate simple interest, we use the formula I =(P*T*R)/100, if we write above mentioned formula, as I=P*T*R, then the error encounter is logical error.
- Runtime error: When a program is running or executing, it is said to be runtime. Hence, the error that are encounters/found while program is being executed is known as runtime error. It is also not detected by language translator. For example: if insufficient memory space, peripheral device not turning on.
Some common terminology in programming:
- Data types: It specifies the type of data to be used in a program. Some common types of data types are:
- Numeric: It is the combination of all the positive and negative whole number including zero.
- Character: it is the possible combination of all the alphanumeric values including especial symbol.
- Variable and Constant:
- Variable: Those entities which holds either numeric or alphanumeric values and changes its value throughout the time of program execution.
- Constant: Those entities which holds either numeric or alphanumeric values but does not change its value throughout the time of program execution.
- Operands and Operators and Operations:
Let us consider as;
S=A+B
Where S, A, B are operands
+, = are operands
S=A+B denotes sum of two operands A, B which is Operation
Types of operators:
It is a special symbol which helps to make operation successful i.e. it helps to make some specific operation.
Commonly used operators are:
- Arithmetic operators: +, -, /, *
- Relative operators: <, >, >=, <=, =
- Logical operators: AND, OR, NOT
Program Design Tool
There are several program designs tools that are available. Some of the commonly used program design tool are algorithm, flowchart, pseudocode.
Algorithm:
The step by step procedure or sequential steps for solving a specific problem is known as algorithm. Algorithm are written in simple English language and are not even close to any programming language.
Rules for writing algorithm:
- Algorithm should execute output after a finite step.
- Algorithm should not depend upon any programming language.
- Algorithm should terminate after finite steps.
Examples:
- Write an algorithm to calculate simple interest.
Step 1: Start
Step 2: Read the value of P.T.R
Step 3: Calculate simple interest by using i=(P*T*R)/100
Step 4: Display simple interest(i)
Step 5: Stop
2. Write an algorithm to check greatest number among two number.
Step 1: Start
Step 2: Read any two-number a, b
Step 3: check if (a>b)
If yes, Display the greatest number is “a” and go to step 4
If no, Display the greatest number is “b” and go to step 4
Step 4: Stop
Flowchart:
It is a diagrammatic or pictorial representation of steps involve in algorithm for solving a particular problem is known as flowchart. It uses several geometrical shapes, symbol for representing different action involve in problem solving. There are two types of flowchart:
a. Program Flowchart: It is a type of flowchart which focuses on a specific problem. This type of flowchart portage only a single task (logic) at a time.
Symbols used in flowchart:
Examples:
- Draw flowchart to calculate simple interest.
- Draw flowchart to find greatest number among two numbers.
b. System Flowchart: It is also a type of flowchart that shows the logical flow of a program and its collection. It shows the overview of the data flow and sequence of operation in a system.
Symbols used in system flowchart:
Example of System Flowchart
What is c programming language?
It is a High Level Programming Language, developed by Dennis Ritchie at AT & T’s Bell Laboratories of USA, in 1970. It is a very powerful programming language. It is used for both system programming and application programming. So, often known as Middle Level Programming Language, also. It means, it supports or works as the low level language and high level language, both.
What are the features of c language?
The features of c language are:
- It supports high level and level programming both, so known as mid level programming language.
- It is mostly used for System programming but very popular for Application programming, too.
- The program development is faster and more efficient.
- It has very powerful tools and keywords.
- It uses its own text editor.
- It has its own compiler.
- It supports structured programming.
- It is portable easily.
- It has very powerful library functions set.
- Flexible in programming.
What are the advantages and disadvantages of c language?
The advantages are:
- Suitable for system programming.
- It is easier to interact with hardware.
- Easy to learn.
- Program code is secure.
- It is compact and efficient.
The disadvantages are:
- It does not contain runtime checking.
- There is no strict data type checking.
- As the program extends, the debugging becomes more complex because it uses compiler instead of interpreter for the compilation.
- Semi-colon requires for each statement.
Define the following terms:
a) Editor: This is the area, in which we type the program. C language has its own text editor but we can use any other text editor program also.
b) Pre-processor: This is the collection of complex codes to instruct the machine to understand the certain keywords. It is written with preceding # symbol. For example: #include, in this example, include pre-processor with the hash symbol, uses the instruction or complex codes from the file ‘stdio.h’, which is already stored by c language. These .h files are called header files. So, include pre-processor is used for using the header files.
c) Compiler: It is a type of software to change the source code of high level programming language into machine readable form called object code.
d) Linker: It is also a type of software, which links the various library files with the object codes and creates an executable file with .exe extension. Then, exe file can run independently.
FUNDAMENTAL OF C
Define the character set. Also define the character set used in c language.
The set of alphabets, digits, white characters and other symbols used in any programming language is called a character set. The character set used in c are:
Alphabet – A, B, C, ……..Z and a, b, c, ….z
Digits – 0, 1, 2, …………9
Special Symbols – ~ ‘ ! @ % ^ & * ( ) – _ + = | \ { } [] : ; “ ‘ <> , . ? /
Define comment. Comment is a text or set of other characters, which is not compiled or executed from the compiler. It is written in the program to give required information to other programmers and the developers themselves. There are two types of comment writing methods:
a. Single line comment: It is written with the // symbol.
Eg. // This is my first program.
b. Multi-line comment: It is written with /*………….*/ symbols.
Eg. /* This is
multi line
comment style */
Define C Tokens.
The set of identifiers, keywords, constants, variables and operators is known as C Tokens. It remains as a single unit and compiler does not break in the time of compilation.
Define the following terms:
a) Identifiers: Identifiers are names for entities in a C program, such as variables, arrays, functions, structures, unions and labels.
b) Keyword: Keyword is a reserved word that is already stored by the c language developer. The reserved word cannot be used as the identifiers. There 32 Keywords in C according to the ANSI (American National Standard Institute) in c language. They are: void, printf, scanf, if, else, while, getch, do, for, break, continue etc
c) Data types in c: The term Data Types in any language refers to the types of data which can be used in the program execution for entering and manipulating as the values. In the same way, the data types in c also refer to the data types, which can be used as the values. Basically it is of four types. They are:
- int : It represents the integer type data. It means the numbers without the decimal points. It consumes 2 bytes memory. The derived data types from int are short int and long int.
- float : It means the real numbers with the decimal points. It consumes 4 Bytes memory space. It can also be signed and unsigned. Derived data types of it are double and long double.
- char : It is used for a single character (alphabet or symbol) like ‘A’, ‘f’, ‘@’ etc. It requires 1 byte memory. It can also be signed or unsigned.
- void : void means no value. It means null value. It is used for returning null value to the modules.
d) Constants
e) Variables
f) Statements : The set of keywords, identifiers, operators, variables and constants ended with the semicolon or a curly bracket is called statement. It is of two types:Simple
- Statement : The statement written in a single line and ended with the semicolon is simple statement. Eg. printf (“My program”);
- Compound Statement: The group of simple statements grouped by the curly bracket open and close is the compound statement. Eg.
if (n>0)
{
a=b+c;
x=x*x;
printf(“%d %d”, a,x);
}
g) Escape Sequences: The symbol \ or ‘ is supposed as the Escape character. It means, the compiler of c programming language understands this character and the text after this to take as a special case. And the set of this symbol and the character behind it is known as the Escape Sequence. Some common escape sequences are:
Character | Escape |
New Line | \n |
Horizontal tab | \t |
Null character | \0 |
Quotation mark | \” |
Apostrophe | \’ |
Backslash (\) | \\ |
h) Operators: (imp)The symbols, which are used to operate on the operands for the mathematical and logical calculations are known as operators. C programming language has a rich set of built-in operators. Operator that requires two operands are binary (dyadic) operators, operators that require one operand is unary (monadic) and the operator that requires three operands is ternary operator. Eg. a+b, here + is an operator.
Types of operators:
- Arithmetic Operator
- Relational Operator
- Equality Operator
- Logical Operator
- Assignment Operator
- Increment/Decrement Operator
- Conditional Operator (Ternary Operator)
- Bitwise Operator
- Special Operator
i) Library Functions: Functions are the independent sections or the block of statements given a specific name and they can be used by any program according to the requirements. They are developed to perform a certain task. They are of two types:
a) Library Functions: These are the ready-made formula-like functions stored in c language library. They can be used in any program. abs(), printf (), scanf (), clrscr(), getch(), strlen(), sqrt(), etc. are some examples of Library functions.
b) User defined function: The functions developed by the users in their own program are called User-defined functions.
INPUT/OUTPUT (I/O) functions
1. printf() : It is a formatted output function.
Eg. printf(“My School”);
2. scanf() : It is to enter any value to the program.
Eg. scanf(“%d”, &x);
Program Example
a) Write a c program to enter any two numbers and print the sum of them.
# include
void main()
{
int a, b, s;
clrscr();
printf(“Enter First Number”);
scanf(“%d”, &a);
printf(“Enter Second Number”);
scanf(“%d”, &b);
s = a + b;
printf (“The sum is %d”, s);
getch();
}
b) Write a c program to calculate the area of a rectangle, where the length is 20 and breadth is 15.
# include
void main( )
{
int l = 20, b = 15;
int a;
clrscr();
a = l * b;
printf (“The area is %d”, a);
getch();
}
c) WAP to calculate the area of a rectangle in c. [Hints: a = l x b]
# include
void main()
{
int l, b, a;
printf (“Enter Length: ”);
scanf (“%d”, &l);
printf (“Enter Breadth: “);
scanf (“%d”, &b);
a = l * b;
printf (“The area is %d”, a);
getch();
}
d) Write a program to enter length and breadth of a rectangle and calculate the perimeter. [p = 2 (l + b) ]
# include
void main ()
{
int l, b, p;
printf (“Enter Length :”);
scanf (“%d”, &l);
printf (“Enter Breadth :”);
scanf (“%d”, &b);
p = 2 * (l + b);
printf (“The perimeter is : %d”, p);
getch();
}
e) WAP to calculate the area of a triangle .
# include
void main()
{
int b, h, a;
printf (“Enter base and height”);
scanf (“%d %d”, &b, &h);
a = ½ * b * h;
printf (“The area is %d”, a);
getch();
}
f) WAP to enter the length of any one side of a square and calculate the area and perimeter in c language.
# include
void main ()
{
int l, a, p;
clrscr ();
printf (“Enter length”);
scanf (“%d”, &l);
a = l * l;
p = 4 * l;
printf (“The area is %d and the Perimeter is %d”, a, p);
getch();
}
g) WAP to calculate the volume of a box.[v=l*b*h] (Do yourself)
j) WAP to enter the radius of a circle and print the circumference of it. [c = 2 pi r] (Do yourself)
CONTROL STRUCTURE IN C (important)
Normally, the program execution flows top to the bottom lines of the programs. It means program executes one line after another. But sometime we need to execute other part of the programs or we need to divert the program flow from its normal execution. In such a case, we need some program statements, which are known as Control Structures. They are of three Types of control structure : a. sequence b.selection and c. looping
A) Sequence: Program generally flows from top left top right bottom.
WAP to enter the length, breadth and height of a box and calculate the total surface area (TSA). [TSA = 2 * (L*B + B*H + L*H)]
# include <stdio.h>
void main ()
{
int l, b, h, tsa;
clrscr();
printf (“Enter length, breadth and height”);
scanf (“%d %d %d”, &l, &b, &h);
tsa = 2 * (L*B + B*H + L*H);
printf (“Total surface area is %d”, tsa);
getch ();
}
WAP to enter the radius of a circle and calculate the area . [a = pi r 2]
# include <stdio.h>
void main ()
{
float r, a;
printf (“Enter radius”);
scanf (“%f”, &r);
a = 22/7 * r * r;
printf (“The area is %f”, a);
getch();
}
j) WAP to enter the radius of a circle and print the circumference of it. [c = 2 pi r]
B) Selection/branching/condition: These type of control structure changes the flow of program execution with or with out conditoon.
B.1) Conditional Statements: They break the program flow if the condition is matching. Eg. if, if….else and if…..else….if
if condition
This condition is used for a single condition and single block of statements.
Syntax:
if (condition)
{
Block of statements'
}
Example:
1. WAP to enter the marks of English and print “Pass” if it is 40 or more.
# include <stdio.h>
void main ( )
{
float e;
printf (“Enter English Marks \n”);
scanf (“%f”, &e);
if (e >= 40)
{
Printf (“Pass”);
}
getch ( );
}
Note: The above program states only about pass. If the marks is less than 40, it displays blank.
2. WAP to enter the age of a person and print “He can vote”, if the age is 18 or above.
# include
void main ( )
{
float a;
printf (“Enter age \n”);
scanf (“%f”, &a);
if (a >= 18)
{
Printf (“You can vote”);
}
getch ( );
}
If….else condition
This condition is used for a double conditions and double blocks of statements.
Syntax:
if (condition)
{
Block of statements'
}
else
{
Block of statements'
}
Example:
1. WAP to enter the marks of English and print “Pass” if it is 40 or more, otherwise “Fail”.
# include
void main ( )
{
float e;
printf (“Enter English Marks \n”);
scanf (“%f”, &e);
if (e >= 40)
{
printf (“Pass”);
}
else
{
printf (“Pass”);
}
getch ( );
}
Example 2: WAP to enter the age of a person and print “He can vote” if the age is 18 or above, otherwise print “He cannot vote”.
# include
void main ( )
{
float e;
printf (“Enter age\n”);
scanf (“%f”, &a);
if (a >= 18)
{
printf (“You can vote”);
}
else
{
printf (“You cant vote”);
}
getch ( );
}
Example 3: WAP to check whether given numvber if odd or even
# include
void main ( )
{
int n;
printf (“Enter number\n”);
scanf (“%d”, &n);
if (n%2 == 0)
{
printf (“%d is even”,n);
}
else
{
printf (“%d is odd”,n);
}
getch ( );
}
Example 3: WAP to find greatest among two number.
# include
void main ( )
{
int a,b;
printf (“Enter two number\n”);
scanf (“%d %d”, &a,&b);
if (a>b)
{
printf (“%d is greatest”,a);
}
else
{
printf (“%d is greatest”,b);
}
getch ( );
}
else if statement: This statement is used for the multiple conditions and multiple blocks of statements.
Syntax:
if (condition 1)
{
Statement Block 1;
}
else if (condition 2)
{
Statement Block 2;
}
..
..
else
{
default staement
}
Example 1: WAP to enter a number and print “Positive” if it is greater than 0, print “Negative” if it is less than 0, otherwise print “Zero”.
# include
void main ( )
{
int n;
printf("Enter number");
scanf("%d",&n);
if (n > 0 )
{
printf (“Positive”);
}
else if (n < 0 )
{
printf (“Negative”);
}
else
{
printf (“Zero”);
}
getch ( );
}
Example 2: WAP to enter the percentage and print the division
# include
void main ()
{
float p;
clrscr ( );
printf (“Enter percentage:”);
scanf (“%f”, &p);
if (p > = 80 && p<=100)
printf (“Distinction”);
else if (p>=60 && p<80)
printf (“First”);
else if (p>=50 && p<60)
printf (“Second”);
else if ( p>=40 && p<50)
printf (“Third”);
else
printf("fail");
getch ();
}
Example 3: WAP to enter 3 number and print gratest number
# include
void main ( )
{
int a,b,c;
printf("Enter number");
scanf("%d %d %d",&a,&b,&c);
if (a>b && a>c)
{
printf (“%d is greatest”,a);
}
else if (b>a && b>c)
{
printf (“%d is greatest”,b);
}
else
{
printf (“%d is greatest”,c);
}
getch ( );
}
B.2) Unconditional Statements: They break the program flow with out any condition. Eg. goto statement
Syntax
label:
goto label;
OR
goto label;
label:
Program example of goto [This program allows user to only enter value under 100]
# include
void main ()
{
float p;
clrscr ( );
label:
printf (“Enter percentage:”);
scanf (“%f”, &p);
if (p > 100)
{
printf (“Invalid input”);
goto label;
}
getch();
}
C) Looping: Loop is the process of repeating any block of statements up to the given number of times or until the given condition is not over.
There are three types of Loop: 1. for loop 2. while loop and 3. do while loop
FOR… loop: Syntax of for loop
for (initialization; condition; increment/decrement)
{
Statements (s);
}
Examples:
a) 1, 2, 3, 4, ………….100.
#include
int main()
{
int i;
for (i=1;i<=100;i++)
{
printf("%d\n",i);
}
return 0;
}
b) 1, 3, 5, 7, ……………..99.
c) 2, 4, 6, 8, ………………100.
d) 5, 10, 15, ………………….50.
#include
int main()
{
int i,s;
for (i=1;i<=10;i++)
{
s=5*i;
printf("%d\n",s);
}
return 0;
}
WAP to calculate sum of n-natural number.
#include
int main()
{
int n,i,s=0;
printf("Enter any number\t");
scanf("%ld",&n);
for (i=1;i<=n;i++)
{
s=s+i;
}
printf("Sum is %d\n",s);
return 0;
}
WAP to calculate product of n-natural number. (Factorial of a given number.
#include
int main()
{
int n,i,p=1;
printf("Enter any number\t");
scanf("%d",&n);
for (i=1;i<=n;i++)
{
p=p*i;
}
printf(“Product is %d\n”,p);
return 0;
}
WAP to generate fibonacci series. [ 0,1,1,2,3,5,8 …..10th term]
#include
int main()
{
int i,a=0,b=1,c;
printf(“%d%d””,a,b);
for (i=1;i<=10;i++)
{
c=a+b;
printf(“%d”,c);
a=b;
b=c;
}
return 0;
}
WAP to generate 1 2 4 7 11 ...............10th term
#include
int main()
{
int i,a=1,g=1;
for (i=1;i<=10;i++)
{
printf(“%d”,a);
a=a+g;
g=g+1;
}
return 0;
}
WAP to generate 1 2 5 10 17 ...............10th term
#include
int main()
{
int i,a=1,g=1;
for (i=1;i<=10;i++)
{
printf(“%d”,a);
a=a+g;
g=g+2;
}
return 0;
}
WAP to generate 3 12 27 48 ................10th term
#include
int main()
{
int a,i;
for (i=1;i<=10;i++)
{
a=3*I*I;
printf(“%d”,a);
}
return 0;
WHILE Loop (Entry Control loop)
Syntax:
while(condtion)
{
Block of statements;
}
WAP to calculate sum of n-natural number.
#include
int main()
{
int n,s=0,i=1;
printf("Enter any number\t");
scanf("%d",&n);
while (i<=n)
{
s = s+i;
i=i+1;
}
printf("Sum of digits is %ld\n",s);
return 0;
}
WAP to calculate product of digits of a given number.
#include
int main()
{
int n,p=1,i=1;
printf("Enter any number\t");
scanf("%d",&n);
while (i<=n)
{
p = p*i;
i=i+1;
}
printf(“Product of digits is %d\n”,p);
return 0;
}
WAP to generate 1 2 4 7 11 ...............10th term
#include
int main()
{
int i=1,a=1,g=1;
while (i<=10)
{
printf(“%d”,a);
a=a+g;
g=g+1;
i=i+1;
}
return 0;
}
WAP to calculate sum of digits of a given number.
#include
int main()
{
int n,s=0,r;
printf("Enter any number\t");
scanf("%d",&n);
while (n!=0)
{
r = n%10;
s = s+r;
n = n/10;
}
printf("Sum of digits is %d\n",s);
return 0;
}
WAP to calculate product of digits of a given number.
#include
int main()
{
int n,p=1,r;
printf("Enter any number\t");
scanf("%d",&n);
while (n!=0)
{
r = n%10;
p = p*r;
n = n/10;
}
printf(“Product of digits is %d\n”,p);
return 0;
}
WAP to reverse a given number.
#include
int main()
{
int n,p=0,r;
printf("Enter any number\t");
scanf("%d",&n);
while (n!=0)
{
r = n%10;
p = p*10+r;
n = n/10;
}
printf(“Reverse is %d\n”,p);
return 0;
}
WAP to check whether given number is palindrome or not.
#include
int main()
{
int n,p=0,r,z;
printf("Enter any number\t");
scanf("%d",&n);
z=n;
while (n!=0)
{
r = n%10;
p = p*10+r;
n = n/10;
}
if (z==p)
{
printf(“%d is palindrome \n”,z);
}
else
{
printf(“%d is not palindrome \n”,z);
}
return 0;
}
WAP to check whether given number is armstrong or not. [153 is Armstrong]
#include
int main()
{
int n,s=0,r,z;
printf("Enter any number\t");
scanf("%d",&n);
z=n;
while (n!=0)
{
r = n%10;
s = s+pow(r,3);
n = n/10;
}
if (z==s)
{
printf(“%d is armstrong \n”,z);
}
else
{
printf(“%d is not armstrong \n”,z);
}
return 0;
}
DO Loop
Syntax:
do
{
Block of statements;
}while(condition);
WAP to calculate sum of n-natural number.
#include
int main()
{
int n,s=0,i=1;
printf("Enter any number\t");
scanf("%d",&n);
do
{
s = s+i;
i=i+1;
}while (i<=n);
printf("Sum of digits is %ld\n",s);
return 0;
}
Array
An array is a collection of variables of same type that are represented by a common name i.e. array is the collection of homogenous data type (Contains similar datas). If we declare array as int then it must only contain all integer data and same for floats and char. Each array element is specified by array name followed by index or subscript enclosed in square bracket (eg, a[10]). Hence, it is also called indexed or subscripted variables. In an array index of array represent the size of an array.
Let us consider, int age[5]
This mean array name is age which is capable of storing 5 different data under integer datatype.
age[0] = 15
age[1] = 25
age[2] = 13
age[3] = 22
age[4] = 17
Types of array
Depending upon the number of subscript or index number array are of 2 types:
- 1-Dimension
- N-Dimension (Multi-dimension)
1-Dimension:
This type of array has only one subscript.
Declaration:
Data_type array_name[size]
Example:
int salary[100]
Program example.
Q1. WAP to input 10 different number and print them all.
#include
int main()
{
int a[10], i;
printf ("Enter any 10 number");
for(i=0;i<10;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<10;i++)
{
printf(“%d”,&a[i]);
}
return 0;
}
Q2. WAP to input salary of 1000 employees and calculate average salary.
#include
int main()
{
int sal[1000], i, s=0;
float av;
printf ("Enter any 10 number");
for(i=0;i<1000;i++)
{
scanf(“%d”,&sal[i]);
}
for(i=0;i<1000;i++)
{
s=s+sal[i];
}
av = s/1000;
printf(“Average salary of 1000 employee is %f”, av);
return 0;
}
Q3. WAP to input salary of 1000 employees and count total number of employee getting salary between 30000 and 50000.
#include
int main()
{
int sal[1000], i, c=0;
for(i=0;i<1000;i++)
{
scanf(“%d”,&sal[i]);
}
for(i=0;i<1000;i++)
{
if(sal[i]>=30000 && sal[i]>=50000)
{
c=c+1;
}
}
printf(“Total number of employee is %d”, c);
return 0;
}
Q5. WAP to input 10 different number and find the greatest among them.
#include
int main()
{
int a[10], i, g;
printf ("Enter any 10 number");
for(i=0;i<10;i++)
{
scanf("%d",&a[i]);
}
g = a[0];
for (i=0;i<10;i++)
{
if (g>a[i])
{
g=a[i];
}
}
printf("Greatest number is %d\n",g);
return 0;
}
Q6. WAP to input 10 different number and sort the in ascending order.
#include
int main()
{
int a[10], i, j, temp;
printf ("Enter any 10 number");
for(i=0;i<10;i++)
{
scanf("%d",&a[i]);
}
for (i=0;i<10;i++)
{
for (j=0;j<10;j++)
{
If (a[j]>a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
printf(“Ascending order is”);
for (i=0;i<10;i++)
{
Printf(“%d \t”,a[i]);
}
return 0;
}
Q3. WAP to input salary of n-employees and count total number of employee getting salary between 30000 and 50000.
#include
int main()
{
int sal[1000], i, c=0, n;
printf("Enter the number of employees");
scanf("%d",&n);
for(i=0;i=30000 && sal[i]>=50000)
{
c=c+1;
}
}
printf(“Total number of employee is %d”, c);
return 0;
}
N-Dimension (Multidimension array)
This type of array has more than one subscript.
Declaration:
Data_type array_name[size][size]
Example:
int n[3][3]
Program example
Q1. WAP to input 3x3 matrix data and display the data of it.
#include
int main()
{ int a[3][3],i,j;
printf("Enter 9 number");
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
}
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
return 0;
}
Q2. WAP to input 3x3 matrix and perform matrix addition
#include
int main()
{ int a[3][3], b[3][3], c[3][3],i ,j;
printf("Enter 9 number");
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
scanf(“%d%d”,&a[i][j],&b[i][j]);
}
}
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
c[i][j] = a[i][j] + b[i][j];
}
printf("\n");
}
printf(“Added matrix is”);
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
printf(“%d \t”,c[i][j]);
}
printf(“\n”);
}
return 0;
}
Q2. WAP to input 3x3 matrix and perform matrix multiplication
#include
int main()
{ int a[3][3], b[3][3], p[3][3],i ,j, k;
printf("Enter 9 number");
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
scanf(“%d%d”,&a[i][j],b[I][j]);
}
}
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
p[i][j] = 0;
for(k=0;k<3;k++)
{
p[i][j] = p[i][j] + a[i][k]*b[k][j];
}
}
}
printf(“Multiplied matrix is”);
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
printf(“%d \t”,p[i][j]);
}
printf(“\n”);
}
return 0;
}
String: String is a group of characters that can be represented only by character array. To represent a character/string we use ‘char’ datatype.
i.e. char a, char a=‘x’
Where, char is data type and a is string variable and ‘x’ is a character.
Similarly, we can initialize string as one-dimension character array as:
Char a[5] = “hello” which is stored in array as follow
a[0] | a[1] | a[2] | a[3] | a[4] | a[5] |
‘h’ | ‘e’ | ‘l’ | ‘l’ | ‘o’ | \0 |
we can initialize array of string as two-dimension array as:
Char a[2][5] = {“ball” , “cat” , “apple”}, which is stored in array as follow
a[2][5] | a[0] | a[1] | a[2] | a[3] | a[4] | a[5] |
a[0] | ‘b’ | ‘a’ | ‘l’ | ‘l’ | \0 | |
a[1] | ‘c’ | ‘a’ | ’t’ | \0 | ||
a[2] | ‘a’ | ‘p’ | ‘p’ | ‘l’ | ‘e’ | \0 |
String handling function [Library function / Inbuilt function] V.imp
As we know, functions are the self contained program that performs certain task. Similarly the function which are given by C-library itself or inbuilt in C-library are known as library or inbuilt-function. String handling function or string function are the library functions which are used to manipulate strings in our program for simplicity and convenience. This inbuilt functions are defined under the header file ’string.h’ . In C we have several string handling functions which are as follows:
[Note: don’t miss ’string.h’ header file]
1) strlen( )
Function: This function returns total number of characters in a given string.
Syntax: strlen(string);
Program example:
#include
#include
int main()
{
char a[10];
int l;
printf("Enter any string");
scanf("%s",a);
l=strlen(a);
printf("The length is %d",l);
return 0;
}
2) strrev( )
Function: This function returns reverse of given string i.e. if we enter ‘ball’ it will return ‘llab’
Syntax: strrev(string);
Program example:
#include
#include
int main()
{
char a[10];
printf("Enter any string");
scanf("%s",a);
strrev(a);
printf("The reverse is %s”,a);
return 0;
}
3) strlwr( )
Function: This function returns given string in lower case i.e. small letters.
Syntax: strlwr(string);
Program example:
#include
#include
int main()
{
char a[10];
printf("Enter any string");
scanf("%s",a);
strlwr(a);
printf("The lower case is %s”,a);
return 0;
}
4) strupr( )
Function: This function returns given string in upper case i.e. capital letters.
Syntax: strupr(string);
Program example:
#include
#include
int main()
{
char a[10];
printf("Enter any string");
scanf("%s",a);
strupr(a);
printf("The upper case is %s”,a);
return 0;
}
5) strcpy( )
Function: This function copies one string to another i.e. source_string to destination_string
Syntax: strcpy(destination_string,source_string);
Program example:
#include
#include
int main()
{
char a[10],b[10];
printf("Enter any string");
scanf("%s",a);
strcpy(b,a);
printf("The copied string is %s”,b);
return 0;
}
6) strcat( )
Function: This function adds two strings into one.The process of adding strings is known as string concatenation.
Syntax: strcat(string1,string2);
Program example:
#include
#include
int main()
{
char a[10],b[10];
printf("Enter first string");
scanf("%s",a);
printf("Enter second string");
scanf(“%s”,b);
strcat(a,b);
printf("The added string is %s”,a);
return 0;
}
7) strcmp( )
Function: This function compare two strings and return 0 if both string are equal else return -1/1 if not equal.
Syntax: strcmp(string1,string2);
Program example:
#include
#include
int main()
{
char a[10],b[10];
Int x;
printf("Enter first string");
scanf("%s",a);
printf("Enter second string");
scanf(“%s”,b);
x = strcmp(a,b);
printf("The compared value is %d”,x);
return 0;
}
Some important program using string functions
WAP to check whether the given string is palindrome or not [MADAM is palindrome]
#include
#include
int main()
{ char a[10],b[10];
printf("Enter string");
scanf("%s",a);
strcpy(b,a)
strrev(a);
if(strcmp(a,b)==0)
{
printf("%s is palindrome”,b);
}
else
{
printf("%s is not palindrome”,b);
}
return 0;
}