54
Software: - Software is a program or collection of programs. This software divided into 2 parts 1)packages 2)languages 1)Packages:- A package is set of predefined program or commands e.g.:- ms-office 2)languages:- A language is a set of Characters arranged in a meaningful format or in systematic order. This language further classified into 2 types. 1) Low level language: - A language whose instructional format is near to the machine understandable language is called low level language. E.g.: - Ada. High level language: -

c Language

Embed Size (px)

Citation preview

Page 1: c Language

Software: -Software is a program or collection of programs.This software divided into 2 parts1)packages2)languages1)Packages:-A package is set of predefined program or commands

e.g.:- ms-office

2)languages:-A language is a set of Characters arranged in a meaningful format or in systematic order.This language further classified into 2 types.1) Low level language: -A language whose instructional format is near to the machine understandable language is called low level language. E.g.: -

Ada.High level language: -A language whose instructional format is near to the user understandable language is known as high level language.E.g.: -

COBOL ,PASCAL ,FORTRAN ,JavaMiddle level language:-A language, which supports both low level and high level languages, is known as Middle level language.

e.g.:- C,C++

Evaluation of c:-

Page 2: c Language

In earlier days there was 2 languages COBOL was the language used for commercial applications and FORTRAN was the language used for scientific calculations .Then Computer Scientists thought for a language which is the complete replacement of FORTRAN & COBOL .In this procedure ALGOL was the first step .It was not up to the mark of user requirements .In Next BCPL(Basic Combined Programming Language) was the language, But it was failed to replace the previous languages. Ken Thompson introduced a language which is the complete replacement of FORTRAN & COBOL .He named his language with First alphabet of BCPL as B-language, But it is Interpreter based language.In 1972 Dennis Rich working at AT & T Bell laboratories in U.S.A introduced a language which is the complete replacement of FORTRAN & COBOL and it is purely compiler based language, he named his language with second alphabet of BCPL as C-language.

Translators: -Translators are the mediators between user and system that can used to translate the information from one form to another form.Following are the translators: -1) Interpreter: -Compile the program line by line.2) Compiler: -Compile the total program at a time and displays a message box with errors and warnings.

Features of C-language: -

Page 3: c Language

1) It is Compiler based language.2) It is a Middle level language.3) C is a Structure oriented language.4) C allows programming at bit level.5) C is function-oriented language.6) C allows user his own compilers, interpreters, functions…7) Programming approach is from top to down.8) It is case sensitive language.

Character set: -A-Z, a-z characters0-9 numbersSpecial characters like [ ],{ },( ),#,&,..............

Words: -There are two types of words1) Reserved words: -A word, which defined by the developers for the support of user is known as Reserved Words.e.g.:- int ,float, goto ,break ,void ,char ,long ,double ,.............2) User defined words:-A word which defined by the User according to his program is known as User defined words.E.g.: -rno ,name , course,.........Note: -

Page 4: c Language

A Reserved word can not be considered as a user defined word.

Function:-A function is a subprogram with set of statements to do a specific task.there are two types of functions in c.1)Library functions:-The functions which are developed by the developers for the support of user are known as library functions.

e.g.:-SQRT() ,POW() ,.........

2)User defined functions:-The functions which are developed by the User According to his program are known as user defined functions.

e.g.:-Add(),Sub(),.........

Structure of the C-language.In Every program language has written in a form,

which is followed by its compiler.Following is the structure of the C.1)Documentation Section.In this section we can write following propertiesi) Title of the programii) User addressiii) Instructionsiv) Logic used in the programv) Created Date & Time.

Page 5: c Language

The above mentioned information need not to be converted into machine language(0's and 1's).So that this will be given b/w comments like follows/* .............. Statements ................................ */2) Linkage section.

In this section we have to link some header files with our program. A header file is a group of several library functions.E.g.: -#include<stdio.h>stdio.hstandard input and output header file#include<conio.h>conio.hconsole input and output header file

#include<math.h>

3) Declaration section.In this section we have to declare constants, user

defined functions, macros,....E.g.: -Declaring a constant# define pi 3.144) Global variables.In this section we can declare the global variables.int i=0;5) Main section.

The name itself indicates this is the main section for every program.Main includes following 2 parts1) Declaration of variables

Page 6: c Language

2) Executable statementsStructure:-

