Lohana Career
Development Center
: Managed by :
Shri Rajkot Lohana Mahajan
“Kesariya Wadi” Nr. Sankirtan temple.
Kalawad Road Rajkot-360 005 “MANGAL-BHUVAN”
Lohana mahajan wadi Sanganava chowk Rajkot-360 001
STUDY MATERIALS
C-LANGUAGE
PREPAIRED BY :HALANI KINJAL M.
Introduction: ‐
What is Computer? The Computer is an Electronic machine. Which takes data from the user [INPUT]. Process on it in pre‐defined sequential way [PROCESS] And send back data to the user [OUTPUT] The concept of Hardware and Software. Our computer system can be divided into 2 parts. 1> Hardware 2> Software 1> Hardware: ‐ All the physical part of the computer are known as “Hardware”. OR We can say that all the parts of the computer that have physical existence are known as hardware. 2> Software: ‐ All the Logical parts of the computer are known as “Software”. OR We can say that all the parts of the computer that have logical existence are known as software. The software can be divided into 2 parts:A) Application Software B) System Software
A) Application software: ‐
The Application software can be used to perform a particular task.
For e.g.: ‐Word, Excel, Power Point etc. B) System software: ‐
The system software can handle your whole computer system that’s why it is also known as an “Operating system”.
For e.g.: ‐Dos, win 98, win xp, Unix etc.
The concept of Language: ‐
The Computer language can be divided into 2 categories…
1) Low level language 2) High level language 1) Low level language: ‐
The low level language is made up of 0s and 1s. And require less compile time but there are so many chances of errors while developing programs.
2) High level language: ‐
The High‐level language is just like an English language. And require more compile time but there are less chances of errors while developing programs. The High‐level language Programs require the conversion programs.
Compiler Interpreter
Compiler checks your whole program at a time and list out all the errors of your program
Interpreter checks one line of your program at a time and indicate error at that line. It you not
solving the error of that line the interpreter can’t move on next line.
The Concept of ASCII Value: ‐
While converting your program into machine level language One Intermediate code is generated to make conversion easily. This code is known as ASCII CODE/ASCII VALUE.
In computer total there are 256 ASCII VALUES. ASCII: ‐ American Standard Code For Information Interchange
The Concept of Variable: ‐
The Variable is the name given to the memory location. During the Execution of program the value of variable may be changed or altered.
Ex.: ‐ 3a+5b …… In this equation a and b are variables.
The Concept of Constant: ‐
The Values, which are stored inside the variables, are known as Constants. During the execution of program the constant remains fixed.
Flow Chart: -
We all are know that to represent any thing the “Graphical method” is the best way. The Graphical presentation tent to provide the information to the viewer.short, the logic techniques of solving problems are known as “Flow Chart”. • There are several symbols, which are used to draw flowcharts. Symbols are used in flowchart: 1> Terminator/Oval: This symbol is used to represent the starting and ending point of “Flow Chart”. This symbol may contain the words like Start, Begin, Stop, End Etc. 2> Rectangle: This symbol is used to represent Process associated with the problem. This symbol is also used to declare the variables. 3> Input/Output:
This symbol is used to represent All Inputs and Outputs, which are associated with the flowcharts.
4> Diamond:
This symbol is used to represent the conditions associated with the flowcharts. This symbol always contains the conditions or expressions. 5> Flow Lines: The flow lines are used to indicate the control flow of the flow chart. Generally the flow of control may be top to bottom or left to right.
6> Connector:
This symbol is used to connect the multiway flow of the control, and direct the control to the particular point. Let see an example of flow chart: ☺ Draw a flow chart to print a simple message. Start Print
☺ Draw a flow chart to add two numbers.
Algorithm
Algorithms are developed on the basis of Flowcharts. Algorithms are just the textual
presentation of the flowchart. In short, the step by step representation of any problem is know as algorithms. Let see an example….
Start A,b,c Numeric Input a Input b C=a+b Print c Start
☺ An Algorithm to add two numbers… Step: 1 Begin
Step: 2 Declare the variable a,b,c Step: 3 Input the value of a Step: 4 Input the value of b
Step: 5 add the value of a and b and assign the ans in the variable c Step: 6 print the value of c
Step: 7 End
An example of conditional flow chart and example….
☺ The flowchart of checking whether the number is odd or even…
Start No Numeric Input No Is No%2==0 No. is EVEN
Off page connector
Introduction of C: ‐
We all know that c is the Programming language. But the brief explanation about the C is as given below.History of C: ‐
At the time of 1960’s the need of programming language was raised for almost specific purpose.
For eg. COBOL was used for commercial purpose.
And FORTRAN was used for Engineering and Scientific Purpose etc..
There are some limitations in these types of languages.
To reduce these limitations, a new language called ALGOL was developed and again to reduce the limitations of ALGOL the language called Combine Programming Language (CPL) was developed by Cambridge University. However CPL was hard to learn and difficult to implement, so it was also turned out.
Martin Richards at Cambridge University developed basic Combined Programming Language (BCPL) by adding good features in the CPL. But Unfortunately this language was also turned out because of less powerful.
At the same time Ken Thompson was developed the language called ‐> B at AT & T’s Bell labs. Ritchie inherited the features of language called B and BCPL and
added some more features of his own and developed a new language called C. So, In Nutshell…… C is the Middle level programming language. Developed By Dennis Rithie. In the year 1972. At the place called AT & T’s Bell labs, in USA.
Note: C have both a relatively good programming efficiency and relatively good machine efficiency. that’s why it is termed as “Middle Level Language”.
Variables: ‐
A variable is the name given to the memory location. During the execution of program the values of variables may be changed/altered. We all know that we can’t access the RAM locations directly. So, what we can do for storing our data? So, C supports the concepts of Variable…There are some rules which must be follow while defining variable. Rules for Defining Variable 1) The variable name must begin with alphabets. 2) The variable name should be meaningful. That means the variable should clearly indicate the purpose. 3) No special symbols rather than underscore (_) is allowed. 4) The variable name must not be a keyword. 5) No commas or blanks are allowed while defining a variable.
Constants: ‐
Constants are the fixed values, which are stored inside the variables. During the execution of program the constants will remains fixed. C Supports various types of constant, which are as given below. Constants Numeric constant Character Constant Integer Real Single Char String Constant Constant Constant Constant 1) Numeric constant: ‐ As it’s name suggests the numeric constants are made up of digits. There are 2 types of numeric constants as given below. A) Integer constants: ‐ There are some rules for defining integer constants. Rules: 1) An Integer constant must have at least one digit. 2) It must not have a decimal point. 3) It could be either positive or negative. 4) If no sign precedes, an integer constants assumed be positive. 5) No commas or blanks are allowed within an integer constant. 6) Example: ‐ 436,45 10
B) Real constants: ‐ There are some rules for defining a real constant. 1) A Real constant must have at least on digit. 2) It must have a decimal point. 3) It could be either positive or negative. 4) If no sign proceeds, an integer constants assumed be positive. 5) No commas or blanks are allowed within an integer constant. 6) Example: ‐ 134.98, 235.67 2) Character constant: ‐ As it’s name suggests the character constant always contains one character or no. Of characters. There are 2 types of character constants. A) Single character constant: ‐ There are some rules for defining single character constants. They are as given below. Rules: 1) A character constant is either a single alpha bate, a single digit or a single special symbol enclosed within a single inverted commas. 2) Example: ‐ ‘A’,’ ‘,’*’ B) String constants: ‐
The rules of defining a string constants are as given below. Rules:
1) The string constants are always enclosed within double inverted commas. The string constants are just
combination of characters, digits, and special symbols. 2) Example: - “Wel come”,” Hello”
Operators: -
Operators are just the symbol that can perform manipulations on the data. C has rich set of operators. There are several types of operators, they are as given below.
1) Arithmetic operators: -
Arithmetic operators are used to perform arithmetic operations on data. The arithmetic operators are as given below.
+, -, *, /, %
They are used to perform the basic operations like addition, subtraction, multiplication, division, and modulus.
2) Assignment operators: -
Assignment operators are used to assign a value to the variables. “=” Sign is used to perform an assignment operation.
Arithmetic assignment operators are also used in combination to simplify the use of both operators. The combinations of both operators are known as “Arithmetic Assignment Operators” or “Short Hand Operators”. Given below are the arithmetic assignment operators, which are most commonly used.
+=, -=, *=, /=, %= 3) Logical operators: -
Logical operators are used to combine to or more expressions. In order to combine two or more the one relational operator, the logical operators are used.
There are 3 logical operators as given below: AND (&&)
OR (||) NOT (!)
4) Unary operators: -
The unary operators can operand one operand only at a time. They are just used to increase or decrease the value of operand. They are always used with integer variable but cannot be used with float variables. They are listed below:
Increment (++) Decrement (--)
They are increase or decrease the value of variable by 1,which is by default.
5) Comparison operators: -
The comparison operators are also known as “Relational operators”. Because they are used to show the relationship between 2 variables and variables and constants. They evaluate to either true or false. Given below are the comparison operators.
>=, <=, ==, <, >, ! =
Data types:
The predefined identification of any variable is known as “Data type”. The data type of any variable tells that what kind of values will be stored inside the variable. C has rich set of data types. Basically there are 4 data types, but all data types has some modifiers which helpful to extend the functionality of data types.
The data types supported by C are as given below.
Data Types
Data Type Keyword Bytes Range
Integer Int 2 -32768 to 32767
Float Float 4 3.4e-38 to
3.4e+38
Character Char 1 -128 to 127
All the data types have some modifiers which helpful to extend the meaning & facility of the data type. The modifiers, along with their memory space and range are as given below:
Data types along with their modifiers
Type Bytes Range Char or signed
char
1 -128 to 127 Unsigned char 1 0 to 255 Int or signed int 2 -32768 to 32767
Unsigned int 2 0 to 65535 Short int or
signed short int
1 -128 to 127 Unsigned short
int
1 0 to 255
Long int or signed long int
4 -2147483648 to
2147483647 Unsigned long int 4 0 to
4,294,483,647
Float 4 3.4e-38 to
3.4e+38
Double 64 1.7e-308 to
1.7e+308
Long double 10 3.4e-4932 to 1.1e+4932
Key words:
-The keywords are the words whose meaning is already explained to the c compiler. The key words are also known as reserved words. There are total 32 key words available in C. They are as given below.
Key words in C
Auto Double Int Struct
Break Else Long Switch
Case Enum Register Typedef
Char Extern Return Union
Const Float Short Void
Continue For Signed Unsigned
Default Goto Sizeof Volatile
Do if static While
Basic structure of C program:
The basic structure of c program is as given below.. Documentation Part
Link Section Definition Section
Global Declaration Section Main( ) Function Section {
}
Sub Program selection
(User defined functions) Declaration Part Executable Part Function 1 Function2 - - Function n
The brief discussion about each section is as given below: ☺ The Documentation section consists of a set of comment lines giving the name of the program, the author and other details, which the programmer would like to use later.
☺ The link section provides instructions to the compiler to link functions from the system library.
☺ The definition section defines all symbolic constants.
☺ There are some variables that are used in more than one function. Such variables are called global variables. And they are declared in the global declaration section that is outside of all the functions. This section also declares all the user-defined functions.
☺ Every C program must have on main( ) function section. This section contains two parts: Declaration part and Executable part.
The declaration part declares all the variables used in the executable Part.
There is at least one statement in the executable part.
These two parts must appear between the opening and closing braces. The program execution begins at the opening braces and ends at the closing brace.
The closing brace of the main function section is the logical end of the program
All the statements in the declaration and executable parts end with a semicolon.
☺ The subprogram section contains all the user-defined functions that are called in the main function.
☺ All sections, except the main function section may be absent when they are not required.
The First C program that print a simple message.
// A program that print a simple message. #include<stdio.h>
#include<conio.h> void main( )
{
printf(“ Hello world”); }
A program to add two numbers.
//A program that add two numbers. #include<stdio.h> #include<conio.h> void main( ) { int a,b,c; clrscr( );
printf(“ Enter the value of a: “); scanf(“%d”,&a);
printf(“ Enter the value of b: “); scanf(“%d”,&b); c=a+b;
printf(“\n The addition is %d”,c);
getch( );
}
some useful formatting strings:
Data Type 1) Integer 2) Float 3) Long 4) Character 5) String 6) Unsigned int 7) Short int 8) Long double %d %f %l %c %s %u %h %L
Introduction:
-We all know that C program is the set of statements, that can execute normally in sequence one by one without skipping any statement.
Now, if we want that our program execute only when the particular condition is satisfied. That means our program execution is on the basis of the conditions and some portion will be skipped and some portion will be executed, that is totally condition-based execution. That means you can change control flow of the program.
To perform such things C supports decision making statements that are as given below:
1) if statement 2) switch statement
3) Conditional operator statement 4) goto statement
These statements are purely known as “Decision Making”. And they are also ‘control’ the flow of execution, they are also known as “Control Statement”.
DECISION MAKING USING IF
STATEMENT
The if statement is the powerful decision making statement and is used to control the flow of execution of the statements. C uses the keyword if to implement the decision control instruction. It is basically a 2 way decision making statement.
☺Syntax: ‐
if(test expression) {
statement block; }
☺ The Graphical presentation of this is as given below:
Flow Chart of the Simple If statement
This structure allows the computer to evaluate the expressions first and then, depending on whether the expression will evaluate to true or not? Then depending on the result it will transfer the control on a particular statement.
If the test expression is evaluated to true, then the statement-block will be executed. And the statement-x will also be executed.
If the test condition is evaluated to false. Then the statement-block will be skipped and directly the control will move to the statement-x.
Note that, In both the cases the statement-x will be executed. An Example of the simple if condition is as given below:
True
False
Test Exp- Ressions ? Statement-block Statement -x#include<stdio.h> #include<conio.h>
// A program to show the use of simple if condition. void main( )
{
int age;
clrscr( );
printf(“\n Enter Your age : “); scanf(“%d”,&age); if(age>18)
{
printf(“\n You Get license”); }
printf(“\n Good Bye ‘); getch ( );
}
Output: -
Enter Your age : 20 You get license
Good Bye
DECISION MAKING USING IF…ELSE STATEMENT
The if else statement is the extension of the simple if statement. The general form of if…else is as given below: ☺ Syntax: if(test expression) { True-block statements; } else { False-block statement; } Statement-x;
☺ The graphical presentation is as given below:
The Flow Chart of if..else Statement
The structure allows the expression to be evaluated first and depending on the value which is returned by the expression the control is transferred to a particular statement block.
First the condition is evaluated; if the condition is true then the control is transferred to the True-block of the program, and then the statement-x will be executed, which is out of the if..else block. If the condition is false, then the control is transferred to the
False-block of the program. And then the statement-x, which is out of the if..else block.
Note that, the statement-x will be executed in both the cases, they are not related with the result of the condition.
Test Expression ? False-block statement True False-block statement False Statement - x
//A Program of if else statement #include<stdio.h> #include<conio.h> void main( ) { int no; clrscr( );
printf(“\n Enter any number”); scanf(“%d”,&no);
if(no>0)
printf(“\n The no. is Positive”);
else
printf(“\n The no. is Negative”); getch( );
}
Output: -
Enter any number : 12 The no. is Positive
DECISION MAKING WITH NESTED IF..ELSE STATEMENT When a one if..else statement is within the another if..else is known as “Nesting of If..Else”. The general form of the nested if..else is as given below: ☺ Syntax: ‐ if(test expression‐1) { if(test expression‐2) { statement‐1; } else { statement‐2; } } else { statement‐3; } Statement –x;
The graphical presentation of the nested if..else is as given below: The Flow Chart of Nested if..else In this case, the structure shows that a condition is evaluated first, then according to the condition the control will move in your program. If the Exp.1 evaluated to true, then the control will proceeds Test expression-1 ? Test expression-2? Statement -1 Statement -2 False True Statement -3 Statement-x Next statement True False Entry
If the Exp1 evaluated to true and Exp.2 evaluated to false then the control will transferred to the statemene‐2. And if the Exp.1 will evaluated to false, the control will transferred to the else portion of the main condition. That means the statement‐3 will be evaluated. And in any of the cases the control will proceeds always to the statement‐x. which is not depend on the result of the condition. An Example of nested if is as given below: // A program of the nested if…else #include<stdio.h> #include<conio.h> void main( ) { int a,b,c; printf(“\n Enter a: “); scanf(“%d”,&a); printf(“\n Enter b: “); scanf(“%d”,&b); printf(“\n Enter c: “); scanf(“%d”,&c); if(a>b) { if(a>c) printf(“\n A is Big”); else printf(“\n C is Big”); } else { if(c>b) printf(“\n C is Big”); else printf(“\n B is Big”); } getch( ); }
Output: ‐ Enter a: 20 Enter b: 30 Enter c: 40 C is Big
DECISION MAKING WITH ELSE..IF LADDER
Just observe that the program uses the nested if‐elses. This leads to three disadvantages: 1) As the No. of conditions are going increased the level of indentation is also increased. An as a result the program is shifted to the right hand side, and readability of your program will be decreased. 2) In case of nested if‐else you must take care about the pair of the ifs and elses. 3) You must take care of the opening braces and closing braces of each & every ifs and elses. There is one more way in which we can write the program of multiple conditions, This involves usage of else if blocks as shown below: The syntax, Example & Flow chart of the else if blocks are as follow: ☺ Syntax: ‐ if(condition‐1) statement‐1; else if (condition‐2) statement‐2; else if(condition‐3) statement‐3; else if (condition‐n)The graphical representation of the Else If ladder is as given below: The Flow Chart of the else…if Ladder This construct is known as the “ELSE…IF LADDER”. The conditions are evaluated from top to bottom, downwards. Cond-1 Cond-2 Cond-3 Cond-n Default Statement Statement-n Statement-3 Statement-2 Statement-1 False True False False False True True True Statement-x Next statement
As soon as a true condition is found, the statement associated with that condition will be executed, and then the control will transferred to the statement‐x.(by skipping the rest of ladders). When all the condition become false, then the else portion that is the final else that contains the default‐ statement will be executed, and the control will transferred at the statement‐x. That means the program execution will become faster, when you are using the else…if ladder instead of more than one ifs. Because after execution of a particular statement, there is not more conditions are checking, that means skipping the rest of ladder. The example of the else if ladder is as give below: // A program that shows the use of Else…If ladder #include<stdio.h> #include<conio.h> void main( ) { int m1,m2,m3,tot; float per; printf(“\n Enter Mark1: “); scanf(“%d”,&m1); printf(“\n Enter Mark2: “); scanf(“%d”,&m2); printf(“\n Enter Mark3: “); scanf(“%d”,&m4); tot=m1+m2+m3; per=tot/3;
printf(“\n Percentage : %f”,per); } else if (per>=60 && per<70) { printf(“\n You get First Class”); printf(“\n Percentage : %f”,per); } else if(per>=50 &&per<60) { printf(“\n You get Second Class”); printf(“\n Percentage : %f”,per); } else if(per>=40 && per<50) { printf(“\n You get Pass Class”); printf(“\n Percentage : %f”,per); } else { printf(“\n You are FAIL”); printf(“\n Percentage : %f”,per); } getch( ); } Output: ‐ Enter Mark1: 80 Enter Mark2: 75 Enter Mark3: 85 You get Distinction Percentage : 80
MULTI WAY DECISION WITH SWITCH STATEMENT
We have already done the decision making using simple ifs and multiple ifs and elses. And as we know that each new form of if was reduced the limitations of previous one. Actually there is no limitation of if…..else ladder. But when the no. of conditions are going to increasing the level of indentation will also going to increasing, at that time even a designer of a program will confuse about the program. So remove this limitation of the else…if ladder, C provides a facility called the Switch‐Case statement, also known as “Branching Statement”. The syntax of the Switch is as given below:
☺ Syntax: ‐
switch(expression) { case value‐1: block‐1; break; case value‐2: block‐2; break; ………. ………. Default: Default‐block; Break; }
The graphical representation of switch‐case statement is as given below: The Flow Chart of Switch‐Case Statement The switch statement is preticularly used for menu driven programming.
The switch statement checks value of the expression against a list of case value, and when a match is found, a block of statements associated with that case is executed. The expression is an integer or character expressions. Value‐1,value‐2….are the integer constants or the character constants. Each value in the list of case must be unique, that means no 2 case have similar values. Switch expression Block-1 Expression=value-1 Block-2 Expression=value-1 Block-3 (no-match) found Statement-x
Not that, each case keyword with expression is followed by a colon.
The block‐1,block‐2…. Are the statement blocks and may contain 1 or more statement that will be executed.
The value of switch (expression) will compared with a list of case values, and when a match is found the statement of that case will be executed.
Note that, each block contain the “break” statement at the end of each statement block will signals the control at the statement‐x which is out of the switch statement. When there is no match found between switch and case value the default case which is optional, and known as else case will be executed.
ANSI C permits the use of as many as 257 case labels. Advantage : ‐ The main advantage of switch statement over if is that it leads to more structured program & the level of indentation is manageable, more so if there are multiple statements within each case of switch. The Drawback is the use of logical operators. That means the logical operators can not be used in switch..case.
Example: ‐
// A program of switch case statement #include<stdio.h> #include<conio.h> void main( ) { int ch,a,b; printf(“\n 1.Addition”); printf(“\n 2.Subtraction”); printf(“\n 3. Multiplicatioin”);printf(“\n Enter A & B :”); scanf(“%d %d”,&a,&b); switch(ch) { case 1: c=a+b; printf(“%d”,c); break; case 2: c=a‐b; printf(“%d”,c); break; case 3: c=a*b; printf(“%d”,c); break; case 4: c=a/b; printf(“%d”,c); break; default: printf(“\n Invalid choice”); break; } }
CONDITIONAL OPERATOR
The conditional operator are also known as a “Ternary operator”. It used as an alternative of simple if…else statement.
The combination of ? and : is known as a conditional operator. The general form of conditional operator is as given below:
☺ Syntax: ‐
Conditional expression
?
expression 1:
expression 2;In which the conditional expression is evaluated first, if the conditional expression is evaluated to true, then the expression 1 which is immediately followed by conditional expression will be executed.
If the conditional expression is evaluated to false then the expression2 will be executed. The conditional operators can be used as an alternate of the simple if……else block. Since it can take 3 operands. The example of the conditional operator and it’s comparison with simple if…else block is as given below:
Example: ‐
// An example of conditional operator. #include<stdio.h> #include<conio.h> void main( ) { int x,y; printf(“\n Enter the value of x :”); scanf(“%d”,&x); y=(x>5)?5:8; printf(“\n Y= %d”,y); getch( ); } The following points can be noted out: ‐1) It’s not necessary that the conditional operators should be used only in arithmetic statements. The same thing can be done using if..else is as given below: If(x>5) y=5; else y=8;
(i==1 ? printf( “Hi”) : printf( “ Hello”); 2) The conditional operator can be nested as shown below: Example: ‐ Char a=’z’; Printf(“%c”,(a>=’a’ ? a : ‘ ! ‘));
THE GOTO STATEMENT
The goto statement is used to alter the normal sequence of program execution by transferring control to some other part of the program.
That means if you want to control the flow of control according to a certain condition then you can do it with the help of “Goto Statement”.
Actually this statement is referred to as “goto label”.
C supports the goto statements to branch unconditionally from one point to another in the program.
The goto requires a label to identify the place where the branch is to be made. The label is any valid variable name, and must be followed by a colon. The label is placed immediately before the statement where the control is to be transferred.
☺ Syntax: ‐
Forward Jump Backward Jump Goto label; - - - - - - - - - label: statement ; Label: Statement; - - - - - - - - - goto label;
The label can be nay where in the program either before or after the goto label; statement.
Note that a goto breaks the normal execution of the program.
If the label: is placed before the statement goto label; a loop will be formed and some statements will be executed repeatedly. And such jump is known as “Backward Jump”. If the label is placed after the goto label; some statements will be skipped & the jump is known as a “Forward Jump”. The most common applications of the goto is as given below:
1) Branching around the statements and group of statements under certain conditions.
2) Jumping it the end of a loop under the certain conditions, thus bypassing the reminder of the loop during the current pass.
3) Jumping completely out of the loop under the certain conditions, thus terminating the execution of the loop. The example of the goto statement is as given below: Example: ‐ // A program of the goto label… #include<stdio.h> #include<conio.h> void main( ) { int cnt=1; a: // label printf(“\n Computer”);
} Output: ‐ Computer Computer Computer Computer Computer Computer Computer Computer Computer Computer
We have already learn about the sequential program and also learn about that how we can control the flow of program and branching of some of statements of the program. Now we are going to learn that how to perform the particular task no. of times. That means how repeat a task without writing a task no. of times.
This thing can be done using the concepts of loop.
To understand the concept of the loop, it is necessary to understand the concept of the following things: 1) Loop: ‐ To perform a particular task no. of times the concepts of loops can be used. Loops can be of 2 types: A> Finite Loop: ‐ The loop in which the no. of iteration is predefined is known as Finite Loop.
B> Infinite Loop: ‐ The loop in which the no. of iteration is not predefined is known as Infinite Loop. 2) Iterations: ‐ The meaning of the word “Iteration” is “Repetition”. 3) Counter Variable : ‐ The variable which is used to count the no. of iterations is known as counter variable. In looping the sequence of statements are executed until some conditions for termination of the body of the loop are satisfied. Therefore the program loop is made up of 2 statements: The Body of the loop The Control statement (A Condition) Depending on the position of the condition (control statement) in the loop, the loop may be classified into 2 categories : 1) Entry‐Controlled loop 2) Exit‐Controlled loop There are 3 methods through which some part of the program can be repeated number of times, they are as given below: 1) The While statement 2) The do…while statement 3) The for statement
THE WHILE STATEMENT
The while statement is the simplest of all the loop structure in the C language. The syntax of the while statement is as given below: ☺ Syntax: ‐ while( test expression) { body of the loop } statement‐x;The while statement is known as entry‐controlled loop. Because the condition is checked first and then the body of the loop will be executed if the condition is true.
Here the while is the keyword which denotes that the following block is the loop.
If test expression is evaluated to true then and then the body of the loop will be executed, otherwise the control will transfer to the statement‐x, which is immediately after the loop.
If the condition is true and the loop will executed, then again the condition will be checked if the condition is true than the body of the loop will be executed. This process is continued while the test condition is not evaluated to false.
The flow chart and the example of the while statement is as given below:
The Flow Chart of the Entry‐Controlled Loop ☺Example: ‐ // A program of the while statement #include<stdio.h> #include<conio.h> void main( ) { int no=1; while(no<=10) { printf(“\n %d”,no); no++; Entry Test-Condition ?
Body of the loop True
Output: ‐ 1 2 3 4 5 6 7 8 9 10
THE DO…WHILE STATEMENT
The do…while statement is known as an “Exit‐Controlled Loop”. In case of while loop, the condition is checked first and then the body of the loop will be executed. That means if the condition is not satisfied at first attempt then the control will jump out of the loop. Where as in case of do…while statement the body of the loop is executed first and then the condition will checked, that means the body of the loop is executed if a condition is not satisfied at first attempt. The syntax and example of the do…while statement is as given below:☺ Syntax: ‐
do { body of the loop } while (condition);In above syntax the do & while are the keywords which defines the loop. Consider the syntax the condition is not checked at the entry of the loop, but the condition is on exiting the loop. According to the syntax, when the control will be reached at the do statement, then the control will proceeds to the body of the loop. And at last the condition will check. Now if the condition is true then the control will go at the do statement again and the body of the loop is executed once again, this process continuous as long as the condition is true. The graphical presentation of the same is as given below: The Flow Chart of “Exit‐Controlled Loop Body of the loop Test condition ? True False
void main( ) { int sum=0,count=1; do { sum=sum+count; count=count+1; }while(count<=10) printf(“\n The Summation of 1 to 10 is : %d”,sum); getch( ); } ☺ Output: ‐ The summation of 1 to 10 is 55
THE FOR STATEMENT
The for statement is the most widely looping control statement among the all statements. This is again an entry controlled looping statement and provides a more concise loop control structure. The for loop is very simple and the syntax of the for loop is something different from the other 2 statements. ☺ Syntax: ‐ for (initialization ; test condition ;increment) { body of the loop; } Where, You can see the initialization of the counter variable is also the part of the loop. Here the for statement is consist of 3 parts: Initialization (i) Testing (t) Increment (i) The initialization of the counter variable is done only once, using an assignment statement.
The second part is consist of the conditional statement, that is the used to control the loop. If you want to know the maximum iterations of the loop, then you can identify it using the conditional expression.
The last part is consist of the increment or decrement of the counter variable, through which the value of the counter variable is finally reach at the maximum iterations of the loop.
After executing this increment and decrement of the variable the value of the variable the new value of the variable is again tested, if the new value of the variable is satisfy the condition then the body of the loop is again executed. This process is continued till the value of the counter variable is reached at the maximum value of the variable. ☺ Example: ‐ // A program that shows the use of the for loop. #include<stdio.h> #include<conio.h> void main( ) { int I; for(i=1;i<=10;i++) { printf(“\n Computer”); } getch( ); } ☺ Output: ‐ Computer Computer Computer Computer Computer
Features of for loop: ‐ 1) You can initialize more than one variable at a same time in the for statement. 2) You can give multiple arguments as an increment and decrement part of the for statement. 3) The test condition has any compound relation and the testing need not be limited only to the loop control variable. 4) It is also possible to use the expression to initialize the value of the counter variable. 5) It is also possible to omit one or more sections of the for statement. Nesting of for loop: ‐ As an if statement, the for loop may be nested, that means one for loop within another for loop. This is as given below: For(i=1 ; i<=5 ; i++) { ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ for( j=1 ; j<=5 ; j++) Outer Loop { Inner ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ Loop ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ } ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ } The nesting of the loop may continue upto any desired level, but our ANSI C Compiler allows up to 15 levels of the nesting. The outer loop is for the rows and the inner loop is for the columns.
// A program of the nesting for loop #include<stdio.h> #include<conio.h> void main( ) { int I,j; clrscr ( ); for( i=1 ; i<5 ; i++) { for(j=1 ; j<=5 ; j++) { printf(“%d”,i); } printf(“\n”); } getch( ); } Output: ‐ 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5
Up to this chapter, we are learning to store only one value in the variable at a time.
Now suppose you want to store multiple values in the program, at that time you need not to declare that much variables in your program. C supports the concept of an array.
Using an array, we can store multiple values within one variable. The concept of an array is used to handle the large amount of data.
ARRAY : ‐ An Array is a collection of the elements having similar data type.
We can use an array to represent not only simple lists of values but also tables of data in two or three or more dimensions. There are 3 types of an array available in C. 1) One dimensional Array 2) Two dimensional Array 3) Multi dimensional Array 1) One dimensional Array: ‐
The array is said to be an one dimensional, if the array variable name has only one subscript. That means a list of items can be given one variable name using only one subscript and such variable us called a “Single scripted variable” or “One dimensional Array”.
☺ Syntax: ‐
Where,
The data type is any valid c data type. Variable is any valid c variable.
And the value specifies that how many values can be stored inside the variable. ☺ Declaration of a one dimensional Array: ‐ int a[5]; ☺ The computer reserves the five locations as shown below:
Declares the variable named a and can hold 5 values at a same time.
All the values may belong to only one data type that is integer.
The example of the single dimensional array is as given below:
Consider the figure, the array variable name has on subscript that is called the index number. The array subscript begins with 0 and the last subscript is always size of array minus 1. Number[0] Number[1] Number[2] Number[3] Number[4]
• Note : ‐
•
Any references to the arrays outside the declared limits would not necessarily cause an error. Rather it might result in unpredictable results.•
The size should be either a numeric constant or a symbolic constant.☺ Example: ‐ //A Program of the single dimensional array….. #include<stdio.h> #include<conio.h> void main( ) { int a[5],I; for(i=0;i<=5;i++) { scanf(“%d”,&a[i]); } for(i=0;i<=5;i++) { printf(“\n%d”,a[i]); } getch( ); } Output: ‐ 1 2 3 4 5 1 2 3 4 5
Character Array
As we know the meaning of array, which means an array is a collection of elements having similar data type.
We have already seen the declaration of integer array. In your mind the concept of character array is similar to the int array, right?
But the answer is No!...
Up to this topic we know that the char data type can hold only one character at a time. Now, suppose you want to store the whole name in one variable, so what you can do?
String: ‐ The string is the collection of characters. OR The string is the Array of characters.
The all above things has just one meaning, that means to provide the facility to the variable of storing of string the concept of character array is used. The character array is nothing but the array of the character data type. ☺ Syntax :‐ char variable_name[size];
In which the size of the array is indicate that how many characters are stored inside the variable.
Each character of the string is treated as an element of the array is stored in the memory as follows:
☺Example: ‐
When the compiler sees a character string, it terminates it with an additional character called null character (‘/0’) i.e slash zero.
Initialization of one dimensional array.
As an ordinary variable we can also initialize the array variable. The array can be initializing either “Compile time” or “Run time”.
Compile Time Initialization: ‐
You can initialize an array at compile time by defining a set of values within {…….}. ☺ Syntax: ‐ data type variable_name[size]={list of values}; Example 1: int no[3]={1,2,3}; where, no[0]=1 no[1]=2 no[3]=2 ‘W’ ‘e’ ‘l’ ‘ ‘ ‘C’ ‘o’ ‘m’ ‘e’ ‘\0'
Example 2: float a[4]={0.08,0.10,6.78,45.5} where, a[0]=0.08 a[1]=0.10 a[2]=6.78 a[3]=45.5 Example 3: char nm[5]={‘L’,’C’,’D’,’C’,’/0’} OR char nm[5]= “LCDC” where, nm[0]=’L’ nm[1]=’C’ nm[2]=’D’ nm[3]=’C’ nm[4]=’/0’ 2) Tow dimensional Array: ‐
We all know that an array variable can store a list of values. Now, if we want to store a list of value in form of table, at that time two‐ dimensional array is used. The two dimensional array is just a variable name with 2 subscript. The same rule is applied over here. That is the subscript is start from 0 and the last subscript is size‐1. Here we have to specify to things in 2‐D array.
☺ Syntax: ‐ data type variable_name [row size] [column size]; ☺ Example: ‐ int no[3][4]; The above variable no can hold total 12 values. The memory representation of the no variable is as given below:
No[0][0] No[0][1] No[0][2] No[0][3] No[1][0] No[1][1] No[1][2] No[1][3] No[2][0] No[2][1] No[2][2] No[2][3]
There is another concept of 2‐D character array. That means you can store only one string in 1‐D array of the character data type. But when you want to store more than one string within one variable at that time 2‐D array of the character data type is used. To Store more than one string within 1 variable: ‐ Char nm [3][4]; The variable can store 3 strings, each having 4 characters.
Remember: ‐
There are 2 ways of getting string form the key board. 1) Either you use scanf( ) function. 2) Or you use the gets ( ) function.But remember that the scanf( ) function can’t accept the space within a string.
And the gets ( ) function can accept the space within a string.
When we want to create a variable that can hold the values of different data types, at that time the concept of structure variable.
Structure: ‐
Structure is the collection of elements having different data types. ☺ Syntax: ‐ struct tag_name { data type member..1; data type member..2; data type member..3; ‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐ data type member..n;
};
Struct tag_name struct type variable;
Where,
The struct keyword defines the structure.
The tag name is the identifier of the structure. This should
be meaningful.
And in the last you can see one variable which is not
belongs to a particular data type. It’s data type is
structure.
The structure is the user defined data type. It is not a built‐
in data type.
Remember one point: ‐ Internally the members of the
structure have not any space in the memory at compile
time, when they are associated with the structure type
variable at that time they have been given a memory.
To access the members of the structure the member
operator (.) is used. Let see on example that contain the
data of student.
☺ Example: ‐
// A program of the structure….
#include<stdio.h>
#include<conio.h>
void main( )
{
struct stud
{
int rno;
char nm[15];
};
struct stud s;
printf(“\n Enter your Roll No. :”);
scanf(“%d”,&s.rno);
printf(“\n Enter your Name :”);
scanf(“%s”,&nm);
printf(“\n Roll No. : “,rno);
printf(“\n Name : “,s.nm);
getch( );
}
☺ Output: ‐
Enter Roll No. 12
Enter Name : Anmol
Roll No : 12
Name : Anmol
In the above program you can see that the structure has 2
members. And can be access by using a structure type
variable and member operator.
In C, there are 2 types of functions
1) Built‐ in functions (Library functions)
2) User Defined functions (UDF)
Function: ‐ A Function is a self contain block of statement
that can perform a particular task.
In previous chapters we are already used built‐in
functions like, printf( ), scanf( ), clrscr( ) etc.
That means the functions which are created by the user
are known as user defined functions.
The user defined functions are declared, defined and
called within the c file as per the requirement of the
user.
There are some points that can be noted out as given
below:
1) The Function is defined out side the main ( ).
2) The Function can be called from the main ( ) or any
other UDF.
3) After executing each of the UDF the control will
transfer in the main( ).
4) The function call statement is followed by ( ) and
semincolon ( ; ).
5) The Function definition is followed by the ( ).
6) There is no need to specify the name of the variable at
the time of prototype of the function.
7) One C program can have more than one UDF.
8) Each and every program has one UDF that is
obviously main( ).
9) The functions are executed in order, in which they are
called, not in which they are defined.
10) There are some types of the UDF is as given below:
Types of the UDF
1) Function without argument without return value. 2) Function with argument without return value. 3) Function with argument with return value. 4) Function without argument with return value. To understand the types of the udfs, we have to under stand the following things:
Prototype: ‐ The declaration of the UDF is known as prototype of the function.
Argument: ‐ The parameter (value/variable) which can be passed while calling the function is known as arfument. 1) Function without argument without return value: ‐ When the function has no argument, it does not receive any data from the calling function. And when the function does not return any value, the calling function does not receive any data. Let’s take one example… ☺ Example: ‐ #include<stdio.h> #include<conio.h> void add(void) // Function prototype void main( ) { clrscr( ); add( ); //Function calling statement getch( ); } void add( ) // Function definition { int a,b,c; printf( “Enter a,b : “); scanf(“%d %d”,&a,&b);
2) Function with argument without return value: ‐ In this category, the calling function has some data that can be passed as an argument.
But the called function has no data so that it can’t return any value to the calling function.
That means One way communication is possible between functions. ☺ Example: ‐ #include<stdio.h> #include<conio.h> void add(int ,int) void main( ) { int a,b; printf(“\n Enter a & b”); scanf(“%d %d”,&a,&b);
add(a,b); //function call with 2 arguments…(formal argument) getch( ); } void add( int a,int b) { int c; c=a+b; printf(“\n Addition is : %d”,c); }
3) Function with argument with return value: ‐
In this type the calling function has some data that can be passed as an argument.
And the called function also response the calling functions, that means the called function can return a value to the calling function by using the return statement.
Return is the keyword which can be used to return the values from the functions. ☺ Example: ‐ #include<stdio.h> #include<conio.h> int add( int,int) void main( ) { int a,b,c; printf(“\n Enter a and b: “); scanf(“%d%d” ,&a,&b); c=add(a,b); printf(“\n The Addition is %d”,c); } int add(int a, int b) { int c; c=a+b; return (c); }
In this type the calling function cannot send any argument to the called functions as an argument. But the called function can send the value by using a return statement as a response. This is one type of again a “One way Communication”. ☺ Example: ‐ #incclude<stdio.h> #include<conio.h> int add(void) { int c; c=add(); getch( ); } int add( ) { int a,b,c; printf(“\n Enter a: “); scanf(“%d”,&a); printf(“\n Enter b: “); scanf(“%d”,&b); c=a+b; return ( c );
1. C is ____________level language. 2. C is developed by _________________, in the year_________. 3. C is developed at _________________ in USA. 4. _________ is the name given to the memory Location. 5. _________ are the values, which are stored in the variable. 6. During the execution of the program the value of ________is changed and the value of ________is not changed. 7. The Graphical Presentation of any problem is known as ___________ and the step‐by‐step representation of Problem and graphical presentation is known as ___________. 8. ___________ is the predefined identification of any variable. 9. There are total ______ keywords in the C Language. 10. = is ________operator and == is the ________operator. 11. When we use the combination of arithmetic and assignment operator is termed as____________. 12. The character data type can hold ____________at a time. 13. By default the float data type can support __________ decimal point. 14. ? and : are known as _________operator and can be used as an alternate of ____________ statement. 15. ___________ Statement is known as “Branching Statement”. 16. __________ is the technique to finding and fixing the Errors from the program. 17. In C, The execution of each and every program starts with _________. 18. Every C program may contain at least one UDF that is ___________. 19. The non‐executable part of the program is known as _________.
22. The Full form of ASCII is ________________________________. 23. ______ is the shortcut key of Compile. 24. ______ is the shortcut key of Output window. 25. ______ is the shortcut key of Run. 26. ______ is the shortcut key of close the window. 27. ______ is the shortcut key of Watch window. 28. Printf) and scanf () is the function of the ____________. 29. Getch () and clrscr () is the function of the _____________. 30. ______Symbol is used for single line comment and ______ is used form multiple line comment. 31. The “If‐else” within another “If‐else” is known as __________. 32. To perform a particular task No. of times___________are used. 33. The “Array of Characters” is known as ___________. 34. ______ is the format specifier of long int data type. 35. _______ is the format specifierr of the String. 36. String is the data type provided by C? (True/false)________. 37. ______ Function is used to get the string from the user. 38. ______ is the collection of elements having similar data types. 39. ________ is the collection of having Different data types. 40. Structure is _____________ data type. 41. There are ______ types of functions available in C. 42. ________ and _______ are the “Entry‐Controlled “ Loops. 43. ________ is the “Exit‐Controlled” Loops. 44. + and – are the _________ operators and ++ and – are the _______ operators. 45. _______operators are used to combine the Expressions. 46. There are _________ logical operators available in C. 47. The last element of the Character array is _______. 48. We can define the array of structure and array within structure. (True/false)__________. 49. We are using ________ compiler.
50. We are using _________environment of C. 51. The extension of the C File is ________. 52. The default name of the first C file is ________. 53. The ANSI C Compiler allows _______level of nesting in the “FOR LOOP”. 54. Placing semicolon after the “For Statement” is _________ error (Logical/Syntactical). 55. Give Output: ‐ int a=10, b=20; P=a++; Q=++b; What is the value of P and Q 56. ________is the Collection of elements having similar data types and ______ is the Collection of elements having different data types. 57. Fill The Blanks From the Given Example: Struct Stud { int R_no; char nm [15]; int std; }; struct stud s; In above Example __________ is the keyword, _______________ members,___________is identifier,___________is the structure type variable and all these thing is known as ________. 58. To define an array the keyword is used.(True/False)________. 59. To define the structure __________ is used. 60. In the Goto label ___________ is followed by semicolon and _______ is followed by colon.