Top Banner
ANUBHAV COMPUTER INSTITUTE INDEX SR. NO. TOPIC PAGE NO. 1 Overview of C 5 2 Constant, Variables, and Data type 6 3 Operators and Expressions 12 4 Decision Making and Branching 14 5 Decision Making & looping 21 6 Arrays 25 7 Character Arrays & Strings 29 8 Structures 32 9 User-defined Function 35 10 Pointers 40 1
54
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: c Programming

ANUBHAV COMPUTER INSTITUTE

INDEX

SR. NO. TOPIC PAGE NO.

1 Overview of C 5

2 Constant, Variables, and Data type 6

3 Operators and Expressions 12

4 Decision Making and Branching 14

5 Decision Making & looping 21

6 Arrays 25

7 Character Arrays & Strings 29

8 Structures 32

9 User-defined Function 35

10 Pointers 40

1

Page 2: c Programming

ANUBHAV COMPUTER INSTITUTE

SYLLABUS OF ‘C’ PROGRAMMING

Chapter 1:- Overview of C

a) Fundamental of Computerb) History of Cc) Importance of Cd) Simple programse) Basic structure of C programf) Executing a C program

Chapter 2:- Constant, Variables, and Data type

a) Introductionb) C Tokensc) Keywords and Identifiersd) Constante) Variablesf) Data types g) Declaration of variables

Chapter 3:- Operators and Expressions

a) Introductionb) Arithmetic Operatorc) Relational Operatord) Logical Operatore) Assignment Operatorf) Increment & decrementg) Conditional Operatorh) Bitwise Operatori) Special Operator

Chapter 4:- Decision Making and Branching

a) Introductionb) Decision making with if statementc) Simple if statementd) If-------Else statemente) Nested if---- else statementf) Else if ladderg) Switch()

2

Page 3: c Programming

ANUBHAV COMPUTER INSTITUTE

Chapter 5:- Decision Making & looping

a) Introductionb) For statementc) Jumps in loopsd) Difference between while & Do-whilee) While & Do-while statement

Chapter 6:- Arrays

a) Introductionb) One-dimensional arraysc) Declaration of One-dimensional arraysd) Initialization of one-dimensional arrayse) Two-dimensional arraysf) Initialization two- dimensional arraysg) Multidimensional arrays

Chapter 7:- Character Arrays & Strings

a) Introductionb) Declaration and initializing string variablesc) Reading a simple stringd) Writing a simple stringe) Program using strings

Chapter 8:- User-defined Function

a) Introductionb) Need for user-defined functionc) Built in Function d) Return values & their typee) Function declarationf) Category of functiong) No argument no returnh) Argument with no returni) Argument with return

Chapter 9:- Structures

a) Introductionb) Defining a structurec) Declaring structure variabled) Structure programse) Comparison of structure & unions

3

Page 4: c Programming

ANUBHAV COMPUTER INSTITUTE

Chapter 10:- Pointers

a) Introductionb) Accessing the address of a variablec) Declaring pointer variabled) Accessing a variable through its pointere) Programs using pointers.

4

Page 5: c Programming

ANUBHAV COMPUTER INSTITUTE

‘C’ PROGRAMMING

Chapter 1:- Overview of CPrograms: - These are instruction given to the computer performing different task.Software: - It is a collection of programs. There are two types of Software.

1) System 2) Application

System Software: - It act as a inter face between the user and machine.It monitor at hardware of the softwareIt act as the platform of application software

Operation System E.g.:-window

XPNT

E.g.:-DOS (Disk Operating System)UNIXTranslatorLinkerLoader

Application Software: - This is the ready mate packages for the end user. E.g.:- Ms-Office, DTP, Tally, Games, Songs.Hardware: - These are the touchable part of the computer.Programming Software: - Languages use there is basically there types of programming

Software. 1) Machine languages / binary code or low level language.

Definition: - It contains streams of 0’s and 1’s. The language is only understandable by the computer, the data we enter the computer that all are converting into the code of zero and ones only.

2) Assembly languages: - It contains mnemonics codes.E.g.:- ADD A, B SUB A, B Multi: - AB

This language only use to develop the programs in the microprocessor.

3) High Level language:- This level languages. It contains digits zero to nine Characters small a to z to capital A to Z and special characters plus -, “”, +, *.

Hierarchies of operators: - Level which represents the priority of operator.

Operator Priority %,^,(),*, / I

+, - II

5

Page 6: c Programming

ANUBHAV COMPUTER INSTITUTE

= III Chapter 2:- Constant, Variables, and Data type

Data type / Variables / Constant / keyword

Keyword: - These are the words whose meanings are already defined by the compiler. These are also total 32 keywords available in C.

C keywordsauto double int structbreak else long switch

case enum registertypedefchar extern return unionconst float short unsignedcontinue for signed voiddefault goto sizeof volatiledo if static while

________________________________________________________________________

