26
C Programming Language C programming language: C programming language is one of the most popular general-purpose programming languages. It is designed and developed by Dennis Ritchie at bell laboratories, USA, in 1972. Several important concepts of C are drawn from “Basic Combined Programming Language” and “B” language. The BCPL was developed by Martin Richards in 1967 and B Language was developed by Ken Thompson in 1970. C Language is not fixed to any particular operating system. It can be used to develop new operating systems. The C language is closely associated with the UNIX operating system because the source code for the UNIX operating system is in C. It runs different types of operating system like DOS, Windows etc. the C Programming Language is highly portable because it can be written on one computer can be run on another with simple or almost no modification Importance of c language: 1.The C language is a robust language whose rich set of built-in functions and operators can be used to write any complex program. The C compiler combines the capabilities of an assembly language with the features of a high-level language. Therefore, it is well suited for writing both system and application packages. (robust language) 2.Program written in c language are efficient and fast due to its variety of data types and powerful operators. (efficient and fast) 3.C language is highly portable, means that c program written for one computer can be run on another computer with little or no modifications. (highly portable) 4.C language is well suited for structured programming, thus requiring the user to think of a problem in terms Prepared By: Chetan Thapa Magar ( Brightland Higher Secondary College ) www.facebook.com\MeIDoKoXora

C programming language Reference Note

Embed Size (px)

Citation preview

Page 1: C programming language Reference Note

C Programming Language

C programming language:C programming language is one of the most popular general-purpose

programming languages. It is designed and developed by Dennis Ritchie at bell laboratories, USA, in 1972. Several important concepts of C are drawn from “Basic Combined Programming Language” and “B” language. The BCPL was developed by Martin Richards in 1967 and B Language was developed by Ken Thompson in 1970. C Language is not fixed to any particular operating system. It can be used to develop new operating systems. The C language is closely associated with the UNIX operating system because the source code for the UNIX operating system is in C. It runs different types of operating system like DOS, Windows etc. the C Programming Language is highly portable because it can be written on one computer can be run on another with simple or almost no modification

Importance of c language:1. The C language is a robust language whose rich set of built-in functions and

operators can be used to write any complex program. The C compiler combines the capabilities of an assembly language with the features of a high-level language. Therefore, it is well suited for writing both system and application packages. (robust language)

2. Program written in c language are efficient and fast due to its variety of data types and powerful operators. (efficient and fast)

3. C language is highly portable, means that c program written for one computer can be run on another computer with little or no modifications. (highly portable)

4. C language is well suited for structured programming, thus requiring the user to think of a problem in terms of function modules or blocks. A proper collection of these modules would make a complete program. This modular structure makes program debugging, testing and maintenance easier and fast. (structured language)

5. C program may contain a number of user defined functions. We can add our own user defined functions to the c library if required. (extendibility)

6. C program is a middle level language because it combines the best part of high level language with low level language. It is well suited for writing both user and machine oriented programs and provides infinite possibilities. (middle level language)

7. In C language, there are large numbers of built in functions, keywords and operators in C’s system library organized in different header files. Using built-in functions, we can save our effort and reduce the size of the program.

Prepared By: Chetan Thapa Magar ( Brightland Higher Secondary College )www.facebook.com\MeIDoKoXora

Page 2: C programming language Reference Note

Algorithm LanguageALGOL

BCPL

B Language

Traditional C

K & R C

C Programming Language

The history and development of c

1960 International Group

1967 Martin Richards

1970 Ken Thompson

1972 Dennis Ritchie

1978 Kernighan and Ritchie

Elements of c programming language:Every c programming language consists of one or more modules. These modules

are called functions. One of the functions must be called main(). The program will always begin by executing the main function. This function may access other functions. There can be many functions. Each function should be defined separately. The user defined functions are either defined ahead of main function or within the main function. Each function must contain the following; A function heading, which consists of the function name(including the arguments

if present) A list of argument declarations if the arguments are included in the heading A compound statement, which comprises the remainder of the function

The arguments are also called the parameters. Each compo9und statement is enclosed within a pair of braces i.e. { }. The comments or remarks may appear within the program anywhere within the delimiters /* and */. The comments help to read the program and makes convenient during debugging the program errors.

Prepared By: Chetan Thapa Magar ( Brightland Higher Secondary College )www.facebook.com\MeIDoKoXora

Page 3: C programming language Reference Note

Include header file section

Global Declaration section

/* comments */int main (void) /*function name */{/* comments */Declaration partExecutable partReturn 0;}User-defined functions{Body of the function}

C Programming Language

Structure of a c programming:The structure of a C program implies the composition of a program, i.e. It