main() {

Declaration of variables;Executable statements;

}

6) Subprogram section.In this section we can define and design the user defined functions.

INPUT and OUT functionsprintf( ):-This function is used to print any messages on the screen

syn:-printf("Message");

Write a Program to print the message as Wel -Come to C

/*This is my First program*/#include<stdio.h>main(){ printf("Welcome to C");}

Page 7: c Language

Alt+F9 -----> To compile the programCtrl+F9 -----> To Run the ProgramAlt+F5 -----> To See the Results of the program.

To open C: -Click On Start MenuClick on RunType as c:\tc\bin\tcAnd click on ok.

* Write a program to print the user address./* User Address */#include<stdio.h>main(){printf("Vara Prasad");printf("# 16-1-538");printf("Hanamkonda");printf("Hyderabad");}

Escape sequence characters:-\n --------> to move the cursor to New line\t --------> To Produce the horizontal tab.\b --------> For Backspace\a --------> For Beep sound\\ --------> For "\"

Page 8: c Language

\" --------> For double codes(")

clrscr( ):-This function is used to clear the previous output of

the program. It is available in a header file called "conio.h"*write a program to implement the Esc in the program.

/*Escape Sequence characters */#include<stdio.h>#include<conio.h>main(){ clrscr(); printf("Softech"); printf("\n\tSoftech"); printf("\n\\softech\\"); printf("\n\"Softech\""); printf("\n\bSoftech"); printf("\ns\boftech");}o/p:- Softech

Softech \Softech\ "Softech" Softech OftechVariable:-

A variable is a memory location whose value changes from time to time.

Constant: -

Page 9: c Language

A constant is a memory location whose value does not change at any time.Data types: -A data type is type of the data that is which type of values we can store in to the respective variables int: -This data type allows integer values only range starts from -32768 to 32767.it occupies 2B of space.short int: -This data type allows integer values only range is less than that of "int". It occupies 2B of space.long int :-This data type allows integer values only range is greater than that of "int". It occupies 4B of space.float: -This data type allows decimal numbers. It occupies 4B of space.char:-This data type allows characters. It occupies 1B of space.

Syntax for declaring a variable:-

Datatype var1, var2, var3,.....;

Formatted i/p and o/p functions:-

printf():-(o/p function)This function is used to print any messages or

values of the variables.syn:-

Page 10: c Language

printf("Formatstrings/Messages",variables);

scanf():-(i/p function)This function is used to accept the values in to the respective variables at Run Time

syn:- scanf("Formatstrings",&var1,&var2,....); Here '&' indicates address of the respective variables.

Format strings: -

Data type Format stringsInt %d

short int %sdlong int %ld

Float %fChar %c

String(group of chars) %S

Write a program to calculate the addition of the 2 values.

Write a program to calculate the addition of the 2 values accept the values at run time.

Operators In C:-1) Arithmetical Operators:-

Page 11: c Language

These operators are used to perform all mathematical calculations.

Operator Description+ Addition- Subtraction* Multiplication/ Division (Quotient)

% Division (Remainder)

2) Unary/Binary Operators:-Unary: -

If an operand or variable is given with a single operator then it is called Unary operator.

e.g.:- a+, a-,.....

Binary: -If a single operator is given with 2 operands or 2

variables then it is called as binary operator.e.g.:- a+b, a-b, a*b, ...........

3) Relational operators(Comparison Operators):-These operators are used to provide the relation

ships or to compare the values of the variables.

Operator Description

Page 12: c Language

< Less than > Greater than

>= Greater than or equal <= Less than or equal

= = Equal to != Not Equal to

4) Assignment Operator:-(=)This Operator Assigns or store the value or

expression result to the left side variable.eg:-

a=10;It reads as "a assigns 10"5) conditional operator:- ( ? :) This operator is used to give condition to the values or expression for two or more operands .

Syntax :- variable1>variable2 ? true statement : false statement Ex :- a>b? printf(“A is big “): printf(“ b is big”);

Write a program to calculate area and perimeter of the circle.

Write a program to perform all binary operations

Wap to swap the given two values.

Page 13: c Language

Wap to swap the given two values with out using the third variable

sizeof():-This function is used to return the size of the specified

variable /data type.

Write a program to print the sizes of the all data types.

Wap to calculate the addition of the given 2 digit number.