Constants: - The quantity which does not change during the programmer execution is Called constant. It may be any string constant, integer constant. Variables: - The quality which always changes during the execution of the programmer

is called variable. There are some rules to declare the variable.1) First letter should be alphabet.2) Special characters are not allowed to take as variable name except under score

sign. (-)3) All the variables are going to use in the program should be declare at the starting.4) Keywords are not allowed to take as variable name.5) Variable name should be unique within a program.6) Their data type should be declared with the variables.

Date type: - There are basically 2 types of data types 1) Fundamental2) User defined

1) Fundamental:-

Integer- It only contains the value which does not contain decimal.Number of bytes contains by the integer is 2 bytes

String conversion character is %d. Its symbol used to declare int.

Float- It contains the value having decimal points. For e.g.:- 25.313241.Number of bytes contains by the integer is 4 bytes

String conversion character is %f.

6

Page 7: c Programming

ANUBHAV COMPUTER INSTITUTE

Its symbol used to declare float.

Double: - It also contains the values having decimal but it extends the digits After decimal for e.g.:- 26.12345678910.Number of bytes contains by the integer is 8 bytes

String conversion character is %lf. Its symbol used to declare double.

Character: - If only contains the single character at a time. N I t e s h Number of bytes contains by the integer is 1 bytes

String conversion character is %c. Its symbol used to declare char.

Basic structure of C programs

Documentation section Linking sectionDefinition section Global declaration main ( ) {Local variable declaration executable statement ____________________

__________}

Documentation :- These are the comments given to the program. These lines are ignored by the compiler. It start with slash with as trick (/ *) and closing with the same symbols * with /.

Linking section: - To run the program some libraries are required to link with the program for there execution for e.g.:- # includes<stdio.h>

# include<conio.h> #include<math.h>

Definition Section:-To declare any constant in any program are defined in this section.For e.g.:- # defined PI 3.142

Global declaration: - If you are going to use any variable outside the main function are declared before the main.

main ( ):- This is a user defined function but act as inbuilt function. Execution of a program is always starting with main function.

7

Page 8: c Programming

ANUBHAV COMPUTER INSTITUTE

Local Variables: - These are the variables that are used within the main function.

Printf ():- This is the function use to print any value or string on the screen.

Syntax printf(“string conversion characters”, variable 1, var 2 ………var n);E.g.:- printf(“Welcome to the world of C”); printf (“%d”, c);

Scanf ():-This function is use to read the value from the keyboard to the program.Syntax Scanf (“string conversion character, & var 1, & var 2);

1) /* Program to find the sum of two numbers */

#include<stdio.h>#include<conio.h>main( ){int a,b,c;clrscr( );printf(“Enter the two number\n”);scanf(“%d%d”, &a,&b);c=a+b;printf(“The sum of two no.=%d”,c);getch( );}

2) /* Program to find the sum of two numbers */

# include<stdio.h># include<conio.h>main ( ) {clrscr( );printf(“WELCOME TO THE WORLD OF C “);getch( );}

3) /* Program to find the subtraction of two numbers */

# include<stdio.h># include<coino.h>main ( ){ int a,b,c;

8

Page 9: c Programming

ANUBHAV COMPUTER INSTITUTE

clrscr( );printf (“ Enter the two numbers\ n” );scanf (“ %d %d”, &a,&b);c = a-b;printf ( “The subtraction of two number = %d”,c);getch ( ); }

4) /* Program to find the multiplication of two numbers */

# include<stdio.h># include<conio.h>main( ){int a,b,c;clrscr( );printf(“Enter the two numbers\n”); scanf (“%d%d”, &a,&b);c = a*b;print f (“The multiplication of two numbers = %d “,c);getch( );}

/* Program to find the division of two numbers */

# include<stdio.h># include<conio.h>main( ){int a,b,c;clrscr( ); printf(“Enter the two numbers\n”);scan f ( “%d%d “, &a ,&b);c = a / b;print f (“The division of two numbers = %d”, c);getch ( );}

/* Program to find the area of circle of a number */

# include <stdio.h># include <conio.h>main( ){int a,b,c;

9

Page 10: c Programming

ANUBHAV COMPUTER INSTITUTE

clrscr( );printf(“ Enter the two numbers\n”); scanf(“%d%d “, &a , &b);c = 2 * 3.142 * a;print f (“The area of circle of a number = %d”,c);getch( ); }

/* Program to find the simple interest of a number */

# include<stdio.h># include<conio.h>main( ){float p,r,n,i;clrscr( );printf (“Enter the value of P, N, R\n”);scanf(“%f %f %f”,&p,&r,&n);i=(p*r*n)/100;printf(“The simple interest =%f”,i);getch( );}

/* Program to find the area of a triangle of a number */

# include<stdio.h># include<conio.h>main( ){int b,h,a;clrscr( );printf(“Enter the number\ n”);c =0.5* b* h;printf(“The area of a triangle of a number= %d”,a);getch ( );}