answers and questions such as “what are main components to write a c program? How are they organized?”

orheader filevoid main (){…………………………..………………………….………………………….statements; body………………………………..……………………………………………………………….}

Prepared By: Chetan Thapa Magar ( Brightland Higher Secondary College )www.facebook.com\MeIDoKoXora

Page 4: C programming language Reference Note

C Programming Language

C programming#include<stdio.h>#include<conio.h>void main(){printf(“hello, this is my first c programming”);}Justification:

#include directive: It is the most essential directive. A directive is links to a header file. The header file makes full use of the i/o functions of the standard C library. Here stdio.h is a header file and # sign is known as preprocessing directive.void main(): It is the main function that must appear in every C program. main without void is used when there are no arguments. main() without any parameters has an argument.printf(): The printf() function is used to print out the message, either on paper or screen. The letter f in printf function stands for formatted.getch(): It is defined in stdio.h header file. This function holds from screen scrolling.

Learning programming concept:#include<stdio.h>void main(){/* ………….. Printing begins ……*/printf(“Hello, I am Chetan Thapa Magar”); /*www.facebook.com/MeIDoKoXora*//*……………..printing ends ………………*/}

Steps in learning a language:

Prepared By: Chetan Thapa Magar ( Brightland Higher Secondary College )www.facebook.com\MeIDoKoXora

Page 5: C programming language Reference Note

Character set C tokens Statements Programs

C Programming Language

Generally steps used in c programming are given below;

Character set:The C character set includes alphabets of both upper (a-z) and lower case (a-z)

letters can be used in C programming language. Followings are the character set used in C programming language.

Nature SymbolsAlphabets A-z, a-zNumerals 0-9Arithmetic + - * / % = ?Logical ! < >| &Parentheses ( ) { } [ ]Punctuation ; : , .Special = ‘ “ # \ ^ ~ (blank)

C tokens:In C programming language text, a word and punctuation marks are called

tokens. It is also called smallest individual keywords.Reserved keywords in C programming language are given below;Auto Break Case Char Const Continue Default DoDouble Else Enum Extern Float For Goto IfInt Long Register Return Short Signed Sizeof StaticStruct Switch Typedef Union Unsigne

dVoid Volatile While

Identifiers:An identifier is a sequence of characters that represents an entity such as a

function or a data objects.

Constant:

Prepared By: Chetan Thapa Magar ( Brightland Higher Secondary College )www.facebook.com\MeIDoKoXora

Page 6: C programming language Reference Note

C constant

Numeric Constants constant Character Constants constant

Integer Constants constant Real Constants constantSingle character Constants constant String constant

C Programming Language

Constant is a value that can be stored in the memory and cannot be changed during execution of the program. C constants are given below;

Strings (alphabets):A string is a sequence of characters. These are stored in memory as ASCII codes

of characters that make up the string appended with ‘\0’ (scii value of null). Normally each character is stored in one byte, successive characters are stored in successive bytes. Any sequence or set of characters defined within double quotation symbols is constant string.

Variables:Variable is a named location in memory, i.e. Used to hold a value that can be

modified by the program. These variable can take different values but one at a time. The values of variables can be changed during execution. All the variables should be declared before they can be used. Variable names may be consists of uppercase character, lower case character and underscore. 5bc, int, rec#, avg no etc. Are invalid variables.

Operators:An operator is a symbol that tells the processor to perform certain

mathematical or logical manipulations. Operators are in programs to manipulate data and variables. The data itself is called ‘operand’. Operators thus operate on operands. C programming language is extremely rich in operators. It has about 45 different operators. The usually form a part of mathematical or logical series called expressions.

Types of operators:

Prepared By: Chetan Thapa Magar ( Brightland Higher Secondary College )www.facebook.com\MeIDoKoXora

Page 7: C programming language Reference Note

C Programming Language

Depending on the functions performed, the C programming language operators can be classified into a number of categories;

Arithmetic operators:Arithmetical operators generally include arithmetic operands. Arithmetical

operators are given below;

+ (for addition)- (for subtraction)*(for multiplication)/(for division)%(for remainder)These operators can work with int, float or char.

Relational operators:Relational operators are for relational operation. These are variables,

constants or expressions. Characters are also represented internally as integers (by their ascii codes), elements to be compared can characters as well.= = (equal to)!= (not equal to)>(greater than)<(less than)<=(less than or equal to)>=(greater than or equal to)

Logical operators:By using a logical operator an expression evaluates to either true (non zero

value) or false (0).&& (logical and)|| (logical or)! (logical not)