Unformated i/p and o/p functions:-This functions are not allow the format stringsi/p functions:-1)getch():-this function is used to accept the character in to the respective variable at run time which is not visible.syn:- char_var=getch();2)getchar():-this function is used to accept the character in to the respective variable at run time which is visible.syn:- char_var=getchar();o/p functions:-1)putch():-This function is used to print the character of the respective variable on the screen .It will not allow any Escape sequence character. syn:-

Page 14: c Language

putch(char_var);2)putchar():-This function is used to print the character of the respective variable on the screen .It will allow the Escape sequence characters. syn:- putchar(char_var);

Unformated i/p and o/p string functions:-1)puts():-This function is used to print the string on the screen.syn:- puts("String");2)gets():-This function is used to accept a string in to the respective variable.syn:- gets(String_var);* write a program to implement Unformated i/p nad o/p functions in the program.

getch():-This function is used to sgive the pause to User at run time.

Control Structures:-

Page 15: c Language

These Structures are used control the compiler at run time and execute the statements according to the given conditions.These are 2 types1) Conditional Structures2) Iterative Structures (or loops)

Conditional Structures: - These Structures are executing the statements depending up on given condition. There are following 4 types of conditional statements.simple if if .. elseNested if (If With In The If)else..if (lader if)

1) Simple if:-Structure: -if (condition){ statements; }

In the above structure the statements are executed when the specified condition is true otherwise control avoids the statements from execution.2) if..else:-

Structure: -if(condition){ statemetns1; }

Page 16: c Language

else{ statemetns2;}

In the above structure if specified condition is true then statements1 are executed other wise statements2 are executed.

Write a program to print big number in given 2 numbers using simple if.

Write a program to find whether the given number is positive or negative.

Note: -1) Every control statement will not terminated by

semicolon (;).2) Boundaries({, }) are compulsory for multiple

statements, but these are optional for single statement.

Write a Program to find whether the user is eligible for vote or not

Nested if: -If a simple if..else statement is given with in another if then it is called Nested if.

Page 17: c Language

Structure: -if(con-1)100>p{ if(con-2)50>p statemetns1; else statemetns2;}else{ if(con-1) statements3; else

staments4; }In the above structure if con-1 is true then

control will enter into the if block. If con-2 is true then statements1 are executed other wise it will execute statemetns2, but the statements3 &4are executed when con-1 is false.

else if ladder: -If a simple if ..else statement is given with in the else block then it is called else if ladder.

Structure: -if(con-1) statemetns1;else if(con-2) statemetns2;else

Page 18: c Language

statemetns3;

In the above structure if con-1 is true then control will execute statemetns1 other wise control will enter into the else block, here if con-2 is true then control will execute statemnts2 other wise statements3. Write a program to find the big number in given 3

numbers.

Logical operators: -These operators are used to join the number of

conditions and returns result as either true or falseFollowing are the logical operators:-1)and(&&)2)or (||) 3) Not(!)

1) And(&&)This operator joins the number of conditions and returns result as True when all the given conditions are true otherwise it returns false.Truth table: -

P Q P&&Q1 0 00 1 00 0 0

Page 19: c Language

1 1 12)Or(||):-This operator join the number of conditions and returns result as True when all the given conditions or any one of the given conditions is true otherwise it returns false.truth table:-

P Q p||q1 0 10 1 10 0 01 1 1

3)Not(!):-This operator joins the number of conditions and returns result as True when all the given conditions are false otherwise it returns false.truth table:-

p !p1 00 1

Write a program to find the big number in given 3digit number.

Write a program to calculate the Bill amount of the Consumer according to the following conditions.

Amount Discount

Page 20: c Language

<3000 3% >=3000 and <5000 4% >=5000 and <10000 5%

>=10000 6%input values are qty and rate.

Write a program to find the net salary of person According to the following conditions.

Basicsal Bonus------------------- ---------Up to 5000 12.345%

Above 5000 and Up to 10000 14.234%Above 10000 and Up to 30000 16.534%

Above 30000 17%

Wap to calculate the bill of the customer according to the following table.

Type Of the Room Per Day Charge ------------------------- --------------------- Ordinary 250 Deluxe 300 Ac 400

Write a program to calculate the student results. Wap to find whether the given character is vowel or

consonant

Page 21: c Language