/* Program to find the power of any entered no. */#include<stdio.h>#include<conio.h>#include<math.h>main(){int n, p;

10

Page 11: c Programming

ANUBHAV COMPUTER INSTITUTE

clrscr( );printf(“Enter any no\n”);scanf (“%d”,&n); p=pow(n,5); print f(“The Power of n=%d”,p);getch();}

/* Program to find the square of any no*/

#include<stdio.h>#include<conio.h>#include<math.h>main(){float n,sq;clrscr();printf(“Enter the value of N\n”);scanf (“%f”,&n);sq=sqrt(n);printf(“The square root of no=%f”,sq);getch();}

11

Page 12: c Programming

ANUBHAV COMPUTER INSTITUTE

Chapter 3:- Operators and Expressions

Operator’s available in ‘C’

1. Arithmetic.2. Relational.3. Logical.4. Special.5. Bitwise.6. Conditional.7. Increment / Decrement.8. Assignment.

Arithmetic:-

+ Add - Subtract / Division * Multiplication % Modulus

Relational:-

< Smaller than> Greater than.<= smaller than or equal to

>= grater than or equal to = = equal to! = Not equal to

Logical:-a) And :- (&&) if any of the condition is wrong the whole output is wrong.B) OR :- (||) if any of the condition is correct the output is correct.c) Not:- (!) if value is not equal. Special :-

a) comma :- used to separate the variables (,) .

b) sizeof() :- This returns the no of byte contain by the variable.e.g.:-int a, b;b=sizeof(a);b=2

12

Page 13: c Programming

ANUBHAV COMPUTER INSTITUTE

Bitwise:-

Used to shift the bits form one place to another >> Right shift << Left shift

Conational:-

To compare the more than 1 variable at a time.Syntax:-Var3= (var1 > var2 ?var1: var2); E.g. C= (a>b? a: b)

Increment /Decrement:-

To change the value of the variables.Eg:- Increment post / pre Decrement post / prePost- i++ i-- i=i+5 i=i-5

Pre- ++i --i i+=5 i-=5

13

Page 14: c Programming

ANUBHAV COMPUTER INSTITUTE

Assignment :- Used to assign the value in the variable.

a = 10

------------------------------------------------------------------------------------------------------------------

Chapter 4:- Decision Making and Branching

Control statement: - It represents the flow of execution in the program.1) Sequence2) Conditional 3) Looping

Sequence: - The flow of execution of a program is just by one step to the next step.

Conditional: - The flow of execution of a program is depends upon condition.1) If – simple if

If else Nested ifElse if ladder

2) switch() :- The flow of execution is until & unless is with in loop the condition is true.a) Forb) Whilec) Do-while

If:- Syntax

if (condition) {-------------- }

Next statement

14

Page 15: c Programming

ANUBHAV COMPUTER INSTITUTE

/* Program to find the healthy student in a class*/

# include <stdio.h># include<conio.h>main( ){int count, i ;float weight, height;count = 0;printf(“Enter weight and height for 10 boys\n”);For (i =1;i < =10;i++){scanf(“%f %f”, &weight, & height);if(weight < 50 && height > 170)count = count + 1;}print f (“Number of boys with weight < 50kg\n”);print f (“and height > 170 cm = %d\n”, count);getch();}

Else if:-if (condition){

True }else{

False}

/* Program to find the largest of 2 no. */

#include<stdio.h>#include<conio.h>main( ) {int a, b;printf(“ Enter the value of a & b\n”);scanf(“ %d %d”, &a, &b);if (a > b){printf(“ The largest is A”);{else {printf(“ The largest is B”);

15

Page 16: c Programming

ANUBHAV COMPUTER INSTITUTE

}getch( );}

/* Program whether the number is even or odd */

#include<stdio.h>#include<conio.h>main( ) { int a;printf(“Enter any number\n”);scanf(“%d”, & a);if (a%2 = = 0){printf(“No of even”);}else{printf(“No of add”);}getch( );}

Nested ifSyntax

if(condition(1)) __ True{if(condition(2))—True{True block inner if}else {False part of inner if}}else{Outer if else part}

/* Program to find the largest of 3 numbers */

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

16

Page 17: c Programming

ANUBHAV COMPUTER INSTITUTE

{int a, b, c, large;printf(“Enter a, b, c\n”);scanf(“%d %d %d”, &a , &b, &c);if ( a > b){if (a > c){large = a;}else{large = c;} } else if ( b > c){large=b;}else{large = c;}printf(“The large = % d”,large);getch( );}

Else if ladder :-

Syntax :-if(condition){--------------}else if(condition){--------------}else if(condition){--------------}Next statement

/* Program to find the result of a single student */

17

Page 18: c Programming

ANUBHAV COMPUTER INSTITUTE