Assignment operators:Assignment operator takes the form as,

Variable = expressionThe basic assignment operator is (=)

Unary operator:

Prepared By: Chetan Thapa Magar ( Brightland Higher Secondary College )www.facebook.com\MeIDoKoXora

Page 8: C programming language Reference Note

IF Condition

Statement Statement

No Yes

C Programming Language

A unary operator is an operator that requires only one operand. For example, ++, the increment operator, - - the decrement operator and ‘!’ logical negator.

Conditional operator: A ternary operator pair “?:” is available in C programming to construct

conditional expressions of the formExp1? Exp2: exp3 (where exp1, exp2 and exp3 are conditional expressions).

Bitwise operator:C programming language has a distinction of supporting special operators

known as bitwise operators for manipulation of data at bit level. These operators are used for testing the bits or shifting them right or left. Bitwise operators may not be applied to float or double.Operator meaning& bitwise and| bitwise or^ bitwise exclusive or<< shift left>> shift right

Decision making structures:C programming language has various kinds of statements that permit the

execution of a single statement, or block of statement, based on the evaluation of a test expression or permit the selection of the statement in the executed among several statements based on the value of an expression or a control variable. C programming language supports two selection statements; if and switch.

If-else statement:The general syntax and flowchart of the if statement is given below;

syntax:if(expression){

Statement;}

Prepared By: Chetan Thapa Magar ( Brightland Higher Secondary College )www.facebook.com\MeIDoKoXora

Page 9: C programming language Reference Note

C Programming Language

Where statement may consist of a single statement, a block of statements or nothing (in the case of empty statements). The else clause is optional.

Write a program to display odd or even number:#include<stdio.h>#include<conio.h>void main(){

int a;clrscr();printf(“enter any number which is odd or even:”);scanf(“%d”, &a);if(a%2==0)printf(“%d the number is even number”,a);elseprintf(“%d the number is odd number”,a);getch();

}

Wap1 to find the sum of two numbers#include<stdio.h>#include<conio.h>void main(){int a, b, sum=0;clrscr();printf(“enter the value of a:”);scanf(“%d”,&a);printf(“enter the value of b:”);scanf(“%d”,&b);sum=a+b;printf(“the sum of a and b is:%d”,sum);getch();}

Switch-case statement:C programming language has a built-in multiple branch selection statement,

called switch, which is used to test the value of an expression against a list of integer or character constants. When a match is found the statements associated with that 1 Write a Program (wap)

Prepared By: Chetan Thapa Magar ( Brightland Higher Secondary College )www.facebook.com\MeIDoKoXora

Page 10: C programming language Reference Note

C Programming Language

constant are executed until break or end of switch is encountered. The break interrupts the normal flow of control and then moves to the end of the code or resumes to the normal execution. The default statement is executed if no matches are found. The default is optional and if it is not present no action takes place if all matches fail.Syntax:

switch (expression){

case constant1:statement sequencebreak;case constant2:statement sequencebreak:case constant3:statement sequencebreak;……………………………………………………………..defaultstatement sequence

}

example:#include<stdio.h>#include<conio.h>void main(){

int x;clrscr();printf(“enter the value of x\n”);scanf(“%d”, &x);switch(x){

case 1;printf(“one”);break;case 2;printf(“two”);

Prepared By: Chetan Thapa Magar ( Brightland Higher Secondary College )www.facebook.com\MeIDoKoXora

Page 11: C programming language Reference Note

C Programming Language

break;case 3;printf(“three”);break;case 4;printf(“four”);break;default:printf(“no value”);

}getch();

}

Wap to find the length of the string using printf() function:#include<stdio.h>#include<conio.h>void main(){char name[20];char length;clrscr();printf(“enter the word/string :”);scanf(“%s”,name);length=printf(name);printf(“\nlength of a string=%d”,length);getch();}

Output:Enter the word/string : chetanLength of a string = 6

Loop control structures:C programming language has three loop constructs, which are given below;

1) For loop2) While loop3) Do-while loop

For loop:

Prepared By: Chetan Thapa Magar ( Brightland Higher Secondary College )www.facebook.com\MeIDoKoXora

Page 12: C programming language Reference Note

C Programming Language

For loop allow a set of instructions to be repeatedly (continually) executed until a certain condition is reached. This condition may be predetermined (fixed) or open ended.Syntax:for(initialization; condition; increment or decrement){statement;}

Example:#include<stdio.h>#include<conio.h>void main(){int a,ba=5;b=15;clrscr();if(a<b){printf(“a is smaller than b”);}else if(a>b){printf(“a is greater than b”);}getch();}