Switch-CaseBy using conditional statements we can provide one

condition or group of conditions only. This will cause for complexity of the program. To avoid this complexity we have to use "switch case". A switch case is a control statement that can provide no.of cases or Comparisons /conditions to execute the statements in the program. Structure:- switch(variable) {

case 1:statements1;break;case 2:statements2;break;.........case n:statementsnbreak;default:

}In the above structure the value of the variable

matched with any one of the given cases that respective statements are executed, other wise control will execute the default statements. Here "break" statement is given b/w the cases to break the continuity of the switch-case. Wap to illustrate the switch-case concept.

Unformated i/p and o/p string functions:-1)puts():-

Page 22: c Language

This function is used to print the string on the screen in a new linesyn:- puts("String");2)gets():-This function is used to accept a string in to the respective String variable.syn:- gets(String_var); Wap to perform all arithmetical operations using

switch case. Wap to perform all arithmetical operations by

accepting arithmetical operator. Wap to find whether the given character is vowel or

consonant using switch case.

Conditional Operator ( Ternary Operator) This operator works, same like as simple if ..else statement.syn:-

(condition)?truevar/truemsg :falsevar/falsemsg;e.g.:-a=20 b=40a=(a>b)?a:b; c=(a<b)?a:b;40 20 Wap to find whether the given number is odd or

even. Wap to find the big number in given 2 numbers using

conditional operator.

Page 23: c Language

goto:-It is iterative statement used to move the cursor

position to the specified label name. To avoid the infinite loops we have to provide proper conditions.

syn:-goto labelname;

* wap to print n natural numbers.

Increment operators:-(++)This operator increments the value of the variable by one.1) Post increment operator (a++)This operator first assigns the value and then increment the value.e.g.:-a=10;p=a++;p a[10] [11]2) Pre Increment Operator:-(++a)This operator first increments the value and after words assigns the value.eg:-a=10;p=++a;p a[11] [11]

Page 24: c Language

Decrement operator: -This operator Decrements the value of the variable by one.1) Post decrement operator (a--)This operator first assigns the value and then Decrement the value.eg:-a=10;p=a--;p a[10][9]2) Pre Decrement Operator:-(--a)This operator first decrements the value and after words assigns the value.eg:-a=10;p=--a;p a[9] [9]Compound Assignment (Assignment) Operator:-a=a+b ------> a+=b;a=a-b ------> a-=b;a=a*b ------> a*=b;a=a/b ------> a/=b;a=a%b ------> a%=b; Wap to implement Increment and Decrement

Operators.

Page 25: c Language

Iterative statements(loops):-this statements are controll statements used to

repeat the set of statements for n number of times.there are following 3 types of loops1)for2)while3)do..whileFor:-

sturcture:- for(initializaton;condition;Incr/Decr) { statements; }

In the above structure Controll first enter into the initialization part.Next check for the result of the condition, if it is true it will executes the statements.Next it moves to the Incr/Decr position and again check for the result of the condition if it is true agian it execute the statements.This procedure will continue until the given condition is false.* wap to print the n natural numbers.* write a program to print mathamatical table for a given number*wap to print even numbers in given range of numbers.*wap to print factors of the given number and find whether it is prime or not.

Nested For:-

Page 26: c Language

if a for loop is given with another for loop is called as nested foreg:-for(i=1;i<=n;i++){ for(j=1;j<=m;j++)

statemetns;}here the statements are executed for m*n number of times.*wap to print mathematical table.*wap to print following design

* ** *** ****

while():-structure:-while(condition){

statements; }

In the above structure compiler check for the result of the condition if it is true then it execute the statements

Page 27: c Language

again check for the result of the condition if it is true again it execute the statements.This procedure will continue until the given condition is false.*wap to print the n natural numbers.main(){int n,i;clrscr();printf("Enter any Number");scanf("%d",&n);i=1;while(i<=n){printf("%d\t",i);i++;}getch();}*wap to find the given number is perfect or not.*wap to find the factorial of the given number.*wap to print the given number in reverse order and find whether it is pollindrome or not.

do..while():-structure:-

do{ statements; }while(condition);

Page 28: c Language