#include<stdio.h>#include<conio.h>main( ){int m1, m2, m3, rollnumber;char ch[20];float per,total;printf(“Enter the roll number & name of the student\n”);scanf(“%d %s”, &rollnumber, ch);printf (“Enter the subject marks\n”);scanf(“%d %d %d”, &m1, &m2, &m3);total = m1+m2+m3;per = total/3;printf(“The total = %f\n”, total );scanf(“The percentage = %f\n”, per);if(m1>=35 && m2>=35 && m3>=35){printf (“Pass\n”);}

if( per>=75){printf(“Distinction”);}else if (per>=60){printf (“First class”);}else if (per>=45){printf (“Second class”);}else if (per>=35){printf (“Just pass\n”);{else {printf (“fail”);}getch( );}

Switch:-

switch ( ):- It is built in multi-decision statement.

18

Page 19: c Programming

ANUBHAV COMPUTER INSTITUTE

Syntax:-

switch(expression){case labelname(1) : break;case labelname(2) :break;case labelname(n) : break;default :break;}Next statement

/* Program to manipulate 2 variable using arithmetic operators*/

#include<stdio.h>#include<conio.h>main ( ){int a,b,c, re;clrscr ( );printf (“Enter value of A & B\n”);scanf (“%d%d”, &a, &b);printf(“1-> Add\n”);printf(“2-> SUB\n”);printf(“3-> Mul\n”);printf(“4-> Div\n”);printf(“Enter your choice\n”);scanf(“%d”, &c);switch ( c ){case 1 :re = a+b;printf(“The sum = %d”, re);break;case 2 :re = a – b ;printf(“The substration = %d”, re);break ;case 3 :re = a* b;printf(“The multiplication= %d, re);break;case 4 :re = a/b;printf(“The div = %d”,re);

19

Page 20: c Programming

ANUBHAV COMPUTER INSTITUTE

break;default :printf(“Invalid input\n”);break;}getch( );}

/* Program to do the number of program in a single program using switch statement */

#include<stdio.h>#include<conio.h>main ( ){int c;float p,t,r,ra,b,h,result;clrscr();printf(“1->Simple interest\n”);printf(“2->Area of circle\n”);printf(“3->Area area of tringle\n”);printf(“Enter the choice\n”);scanf(“%d”, &c);switch ( c){case 1 :printf(“Enter the principal,rate& time\n”);scanf(“%f %f %f”, & p, & t, &r);result = ( p * r * t)/100;printf(“the interest = %f”, result);break;case 2 :printf(“Enter the radius of circle\n”);scanf(“%f”, &ra);result = 2 * 3.14 * ra ;printf(“The area = % f ”, result);break;case 3 :printf(“Enter the base & height\n”);scanf(“%f %f”, &b,&h);result = 0.5 * b *h;printf(“The area of tringle = %f”, result);break;default :printf(“Invalid choice\n”);break; }getch ( );}

20

Page 21: c Programming

ANUBHAV COMPUTER INSTITUTE

------------------------------------------------------------------------------------------------------------------

Chapter 5:- Decision Making & looping

Looping:-

When the same number of statements is executed so many time to reduce the unwanted or repeated coding. We use looping statements.

1) For2) While3) Do-while

For:-syntax :-for (initialization ; condition ; increment/decrement ){-----body of loop-----------------------------}Initialization :- The starting value of the variable.For e.g. :- i = 1, i = 0

Condition:- To compare with the last limit.E.g. :- i < = 10

Increment / Decrement: - To change the value of the variableEg :- i ++ / by onei + = 2 i = i + 2 / by two

21

Page 22: c Programming

ANUBHAV COMPUTER INSTITUTE

we change the value of the variable by any value.

/* Program to find the total of even a add count from 1 to value N. */

#include<stdio.h>#include<conio.h>main ( ) {int n, i, ecount = 0, ocount = 0;clrscr( ) ;printf( “Enter the value of n\n”);scanf( “%d”, &n);for (i = 1; i < = n ; i ++)if ( i %2 = = 0){ecount = ecount + 1;}else{ocount = ocount + 1;}printf(“The total even count = %d\n”,ecount);printf(“The total odd count = % d\n”, ocount);getch( );}

/* Program to find the sum of series */

#include<stdio.h>#include<conio.h>main ( ){int n, i, sum = 0;clrscr( );printf(“Enter the value of N\n”);scan f (“%d”, &n);for (i = 1; i <= n; i ++){ sum = sum + i;}printf(“The sum = %d\n”, sum);getch ( );}

Difference between while and do-while statementsWhile Do-while1) It is a looping statement 1) It is a looping statements2) It is entry control loop 2) It is a exit control loop.

22

Page 23: c Programming

ANUBHAV COMPUTER INSTITUTE

3) It first check the condition then 3) It first execute the statement then check i.e. at executes the statement. least once it executes the statement even

if condition is false.4) syntax:- 4)syntax:-initialization initialization while(condition) do