Wap to find the smallest out of the three numbers#include<stdio.h>#include<conio.h>void main(){int a,b,c, smallest;clrscr();printf(“\nenter the three numbers : “);scanf(“%d %d %d”, &a, &b, &c);if(a<b){if(a<c)smallest =;elsesmallest = c;}

Prepared By: Chetan Thapa Magar ( Brightland Higher Secondary College )www.facebook.com\MeIDoKoXora

Page 13: C programming language Reference Note

C Programming Language

else{if(b<c)smallest =b;elsesmallest = c;}printf)”the smallest of %d %d %d is %d\n”,a,b,c,smallest);getch();}

Example for (for loop)Wap to display the multiplication table 1-12

#include<stdio.h>#include<conio.h>void main(){int row, column;puts(“\t multiplication table 1-12”);for(row=1;row<=10;row++)

{for(column=1;column<=12;column++)printf(“%5d”,row*column);putchar(‘\n’);}getch();

}

While loop:In C programming language while loop is used to check the test condition at

the top of the loop, which means that the body of the loop will not execute if the condition is false to begin with. This feature may eliminate (remove) the need to perform a separate conditional test before the loop.Syntax:while (condition){statements;}

Do-while loop:

Prepared By: Chetan Thapa Magar ( Brightland Higher Secondary College )www.facebook.com\MeIDoKoXora

Page 14: C programming language Reference Note

C Programming Language

In C programming language the do-while loop checks its condition at the bottom of the loop. This means that a do-while loop always execute at least once. The general form of the do-while loop is given below;Syntax:do{statement;}while (condition);

Break statement:Break is a simple statement. It only makes sense if it occurs in the body of a

switch, do, while or for statement. When it is executed the control of flow jumps to the statement immediately.

Exit statement:exit() is a function. It is used to exit the program as a whole. In other words it

returns control to the operating system.

Difference between break and exit statement:1. break is a keyword 1. exit is a function2. No header file is needed 2.header file process.h must be needed3. break stops the execution 3. It terminates the program.

Of the loop.

Wap that reads the marks of a student in 7 subjects. Then calculate the percentage and determine the division using following conditions.%>=80 distinction%between 60 and 79 first division%between 45 and 59 second division%between 32 and 44 third division%<=31 fail

#include<stdio.h>#include<conio.h>void main(){float nep, eng, math, phy, chem, bio, comp, percent;printf(“enter the marks in nepali:”);scanf(“%f”,&nep);printf(“enter the marks in english:”);scanf(“%f”,&eng);

Prepared By: Chetan Thapa Magar ( Brightland Higher Secondary College )www.facebook.com\MeIDoKoXora

Page 15: C programming language Reference Note

C Programming Language

printf(“enter the marks in math:”);scanf(“%f”,&math);printf(“enter the marks in physics:”);scanf(“%f”,&phy);printf(“enter the marks in chemistry:”);scanf(“%f”,&chem);printf(“enter the marks in biology:”);scanf(“%f”,&bio);printf(“enter the marks in computer:”);scanf(“%f”,&comp);percent = (nep + eng + math + phy + chem + bio + comp) /7;if(percent>=80)printf(“your division is : distinction”);elseif(percent>=60 && percent<80)printf(“your division is : first division”);elseif(percent>=40 && percent<60)printf(“your division is : second division”);elseif(percent>=32 && percent<45)printf(“your division is : third disivion”);elseprintf(“sorry you are : fail”);printf(“\nyour percentage is %2f”,percent);getch();}

Wap to display the message “universal computer institute” 15 times using for loop.#include<stdio.h>#include<conio.h>void main(){int i;clrscr();for(i=0;i<15;i++)printf(“\nuniversal computer institute”);getch();}

Wap to display the table of 2 using while loop#include<stdio.h>#include<conio.h>

Prepared By: Chetan Thapa Magar ( Brightland Higher Secondary College )www.facebook.com\MeIDoKoXora

Page 16: C programming language Reference Note

C Programming Language

void main(){int a=2.i=1,b;clrscr();while(i<=10){b=a * i;printf(“2*%d=%d\n”,i,b);i++;}getch();}

Wap to display the table of 2 using do-while loop#include<stdio.h>#include<conio.h>void main(){int i=1,b;clrscr();do{b=2*i; i++;printf(“%d\n”,b);i++;}while(i<=10);getch();}

Nested loop:When the body part of the loop contains another loop then the inner loop is

said to be nested within the outer loop. Since a loop may contain other loops within its body, there is no limit of the number of loops that can be nested. In the case of