in the above structure for first time the statements are executed with out any condition.Next it check for the result of the condition if it is true again it execute the statements .This procedure will continue until the given condition is false.points to remember:-1)A do..while statement is end with semicolon(;)2)The condition is given at ending level.3)For single statement or for multiple staements boundaries are compalsery.*wap to print the n natural numbers.#include<stdio.h>#include<conio.h>main(){int n,i;clrscr();printf("Enter n value");scanf("%d",&n);i=1;do{printf("%d\t",i);i++;}while(i<=n);getch();}*wap tp print the n natural numbers in page wise.

Arrays:-

Page 29: c Language

According to user program he has to declare no.of Variables. this is a problem to the user to access those variables in the program this will produce complexity of the program. To avoid this user has to implement arrays concept. An array is a group of similar data elements. Array store number of values. To access the array elements we have to subscript reference.Types of Arrays:-1)single dimensional arrays2)Double dimensional arrays3)Multi dimensional arrays1)single dimensional array:-In this type of array we can store the values in a single dimension that is linearly.syn:- datatype Array_name[size];eg:-

int a[5];we can store 5 values .

* wap to accept 10 values into an array and print them*wap to accept the n values into an array and print their sum and average..*wap accept the n values into an array and find big number in the array.*wap to find whether the searching element is found or not in an array.(linear search)write a program to arrange the values of the array in ascending order.(Bubble sort)2)Double dimensional arrays

Page 30: c Language

In this type of array we can store the values in two dimensionsthat is in matrix form.syn:-data_type Array_name[size1][size2];eg:-int a[3][3];we can store 9 values.wap to accept 9 values in to double dimension array and print them in Matrix Formwap to print the traspose matrix of given matrix.wap to calculate the sum of the diagonal matrix and print it.[00 01 02][00 01 02][10 11 12][10 11 12][20 21 22][20 21 22]a[3][3],b[3][3],c[3][3]c[i][j]=a[i][j]+b[i][j];c[i][j]=a[i][j]-b[i][j];

wap to print upper triangle matrix and lower triangle matrixwap to calculate the sum of the given two matrix

-:Pointers:-

Page 31: c Language

In previous programs we access the variables through its name or identifier, but to access these variables through its address is the concept of pointers.we note that a variable can not assings address of the other variables.There is one and only one variable that can holds the address of the other variables that is pointer variable.Allways a pointer variable prefixed with " * ".1)Declaring a pointer variable int *var;2)Assigning adress of the other variablesint a,*p;p=&a;3)Access the pointer variable i)To print the value "*p"; ii)To print the assinged address "p"1)wap to implement the pointers concept2)wap to calculate sum using pointers3)swap the 2 values using pointers4)wap to implement the pointers concept with arrays.

StringsA string is defined as group of characters and it is

single dimensional character array .sometimes user needs to manipulate with the strings for this purpose there are several strings functions are available in a header file called "string .h".*declaring a string in the programchar str_name[size];eg:-char name[10];

Page 32: c Language

wap to print given string some of the available string functions are 1)strlen():-this function returns string lengthsyn:-

strlen(string1);2)strcmp():-Compares the 2 stringssyn:-

strcmp(string1,string2);if string1==string2 then it returns 0if string1>string2 then it returns 1if string1<string2 then it returns -13)strcpy():-

th is function copies second string into the first string

syn:-strcpy(string1,string2);4)strlwr():-this function returns given string in lower case letterssyn:-

strlwr(string1);5)strupr():-this function returns given string in upper case letterssyn:-strupr(string1);6)strcat():-this function adds the 2 stringssyn:-strcat(string1,string2);7)strrev():-this function reverse the given string.syn:-

Page 33: c Language

strrev(string);1)wap to print the given string in lower case,upper case,reverse order and its length.2)wap to find whether the given string is pollindrome or not .Note:-Allways a string can be end with a null character.it is indecated by '\0'.3)wap to print the length of the given string and print it in reverse order with out using string functions.4)wap to find whether the given string is pollindrome or not with out using string functions.5)wap to print the given string in lower case letters and upper case letters with out using string functions.6)wap to print the ASCII symbols

Functions:-A function is a subprogram with set of statemets to do a specific task.C allows user to define and design his own functions.To implement functions conceptwe have to follow following 3 steps1)Declaration of function will be at declaration section that is before main sectionsyn:-

return_type Fun_name(arguments);2)Coading part of the function will be at sub program section that is after main.syn:-

return_type Fun_name(arguments)