{ { decrement / increment Increment / decrement } } while (condition);

/* Program to print the series from 1 to n using while */#include<stdio.h>#include<conio.h>main() {int i,n;clrscr();printf(“Enter the value of N\n”);scanf(“%d”, &n);i = 1;while(i < = n){printf (“%d\n”, i );i ++ ;}getch();}

Do – while/* Program to print the series from 1 to N using do-while*/

#include<stdio.h>#include<conio.h>main ()i = 1;do{printf (“%d\n”, i);i ++ ;}while ( i< = n) ;getch() ;}

/* Program to find the sum of series */

23

Page 24: c Programming

ANUBHAV COMPUTER INSTITUTE

#include<stdio.h>#include<conio.h>main (){int n, i, sum = 0 ;clrscr();printf(“Enter the value of N/n”);scanf(“%d”, &n);sum = sum + i ; i ++ ;}printf(“The sum = % d\n”, sum);getch();}

/* Program to find the sum using Do while */

#include<stdio.h>#include<conio.h>main(){int n, i , sum = 0clrscr();printf(“Enter the value of N\n”);scan f (“ %d”,&n);i = 1;Do{sum = sum + i ;i ++ ;}while (i < = n) ;printf(“The sum = % d\n”, sum);getch();}

--------------------------------------------------------------------------------------------------

24

Page 25: c Programming

ANUBHAV COMPUTER INSTITUTE

Chapter 6:- Arrays

Arrays

When we want to store more than one, value in a single variable we can use array. It is a user defined variable.Eg:- array, string, pointer, files, structure, function.

Declaration syntax :-Datatype arrayname [size];For eg :- int a [10];

Initialization of arrayint a [] = {10,20,30};int a [2] = {10,20,30,40}/ Invalidint a [10];

/* Program to sort the array elements */

#include<stdio.h>#include<conio.h>main(){int a[10], i, n, t, i;clrscr();

25

Page 26: c Programming

ANUBHAV COMPUTER INSTITUTE

printf(“Enter the value of N\n”);scanf(“%d”, &n);printf(“Enter the array elements”);for (i = 0; i < = n; i ++)scanf(“%d”, &a[i]);for (i = 0; i < = n; i ++) { for (i = i + 1; i < = n; i ++) { if (a[i] > a[i] ) {

t = a[i];a [i] = a [ j ] );a [ j ] = t ;

} } }printf(“The sorted elements are\n”);for(i=0;i<=n;i++){printf(“%d\n”,a[i]);}getch();}

Two dimensional array :-Declaration datatype arrayname[size][size];int a[10] [10];

/* Program to read the two dimensional arrays */

#include<stdio.h>#include<conio.h>main( ){int a[10][10], n, m, i, j;clrscr( );printf(“Enter the value of m &n\n”);scanf (“%d %d”, &m, &n);printf(“Enter the elements of array\n”);for(i = 0; i < = m; i ++)for( j = 0; j < = n; j ++)scanf(“%d”, &a[i][ j] );printf(“The element of array \n”);

26

Page 27: c Programming

ANUBHAV COMPUTER INSTITUTE

for(i = 0; i < = m; i ++){printf(“\n”);for ( j = 0; j < = n; j ++){printf(“%d\t”, a[i][ j] );}} getch( ) ;}

/* Program to read the 2 arrays */

#include<stdio.h>#include<conio.h>main( ){int a[10] [10], b[10] [10], n, m, i, j;clrscr( );printf(“Enter the value of m & n\n”);scanf(“% d %d”, & m,&n);printf(“Enter the elements of A array\n”);for (i = 0; i < = m; i ++)for ( j = 0; j < = n; j ++)scanf (“%d”, & a [i][ j]);printf (“Enter the element of B array\n”);for (i =0; i < = m; i ++)for ( j = 0; j < = n; j ++)scanf (“%d”, &b[i][ j] );printf(“The matrix of A are\n”);for (i = 0; i < = m; i ++){printf (“\n”);printf ( j =0; j < = n; j ++){printf (“%d\t”, a[i][j] );}}printf (“The matrix of B are\n”);for (i = 0; i < = n; i ++){printf (“\n”);for (i = 0; i < = n; i ++){printf (“%d”, b[i][ j] );}}getch ();

27

Page 28: c Programming

ANUBHAV COMPUTER INSTITUTE

}

/* Program to add 2 matrix */

#include<stdio.h>#include<conio.h>main (){int a [10][10] , b[10][10], c[10][10],n, m, i, j;clrscr ();printf (“Enter the value of m & n\n”);scanf (“%d %d”, &m, &n);printf (“Enter the element of A array\n”)for (i = 0; i < = m; i ++)for ( j=0; j < = n; j ++)scanf (“%d’, &a[i][ j] );printf (“Enter the element of B array\n”);for (i = 0; i < = m; i ++)for ( j=0; j < = n; j ++)scanf (“%d”, &b[i] [j] );c [i] [j] = 0;c [i] [j] = a[i] [j] + b[i] [j];printf (“the addition of matrix of A & B are\n”);for (i = o; i < = m; i ++){printf (“\n”);for ( j = o; j < = n; j ++){printf (“%d\t”, c[i][j] );}}getch ();}