Prepared By: Chetan Thapa Magar ( Brightland Higher Secondary College )www.facebook.com\MeIDoKoXora

Page 17: C programming language Reference Note

C Programming Language

nested loop, for each value or pass of outer loop, inner loop is completely executed. Thus, inner loop operates/moves fast and outer loop operates slowly. Or loop within the loop is known as nested loop.For example, we can write syntax of nested for loops as;for(counter initialization; test condition;increment/decrement)

{for (counter initialization;test;incr/decr){

statements;}

}

Wap to display multiplication table 1-10#include<stdio.h>#include<conio.h>void main(){int i,j;clrscr();for(i=2;i<=10;i++)for(j=1;j<=10;j++){printf(“%d*%d=%d\t”,i,j,i*j);}printf(“\n”);}getch();)

Wap to display the following pattern** ** * ** * * ** * * * ** * * * * ** * * * * * *

#include<stdio.h>#include<conio.h>void main(){int i, j;

Prepared By: Chetan Thapa Magar ( Brightland Higher Secondary College )www.facebook.com\MeIDoKoXora

Outer loop

Inner loop

Page 18: C programming language Reference Note

C Programming Language

clrscr();for(i=1;i<=7;i++){for(j=1;j<=i;j++){printf(“*”);}printf(“\n”);}getch();}

Special characters:, (comma) & (ampersand). (period) ^ (caret); (semicolon) * (asterisk): (colon) - (minus sign)? (question mark) + (plus sign)‘ (apostrophe) < (less than sign)“ (quotation mark) > (greater than sign)! (exclamation mark) | (vertical bar)/ (forward slash) \ (backward slash)~ (tilde sign) _ (underscore)$ (dollar sign) % (percent sign)( (left parenthesis) ) (right parenthesis)[ (left bracket) ] (right bracket){ (left brace) } (right brace)# (number sing/) hash

Data types:There are four types of data type;

int : This type of data type is used to store the integer value.char: This type of data type is used to store any single character.float : This type of data type is used to store decimal numbers.double: This type of data type is store long range of decimal numbers.

Wap that ask the name of student and marks obtained by him/her in given subjects. Display the percentage of the student assuming full mark 100 for each subject.

#include<stdio.h>#include<conio.h>int main(){

Prepared By: Chetan Thapa Magar ( Brightland Higher Secondary College )www.facebook.com\MeIDoKoXora

Page 19: C programming language Reference Note

C Programming Language

char name[15];float nep,eng,phy,chem.,soc,pop,eco,total,pct;clrscr();printf(“enter the name of student: “);scanf(“%s”,name);printf(“enter marks in seven subject: “);scanf(“%f%f%f%f%f%f%f”,&nep,&eng,&phy,&chem.,&soc,&pop,&eco);total=nep+eng+phy+chem+soc+pop+eco;pct=total/7;printf(“\nthe percentage of %s is : %.2f”,name,pct);getch();}

Note:The statement char name[15]; declares a string variable name which stores

collection of characters (i.e. String is array of characters).

Wap to calculate simple interest when principal, time and rate are given by the user.#include<stdio.h>#include<conio.h>void main(){float p,t,r,i;clrscr();printf(“enter principal in rs :”);scanf(“%f”,&p);printf(“enter time in year :”);scanf(“%f”,&t);printf(“enter rate in percent per anum :”);scanf(“%f”,&r);i=)p*t*r)/100);printf(“the simple interest is : rs. %.2f”,i);getch();}

Data input/output:

The mainly common library functions responsible for input and output operations in c are; getchar(), putchar(), scanf(), printf(), gets() and puts(). The getchar() and putchar() are the functions used to accept a single character from the keyboard and display on the monitor. The scanf() and printf() functions are flexible. They can accept values, characters and strings and using suitable format specifier that can be displayed.

Prepared By: Chetan Thapa Magar ( Brightland Higher Secondary College )www.facebook.com\MeIDoKoXora

Page 20: C programming language Reference Note

C Programming Language

The getchar() function:In this function single character can be entered into the computer using C

library function getchar(). This is a part of the standard i/o library. It returns a single character from the standard input device (keyboard) the function does not require any arguments but empty parentheses must follow the keyword getchar.Character varuabke = getchar();While using getchar() with file handling functions, if an end-of-file condition is encountered with reading a character with the getchar function, the value of the symbolic constant eof will automatically be returned.

Wap to input a character from the keyboard and display.#include<stdio.h>#include<conio.h>void main(){char c;printf(“enter a character: “);c=getchar()

Prepared By: Chetan Thapa Magar ( Brightland Higher Secondary College )www.facebook.com\MeIDoKoXora