Page 34: c Language

{ functon body; return value; }

3)Calling of the function will be in the main sectionsyn:-

Fun_name(arguments);

return type:-Return type is the data type that is which type of value the function can return.Fun_name:-To identify or to access this function a suitabale name is given for it is known as Function name.arguments:-Argumetns are nothing but variables that can invoke the funtion in the main program.Functon body:-Executable statements of the function given as function body.return value:-After the execution of the function the final result can be given as return value.local variable:-A variable which is declared with in the boundaries and that can accessable with in the boundaries only , is called as local variable.Global variable:-A variable which accessable at any where in the program is called Global variable.

Page 35: c Language

1)wap to implement the functions concept and print message as "This is Functions Concept".2)wap to calculate the addition of the 2 values using functions concept3)wap to print the mathematical table for given number. using functions concept.4)wap to print the factorial of the given number and return the result.

5)wap to calculate the simple interest .6)wap to print big number.call by value:-Call the function by values of the variables is called as "call by value".eg:-the previously discussed programs in functions concept are all examples for "call by value"call by reference:-Call the function by address of the variables is called as call by reference.eg:-*wap to swap the given 2 values using call by reference.*wap to pass the array values to a function.

-:Structures:-A structure is a secondary data type and it also

considered as user diffident datatype that can synchronize or group the primary data types such as int,float,char,........

Page 36: c Language

Using this structures we can maintain the records.To declare a structure we have to use a key word called "struct".The declaration will be in declaration section.

syn:-struct struct_name { datatype1 ele1; datatype2 ele2; .......................... };

Declaring a structure variable struct struct_name struct_var;Acessing Structure elements:- struct_var.ele1;eg:-1)Declaring a structure for student details

struct student { int rno; float fee;

};2)Declaring a structure variable

struct student rec;3)Accessing student elements; rec.rno=1234;

rec.fee=7500;1)wap to implement structure concept2)wap to calculate the student results using structures concept.Points To remember:-

Page 37: c Language

1)A structure variable can occupy the size as the total of size of structure elements.2)A structure works same like as single dimensional array.

3)wap to print the size of the given structure.4)wap to print the array values and accept the values in to array at the time of declaration.5)wap to prove structure works like an array.6)wap to implement structures concept with functions. 7)wap to implement structures concept with arrays.

-:Files:-A file is a collection of information.We can also create the files using c programming and store the information on specified file.To implement this concept we have to declare a file pointer.declaring a file pointer:-FILE *fp;To open a file following statement is used fp=fopen("filename","mode");To close a file:- fclose(fp);Different types of file modes:-r ---->to open a file in read mode and to read the informationw ----->To open a file to write mode and write information on to a file.a ----->To open a file in append mode and to extend the information of a file.Types of files:-

Page 38: c Language

There are 3 types of files 1)text files2)sequensional files3)Random files

putc():-this function puts a character on to a specified file. syn:- putc(char_var,fp)getc():-this function gets a character from a specified file. syn:- char_var=getc(fp);EOF:-this key word indicates the end of the file.*wap to create a text file*wap to read the information of a text file called text1.txt and count the no.of characters,no.of occurrences of 'a'.*wap to read the information of a file and accept the file name at run time.

fprintf():-This function is used to print the formatted o/p's on to a specified file.

syn:-fprintf(filepointer,"format strings",variables);

fscanf():-This function is used accept the information of the specified file in to the respective variables.

Page 39: c Language

syn:-fscanf(filepointer,"format strings",address of

the variables);feof():-This function states that the sequensional file or random file is at end position or not.if file is at end position then it returns true(1)if file is not at end position then it returns false(0)

syn:- feof(filepointer)

*wap to create a sequensional file.*wap to read a sequensional file called "stud.dat".*wap to display the records of a student of a file called "stud.dat" of given rnofread():-This function is used to read the information of a specified random file record by record.syn:-

fread(&struct_var,sizeof(struct_var),no.ofstructures,filepointer);fwrite():-This function is used to write the information on to a specified random file record by record.syn:-

fwrite(&struct_var,sizeof(struct_var),no.ofstructures,filepointer);*wap to create random file to store the product details*wap to read the random file called prod.dat record by record*wap to demo on colors in C.

Page 40: c Language

*wap to create the window.*wap to create a smile face.