------------------------------------------------------------------------------------------------------------------

28

Page 29: c Programming

ANUBHAV COMPUTER INSTITUTE

Chapter 7:- Character Arrays & Strings

STRINGS

Strings :- String is a collection of characters.

Declaration :-char string name[ size];char string [30];char string [] = {“Mumbai”};char string [5] = {“Mumbai”} //invalid

Null character: - It represents the termination of string .It is represented by the character‘\O’Some of Inbuilt string function.strrev( )- Reverse of stringstrcpy( ) – Copy one string to another string.strcat( ) – Concatenation string( adding one string to another).strlen( ) – To find the length of stringstrcmp( ) – Compare 2 string

/* Program to find the string length */

# include<string.h># include<stdio.h># include<conio.h>

29

Page 30: c Programming

ANUBHAV COMPUTER INSTITUTE

main() {int i ;char name[20];clrscr();printf(“Enter the string\n”);scanf (“%s”, name );i = strlen(name); printf(“The length of string = %d”, i );getch ();}

/* Program to copy 2 string */

# include<string.h># include<stdio.h># include<conio.h>main() {char str1[20], str2[20];clrscr();printf(“Enter string one\n”);scanf(“%s”, str1);printf(“Enter string two\n”);scanf(“%s”, str2);strcpy(str1, str2);printf(“The string1 = %s”, str1);printf(“The string2 = %s”, str2);getch();}

/* Program to compare 2 string */

# include<string.h># include<stdio.h># include<conio.h>main() {char str1[20], str2[20];clrscr( );printf(“Enter string one\n”);scanf(“%s”, str1);printf(“Enter string two\n”);scanf(“% s”,str 2”);if (strcmp(str1, str2)= = 0)

30

Page 31: c Programming

ANUBHAV COMPUTER INSTITUTE

{printf (“The string are equal\n”);}else{printf(“The string are not equal\n”); }getch ();}

/* Program to concatenation 2 string */

# include<string.h># include<stdio.h># include<conio.h>main () {char str1[20], str2[20];clrscr();printf(“Enter string one\n”);scanf (“%s”,str1);printf (“Enter string two\n”);scanf (“%s”, str2);strcat(str1, str2);printf (“The string1 = %s”, str1);getch();}

/* Program to reverse the string */

# include<string.h># include<stdio.h># include<conio.h>main () {char str[20];printf(“Enter the string”);scanf(“%s”, str);strrev(str);printf(“The reverse of string %s”, str);getch();}

--------------------------------------------------------------------------------------

31

Page 32: c Programming

ANUBHAV COMPUTER INSTITUTE

Chapter 8:- Structures

Structure

It is a collection of different data types. (Items)It is used to group the variables in single templates called structure name. Structure member can be used with the help of structure variable with dot (.) operators.

Declaration:- Struct structure_name { datatype member 1; datatype member 2; };

main( ){

struct structure name st_variable;

}

Struct is a keyboard and we can take any structure name that is called as templates.The variables declare inside the structure are called as structure elements or members and for accessing there elements outside the structure by using the structure variable with dot opertaor.

Syntax:-St_variable.membername;

32

Page 33: c Programming

ANUBHAV COMPUTER INSTITUTE

/* Program using structure to read the name & marks of 3 subjects and final total & percentage & print them all*/

# include<stdio.h># include<conio.h> Struct student { char name[20] float M1, M2, M3, total, per; };main( ){struct student s;clrscr( );printf (“Enter the name of student\n”);scanf (“%f %f%f ”, s.M1, s.M2, s.M3);total = s.M1 + s.M2 + s.M3;per = s.total/3;printf (“________________________\n”);printf (“Name\t M1\t M2\t M3\t Total \t Per\n”);printf (“________________________\n”);printf (“%s\t %f\t %f\t %f\t %f\t %f”,s.name, s.M1, s.M2, s.M3, s.total, s.per);getch();}

/* Program to illustrate the comparison of structure variables*/

struct class{int number ;char name[20] ;float marks ;};main(){int x ;struct class student1 = {111,“Rao”,72.50};struct class student2 = {222, “Reddy”, 67.00};struct class student3;student3 = student2;x = ((student3.number = = student2.number) &&

(student3.marks = = student2.marks)) ? 1 : 0;if(x = = 1){

printf(“\nstudent2 and student3 are same\n\n”);printf(“%d %s %f\n”, student3.number,

student3.name,

33

Page 34: c Programming

ANUBHAV COMPUTER INSTITUTE

student3.marks);}else printf(“\nstudent 2 and student3 are different\n\n”);getch( );}

Unions

Unions are a concept borrowed from structure and therefore follow the same syntax as structures. However, there is major distinction between them in term of storage. In structures, each member has its own storage location, whereas all the members of a union use the same location. This implies that, although a union may contain many members of different types, it can handle only one member at a time. Like structures, a union can be declared using the keyword union as follows:

union item { int m;float x;char c;} code;

This declares a variable code of type union item. The union contains three members, each with a different data type. However, we can use only one of them at a time. This is due to the fact that only one location is allocated for a union variable, irrespective of its size.

--------------------------------------------------------------------------------------

34

Page 35: c Programming

ANUBHAV COMPUTER INSTITUTE

Chapter 9:- User-defined Function

Function

When the same numbers of statements are coming again and again in the coding then better avoid the unwanted coding because at some limit the c compiler becomes unable to compile coding simultaneously.

So, with the help of functions we can avoid the repeating coding.Functions are used to reduce the length of a program & it also makes the program run fast.There are two types of functions.

1) Built in2) User-defined

Built in:- There are function that are already stored in header file (libraries).Eg:- printf(), scanf(), pow(), sqrt(), clrscr(), getch(), return() etc. User-defined function:- Function that are written by the user for performing any specific task in the computer.Declaration :-returntype function_name (argument list){ body of function}

Retuntype:- When called function to calling function the values is pass then we have to inform to the compiler of its type. It may any datatype.Function:- Calling function & calling function should have a save name.

35

Page 36: c Programming

ANUBHAV COMPUTER INSTITUTE

Argument list:- It is also called or parament, 1) No argument no return2) Argument no return3) Argument with return

1)/* Program to find the sum of 2 numbers*/#include<stdio.h>#include<conio.h>main ( ) {sum ( );}sum ( ){int a, b, c;clrecr( );printf (“Enter the value of a & b\n”);scanf (“%d %d”, &a, &b);c = a + bprintf (“The sum = %d”, c);getch( );}

/* Program to find the sum of 2 nos using argument with no return value with function */#include<stdio.h>

Calling fun Called fun

No argument

No return

Calling fun Called fun

Argument

No return

Calling fun Called fun

Argument

Return

36

Page 37: c Programming

ANUBHAV COMPUTER INSTITUTE

#include<conio.h>main ( ){int a, b;printf(“Enter the value of a & b\n”);scanf (“%d %d”, &a, &b);sum (a, b);}sum (int a, int b){int c;c = a + b;printf ( The sum = %d”, c);getch( );}

/* Program to find the sum of 2 nos using argument with no return value with function */#include<stdio.h>#include<conio.h>main( ){int a,b,c;printf(“Enter the value of a & b\n”);scanf (“%d %d”, &a, &b);c = sum(a, b);printf(“The sum = %d”, c);}sum (int a, int b){int c;c = a + b;return(c);}

/* Program to write the program with multiple functions that do not communicate any data between them */

#include<stdio.h>#include<conio.h>void printline (void) ;void value (void);main ( ){printline();value ()printline();}

37

Page 38: c Programming

ANUBHAV COMPUTER INSTITUTE

/* Functional: printline( ) */void printline (void) /* contains no arguments */{int i ;for (i = 1; i < = 35; i ++)printf (“%c”, ‘-’);printf (“\n”);}/* Function2: value() */void value (void) /*contains no arguments */{int year, period;float inrate, sum, principal;printf (“Principal amount ?”);scanf (“%f”, &principal);printf (“Interest rate?”);scanf(“%f”, &inrate);printf (“Period?”);scanf (“%d”, &period);sum = principal ;year = 1;while (year < = period){sum = sum *(1 + inrate);year = year + 1;}printf (“\n%8.2f %5.2f %5d %12.2f\n” principal, inrate, period, sum);}

/* Program to modify the program include the arguments in the function calls. */

#include<stdio.h>#include<conio.h>void printline (char c);void value (float, float, int);main( ){float principal, inrate;int period;printf (“Enter principal amount, interest”);printf (“Rate, and Period \n”);scanf (“%f %f %d”, &principal, &inrate, &period);printline (‘Z’);value (principal, inrate, period);printline (‘C’);}void printline (char ch){

38

Page 39: c Programming

ANUBHAV COMPUTER INSTITUTE

int i ;for (i = 1; i , = 52; i ++) printf (“%c”, &ch);printf (“\n”);}void value (float p, float r, int n){int year;float sum;sum = p;year = 1;while (year < = n){sum = sum * (1 + r);year = year + 1;}printf (“%f\t %f\t %d\t %f\n”, p, r, n, sum);}

/* Program to modify the function value to return the final amount calculated to the main, which will display the required output at the terminal. */

#include<stdio.h>#include<conio.h>void printline ( char ch, int len);value (float, float, int);main (){float principal, inrate, amount;int period;printf (“Enter principal amount, interest”);printf ( “rate, and period\n”);scanf (%f %f %d”, &principal, inrate, period);printline (‘*’, 52);amount = value (principal, inrate, period);printf (“\n%f\t %f\t %d\t %f \n\n”, principal, inrate, period, amount);printline ( ‘=’, 52);}void printline (char ch, int len){int i;for (i = 1; i < = len; i ++) printf (“%c”, ch);printf (“\n”);}value (float p, float r, int n) /* default return type*/{int year;float sum;

39

Page 40: c Programming

ANUBHAV COMPUTER INSTITUTE

sum = p; year = 1;while (year < = n){sum = sum * (l + r);year = year + 1;}return(sum); /* return int part of sum */}

--------------------------------------------------------------------------------------

Chapter 10:- Pointers

Pointers

A pointer is a derived data type in C. It is built from one of the fundamental data types available in C. Pointers contain memory addresses as their values. Since these memory addresses as their value. Since these memory addresses are the locations in the computer memory where program instructions and data are stored, pointers can be used to access and manipulate data stored in the memory.Pointers are used frequently in C, as they offer a number of benefits to the programmers. They include:

1) Pointers are more efficient in handling arrays and data tables.2) Pointers can be used to return multiple values from a function via function arguments.3) Pointers permit references to functions and thereby facilitating passing of functions as

arguments to other functions.4) The use of pointer arrays to character strings results in saving of data storage space in

memory.5) Pointers allow C to support dynamic memory management.6) Pointers provide an efficient tool for manipulating dynamic data structures, linked lists,

queues, stacks and trees.7) Pointers reduce length and complexity of programs.8) They increase the execution speed and thus reduce the program execution time.

int quantity = 179; how to declare pointers

datatype *pointer_name ; eg. int *ptr;

40

Page 41: c Programming

ANUBHAV COMPUTER INSTITUTE

ptr=&quantity

Address of the variable quantity will be intitalise to the pointer variable ptr.Note:- The datatype of the pointer variable should be same as the type of the variable.

/* Program to print the address of a variable along with its value */

#include<stdio.h>#include<conio.h>main (){char a;int x;float p, q;a = ‘A’;x = 125;p = 10.25, q = 18.76;printf (“%c is stored at addr %u.\n”, a, &a);printf (“%d is stored at addr %u.\n”, x, &x);printf (“%f is stored at addr %u.\n”, p, &p); printf (“%f is stored at addr %u.\n”, q, &q);getch( );}

Initialization of pointer variablesint quatity;int *p; /* declaration */p = &quantity; /* initialization */

int *p = &quantity;

float a, b;int x, *p;p = &a; /* wrong */b = *p;

/* Program to illustrate the use of indirection operator ‘*’ to access the value pointed to by a printer */

#include<stdio.h>#include<conio.h>main (){int x, y;int *ptr;x = 10;

41

Page 42: c Programming

ANUBHAV COMPUTER INSTITUTE

ptr = &x;y = *ptr;printf (“Value of x is %d\n\n”, x);printf (“%d is stored at addr %u\n”, x, &x);printf (“%d is stored at addr %u\n”, *&x, &x);printf (“%d is stored at addr %u\n”, *ptr, ptr);printf (“%d is stored at addr %u\n”, ptr, &ptr);printf (“%d is stored at addr %u\n”, y, &y);*ptr = 25printf (“\nNow x = %d\n”, x);getch();}

/* Program to illustrate the use of pointers in arithmetic operations.*/

#include<stdio.h>#include<conio.h>main( ){int a, b, *p1, *p2, x, y, z;a = 12;b = 4;p1 = &a;p2 = &b;x = *p1 * *p2 – 6;y = 4* - *p2/ *p1 + 10;printf (“Address of a = %u\n”, p1);printf (“Address of b = %u\n”, p2);printf (“\n”);printf (“a = %d, b = %d\n”, a, b);printf ((“x = %d, y = %d\n”, x, y);*p2 = *p2 + 3;*p1 = *p2 – 5;z = *p1 * *p2 – 6;printf (“\na = %d, b = %d”, a, b);printf (“z = %d \n”, z);getch();}

/* Program using pointers to compute the sum of all elements stored in an array.*/

#include<stdio.h>#include<conio.h>main( ) {int *p, sum, i ;int x [5] = {5, 9, 6, 3, 7};

42

Page 43: c Programming

ANUBHAV COMPUTER INSTITUTE

i = 0;p = x; /* initializing with base address of x */printf (“Element Value Address\n\n”);while (i < 5){printf (“x[%d] %d %u\n”, i, *p, p);sum = sum + *p; /* accessing array element */i++, p++; /* incrementing pointer */}printf (“\n Sum = %d\n”, sum);printf (“\n &x [0] = %u\n”, &x [0] );printf (“\n p = %u\n”, p);getch();}

___________________________________________________________________________

43