C programming notes batracomputercentre

Page 1

C PROGRAMMING NOTES

September 1 2015

MOVE FORWORD WITH YOUR BEST EDUCATION

BATRA COMPUTER CENTRE

WEBSITE:-WWW.BATRACOMPUTERCENTRE Facebook :- fb.com/batracomputercoachingcentre

PHN NO:8950829990,9729666670, 0171-400670


INTRODUCTION OF C C is a general-purpose high level language that was originally developed by Dennis Ritchie for the UNIX operating system. It was first implemented on the Digital Equipment Corporation PDP-11 computer in 1972. The UNIX operating system and virtually all UNIX applications are written in the C language. C has now become a widely used professional language for various reasons.     

Easy to learn Structured language It produces efficient programs. It can handle low-level activities. It can be compiled on a variety of computers.

WHY TO USE C C was initially used for system development work, in particular the programs that make-up the operating system. C was adopted as a system development language because it produces code that runs nearly as fast as code written in assembly language. Some examples of the use of C might be:          

Operating Systems Language Compilers Assemblers Text Editors Print Spoolers Network Drivers Modern Programs Data Bases Language Interpreters Utilities


FEATURES OF C 1. Low Level Features: 1. C Programming provides low level features that are generally provided by the Lower level languages. C is Closely Related to Lower level Language such as “Assembly Language“. 2. It is easier to write assembly language codes in C programming. 2. Portability: 1. C Programs are portable i.e. they can be run on any Compiler with Little or no Modification 2. Compiler and Preprocessor make it Possible for C Program to run it on Different PC 3 . Powerful 1. Provides Wide verity of ‘Data Types‘ 2. Provides Wide verity of ‘Functions’ 3. Provides useful Control & Loop Control Statements 4 . Bit Manipulation 1. C Programs can be manipulated using bits. We can perform different operations at bit level. We can manage memory representation at bit level. [E.g. We can use Structure to manage Memory at Bit Level] 2. It provides wide verity of bit manipulation Operators. We have bitwise operators to manage Data at bit level. 5 . High Level Features : 1. It is more User friendly as compare to previous languages. Previous languages such as BCPL Pascal and other programming languages never provide such great features to manage data. 2. Previous languages have their pros and cons but C Programming collected all useful features of previous languages thus C become more effective language. 6 . Modular Programming 1. Modular programming is a software design technique that increases the extent to which software is composed of separate parts, called modules


2. C Program Consist of Different Modules that are integrated together to form complete program 7 . Efficient Use of Pointers 1. Pointers have direct access to memory. 2. C Supports efficient use of pointer.

ADVANTAGES OF C LANGUAGE 1. C language is a building block for many other currently known languages. C language has variety of data types and powerful operators. Due to this, programs written in C language are efficient, fast and easy to understand. 2. C is highly portable language. This means that written for one computer can easily run on another computer without any change or by doing a little change. 3. There are only 32 keywords in ANSI C and its strength lies in its built-in functions. Several standard functions are available which can be used for developing programs. 4. Another important advantage of C is its ability to extend itself. A C program is basically a collection of functions that are supported by the C library this makes us easier to add our own functions to C library. Due to the availability of large number of functions, the programming task becomes simple. 5. C language is a structured programming language. This makes user to think of a problem in terms of function modules or blocks. Collection of these modules makes a complete program. This modular structure makes program debugging, testing and maintenance easier.

Disadvantages of C Language 1. C does not have concept of OOPs, that’s why C++ is developed.


2. There is no runtime checking in C language. 3. There is no strict type checking. For example, we can pass an integer value. for the floating data type. 4. C doesn’t have the concept of namespace. 5. C doesn’t have the concept of constructor or destructor.

Basic structure of C programming: To write a C program, we first create functions and then put them together. A C program may contain one or more sections. They are illustrated below.

1. Documentation section : The documentation section consists of a set of comment lines giving the name of the program, the author and other details, which the programmer would like to use later. 2. Link section : The link section provides instructions to the compiler to link functions from the system library.


3. Definition section : The definition section defines all symbolic constants. 4. Global declaration section : There are some variables that are used in more than one function. Such variables are called global variables and are declared in the global declaration section that is outside of all the functions. This section also declares all the user-defined functions. 5. main () function section : Every C program must have one main function section. This section contains two parts; declaration part and executable part 6. Declaration part : The declaration part declares all the variables used in the executable part. 7. Executable part : There is at least one statement in the executable part. These two parts must appear between the opening and closing braces. The program execution begins at the opening brace and ends at the closing brace. The closing brace of the main function is the logical end of the program. All statements in the declaration and executable part end with a semicolon. 8. Subprogram section : The subprogram section contains all the userdefined functions that are called in the main () function. User-defined functions are generally placed immediately after the main () function, although they may appear in any order.

Steps to write C programs and get the output: Below are the steps to be followed for any C program to create and get the output. This is common to all C program and there is no exception whether its a very small C program or very large C program.


Basic commands in C programming to write basic C Program: Below are few commands and syntax used in C programming to write a simple C program. Let’s see all the sections of a simple C program line by line. S.no

Command

Explanation

1

#include <stdio.h>

This is a preprocessor command that includes standard input output header file(stdio.h) from the C library before compiling a C program

2

int main()

This is the main function from where execution of any C program begins.

3

{

This indicates the beginning of the main function.

4

/*_some_comments_*/ whatever is given inside the command “/* */” in any C program, won’t be considered for compilation and execution.

5

printf(“Hello_World! “); printf command prints the output onto the screen.

6

getch();

This command waits for any character input from keyboard.

7

return 0;

This command terminates C program (main function) and returns 0.


8

}

This indicates the end of the main function.

Output: Hello World! .

1. Keywords are those words whose meaning is already defined by Compiler 2. Cannot be used as Variable Name 3. There are 32 Keywords in C 4. C Keywords are also called as Reserved words . 32 Keywords in C Programming Language Auto

double

int

struct

Break

else

long

switch

Case

enum

register

typedef

Char

extern

return

union

Const

float

short

unsigned

continue

for

signed

void

default

goto

sizeof

volatile

Do

if

static

while

C Tokens Chart


 

In C Programming punctuation, individual words, characters etc are called tokens. Tokens are basic building blocks of C Programming

Token Example : No

Token Type

Example 1

Example 2

1

Keyword

do

while

2

Constants

number

sum

3

Identifier

-76

89

4

String

“HTF”

“PRIT”

5

Special Symbol

*

@

6

Operators

++

/


Basic Building Blocks and Definition : Token

Meaning

Keyword

A variable is a meaningful name of data storage location in computer memory. When using a variable you refer to memory address of computer

Constant

Constants are expressions with a fixed value

Identifier

The term identifier is usually used for variable names

String

Sequence of characters

Special

Symbols other than the Alphabets and Digits and white-spaces

Operators A symbol that represent a specific mathematical or non mathematical action

  

C Constants are also like normal variables. But, only difference is, their values can not be modified by the program once they are defined. Constants refer to fixed values. They are also called as literals Constants may be belonging to any of the data type.

Syntax:

const data_type variable_name; (or) const data_type *variable_name; Types of C constant: 1. 2. 3. 4. 5. 6.

Integer constants Real or Floating point constants Octal & Hexadecimal constants Character constants String constants Backslash character constants


S.no

Constant type

data type int unsigned int long int long long int

Example

1

Integer constants

53, 762, -478 etc 5000u, 1000U etc 483,647 2,147,483,680

2

Real or Floating point constants float doule

10.456789 600.123456789

3

Octal constant

int

013

/* starts with 0 */

4

Hexadecimal constant

int

0×90

/* starts with 0x */

5

character constants

char

‘A’ , ‘B’,

6

string constants

char

“ABCD” , “Hai”

‘C’

Rules for constructing C constant: 1. Integer Constants in C:      

An integer constant must have at least one digit. It must not have a decimal point. It can either be positive or negative. No commas or blanks are allowed within an integer constant. If no sign precedes an integer constant, it is assumed to be positive. The allowable range for integer constants is -32768 to 32767.

2. Real constants in C:     

A real constant must have at least one digit It must have a decimal point It could be either positive or negative If no sign precedes an integer constant, it is assumed to be positive. No commas or blanks are allowed within a real constant.

3. Character and string constants in C:   

A character constant is a single alphabet, a single digit or a single special symbol enclosed within single quotes. The maximum length of a character constant is 1 character. String constants are enclosed within double quotes.


4. Backslash Character Constants in C:   

There are some characters which have special meaning in C language. They should be preceded by backslash symbol to make use of special function of them. Given below is the list of special characters and their purpose.

Backslash_character

Meaning

\b

Backspace

\f

Form feed

\n

New line

\r

Carriage return

\t

Horizontal tab

\”

Double quote

\’

Single quote

\\

Backslash

\v

Vertical tab

\a

Alert or bell

\?

Question mark

\N

Octal constant (N is an octal constant)

\XN

Hexadecimal constant (N – hex.dcml cnst)

How to use constants in a C program? 

We can define constants in a C program in the following ways.

1. By “const” keyword 2. By “#define” preprocessor directive


Please note that when you try to change constant values after defining in C program, it will through error.

1. Example program using const keyword in C: #include <stdio.h> void main() { const int height = 100; /*int constant*/ const float number = 3.14; /*Real constant*/ const char letter = ‘A’; /*char constant*/ const char letter_sequence[10] = “ABC”; /*string constant*/ const char backslash_char = ‘\?’; /*special char cnst*/ printf(“value of height :%d \n”, height ); printf(“value of number : %f \n”, number ); printf(“value of letter : %c \n”, letter ); printf(“value of letter_sequence : %s \n”, letter_sequence); printf(“value of backslash_char : %c \n”, backslash_char); } Output: value of height : 100 value of number : 3.140000 value of letter : A value of letter_sequence : ABC value of backslash_char : ?

  

C data types are defined as the data storage format that a variable can store a data to perform a specific operation. Data types are used to define a variable before to use in a program. Size of variable, constant and array are determined by data types.

Data types: There are four data types in C language. They are,


S.no

Types

Data Types

1

Basic data types

int, char, float, double

2

Enumeration data type

enum

3

Derived data type

pointer, array, structure, union

4

Void data type

void

1. Basic data types in C: 1.1. Integer data type:        

Integer data type allows a variable to store numeric values. “int” keyword is used to refer integer data type. The storage size of int data type is 2 or 4 or 8 byte. It varies depend upon the processor in the CPU that we use. If we are using 16 bit processor, 2 byte (16 bit) of memory will be allocated for int data type. Like wise, 4 byte (32 bit) of memory for 32 bit processor and 8 byte (64 bit) of memory for 64 bit processor is allocated for int datatype. int (2 byte) can store values from -32,768 to +32,767 int (4 byte) can store values from -2,147,483,648 to +2,147,483,647. If you want to use the integer value that crosses the above limit, you can go for “long int” and “long long int” for which the limits are very high.

Note:   

We can’t store decimal values using int data type. If we use int data type to store decimal values, decimal values will be truncated and we will get only whole number. In this case, float data type can be used to store decimal values in a variable.

1.2. Character data type:     

Character data type allows a variable to store only one character. Storage size of character data type is 1. We can store only one character using character data type. “char” keyword is used to refer character data type. For example, ‘A’ can be stored using char datatype. You can’t store more than one character using char data type. Please refer C – Strings topic to know how to store more than one characters in a variable.


1.3. Floating point data type: Floating point data type consists of 2 types. They are, 1. float 2. double 1. float:    

Float data type allows a variable to store decimal values. Storage size of float data type is 4. This also varies depend upon the processor in the CPU as “int” data type. We can use up-to 6 digits after decimal using float data type. For example, 10.456789 can be stored in a variable using float data type.

2. double:  

Double data type is also same as float data type which allows up-to 10 digits after decimal. The range for double datatype is from 1E–37 to 1E+37.

1.3.1. sizeof() function in C: sizeof() function is used to find the memory space allocated for each C data types. #include <stdio.h> #include <limits.h> int main() { int a; char b; float c; double d; printf(“Storage size for int data type:%d \n”,sizeof(a)); printf(“Storage size for char data type:%d \n”,sizeof(b)); printf(“Storage size for float data type:%d \n”,sizeof(c)); printf(“Storage size for double data type:%d\n”,sizeof(d)); return 0; } Output:


Storage size for int data type:4 Storage size for char data type:1 Storage size for float data type:4 Storage size for double data type:8

   

.

The symbols which are used to perform logical and mathematical operations in a C program are called C operators. These C operators join individual constants and variables to form expressions. Operators, functions, constants and variables are combined together to form expressions. Consider the expression A + B * 5. Where, +, * are operators, A, B are variables, 5 is constant and A + B * 5 is an expression.

Types of C operators: C language offers many types of operators. They are, 1. 2. 3. 4. 5. 6. 7. 8.

Arithmetic operators Assignment operators Relational operators Logical operators Bit wise operators Conditional operators (ternary operators) Increment/decrement operators Special operators

Continue on types of C operators: 

S.no 1

Click on each operators name below for detail description and example programs. Types of Operators Arithmetic_operators

Description These are used to perform mathematical calculations like addition, subtraction, multiplication, division and modulus


2

Assignment_operators

These are used to assign the values for the variables in C programs.

3

Relational operators

These operators are used to compare the value of two variables.

4

Logical operators

These operators are used to perform logical operations on the given two variables.

5

Bit wise operators

These operators are used to perform bit operations on given two variables.

6

Conditional (ternary) operators

Conditional operators return one value if condition is true and returns another value is condition is false.

7

Increment/decrement operators

These operators are used to either increase or decrease the value of the variable by one.

8

Special operators

&, *, sizeof( ) and ternary operators.

Decision control statements

Whenever we build an application in any programming language, there is a need of including decision control statements in code. We can include various conditions in our program using these statements; we can perform different- different tasks based on the conditions. Following are the decision control statements available in C. a) if statement b) if-else & else-if statement c) switch-case statements


Below are the tutorials links – 1. If statement: The code inside if body executes only when the condition defined by if statement is true. If the condition is false then compiler skips the statement enclosed in if’s body. We can have any number of if statements in a C program. 2. If-else statement: Here, we have two block of statements. If condition results true then if block gets execution otherwise statements in elseblock executes. else cannot exist without if statement. In this tutorial, I have covered else-if statements too. 3. Switch-case statement: This is very useful when we have several block of statements, which requires execution based on the output of an expression or condition. switch defines an expression (or condition) and case has a block of statements, based on the result of expression, corresponding case gets execution. A switch can have any number of cases, however there should be only default handler. Decision control statements if

Syntax

Description

if (condition) { Statements; }

In these type of statements, if condition is true, then respective block of code is executed.

if…else

if (condition) { Statement1; Statement2; } else { Statement3; Statement4; }

In these type of statements, group of statements are executed when condition is true. If condition is false, then else part statements are executed.

nested if

if (condition1){ Statement1; } else_if(condition2) { Statement2; } else Statement 3;

If condition 1 is false, then condition 2 is checked and statements are executed if it is true. If condition 2 also gets failure, then else part is executed.


Example program for if statement in C: In “if� control statement, respective block of code is executed when condition is true. int main() { int m=40,n=40; if (m == n) { printf("m and n are equal"); } }

Output: m and n are equal Example program for if else statement in C: In C if else control statement, group of statements are executed when condition is true. If condition is false, then else part statements are executed. #include <stdio.h> int main() { int m=40,n=20; if (m == n) { printf("m and n are equal"); } else { printf("m and n are not equal"); } } Output: m and n are not equal


Example program for nested if statement in C:  

In “nested if” control statement, if condition 1 is false, then condition 2 is checked and statements are executed if it is true. If condition 2 also gets failure, then else part is executed.

#include <stdio.h> int main() { int m=40,n=20; if (m>n) { printf("m is greater than n"); } else if(m<n) { printf("m is less than n"); } else { printf("m is equal to n"); } } Output: m is greater than n

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

Grade = 'A';

switch( Grade { case 'A' : case 'B' : case 'C' : case 'D' : case 'F' : this\n" ); default : anyway?\n" ); } }

) printf( printf( printf( printf( printf(

"Excellent\n" ); "Good\n" ); "OK\n" ); "Mmmmm....\n" ); "You must do better than

printf( "What is your grade


This will produce following result: Excellent Good OK Mmmmm.... You must do better than this What is your grade anyway? Using break statement: You can come out of the switch block if your condition is met. This can be achieved using break statement. Try out following example: #include <stdio.h> main() { int

Grade = 'B';

switch( Grade ) { case 'A' : printf( break; case 'B' : printf( break; case 'C' : printf( break; case 'D' : printf( break; case 'F' : printf( this\n" ); break; default : printf( anyway?\n" ); break; } }

"Excellent\n" ); "Good\n" ); "OK\n" ); "Mmmmm....\n" ); "You must do better than "What is your grade


Loops   

for loop” “while loop” “do while loop”

The for loop The “for loop” loops from one number to another number and increases by a specified value each time. The “for loop” uses the following structure: for (Start value; continue or end condition; increase value) statement; Look at the example below: #include<stdio.h> int main() { int i; for (i = 0; i < 10; i++) { printf ("Hello\n"); printf ("World\n"); } return 0; }


The while loop The while loop can be used if you don’t know how many times a loop must run. Here is an example: #include<stdio.h> int main() { int counter, howmuch; scanf("%d", &howmuch); counter = 0; while ( counter < howmuch) { counter++; printf("%d\n", counter); } return 0; }

The do while loop The “do while loop” is almost the same as the while loop. The “do while loop” has the following form: do { do something; } while (expression); Do something first and then test if we have to continue. The result is that the loop always runs once. (Because the expression test comes afterward). Take a look at an example:

#include<stdio.h> int main()


{ int counter, howmuch; scanf("%d", &howmuch); counter = 0; do { counter++; printf("%d\n", counter); } while ( counter < howmuch); return 0; }

Array In C programming, one of the frequently arising problem is to handle similar types of data. For example: If the user want to store marks of 100 students. This can be done by creating 100 variable individually but, this process is rather tedious and impracticable. These type of problem can be handled in C programming using arrays. An array is a sequence of data item of homogeneous value(same type). Arrays are of two types: 1. One-dimensional arrays 2. Multidimensional arrays Declaration of one-dimensional array data_type array_name[array_size];

For example: int age[5]; Here, the name of array is age. The size of array is 5,i.e., there are 5 items(elements) of array age. All element in an array are of the same type (int, in this case). Array elements Size of array defines the number of elements in an array. Each element of array can be accessed and used by user according to the need of program. For example:


int age[5];

Note that, the first element is numbered 0 and so on. Here, the size of array age is 5 times the size of int because there are 5 elements. Suppose, the starting address of age[0] is 2120d and the size of int be 4 bytes. Then, the next address (address of a[1]) will be 2124d, address of a[2] will be 2128d and so on. Initialization of one-dimensional array: Arrays can be initialized at declaration time in this source code as: int age[5]={2,4,34,3,4}; It is not necessary to define the size of arrays during initialization. int age[]={2,4,34,3,4}; In this case, the compiler determines the size of array by calculating the number of elements of an array.

Accessing array elements In C programming, arrays can be accessed and treated like variables in C. For example: scanf("%d",&age[2]); /* statement to insert value in the third element of array age[]. */


scanf("%d",&age[i]); /* Statement to insert value in (i+1)th element of array age[]. */ /* Because, the first element of array is age[0], second is age[1], ith is age[i-1] and (i+1)th is age[i]. */

printf("%d",age[0]); /* statement to print first element of an array. */

printf("%d",age[i]); /* statement to print (i+1)th element of an array. */ Example of array in C programming /* C program to find the sum marks of n students using arrays */ #include <stdio.h> int main(){ int marks[10],i,n,sum=0; printf("Enter number of students: "); scanf("%d",&n); for(i=0;i<n;++i){ printf("Enter marks of student%d: ",i+1); scanf("%d",&marks[i]); sum+=marks[i]; } printf("Sum= %d",sum); return 0; } Output Enter number of students: 3 Enter marks of student1: 12


Enter marks of student2: 31 Enter marks of student3: 2 sum=45 C programming language allows programmer to create arrays of arrays known as multidimensional arrays. For example: float a[2][6]; Here, a is an array of two dimension, which is an example of multidimensional array. For better understanding of multidimensional arrays, array elements of above example can be thinked of as below:

Initialization of Multidimensional Arrays In C, multidimensional arrays can be initialized in different number of ways. int c[2][3]={{1,3,0}, {-1,5,9}}; OR int c[][3]={{1,3,0}, {-1,5,9}}; OR int c[2][3]={1,3,0,-1,5,9}; Initialization Of three-dimensional Array double cprogram[3][2][4]={ {{-0.1, 0.22, 0.3, 4.3}, {2.3, 4.7, -0.9, 2}}, {{0.9, 3.6, 4.5, 4}, {1.2, 2.4, 0.22, -1}},


{{8.2, 3.12, 34.2, 0.1}, {2.1, 3.2, 4.3, -2.0}} }; Suppose there is a multidimensional array arr[i][j][k][m]. Then this array can hold i*j*k*m numbers of data. Similarly, the array of any dimension can be initialized in C programming. Example of Multidimensional Array In C Write a C program to find sum of two matrix of order 2*2 using multidimensional arrays where, elements of matrix are entered by user. #include <stdio.h> int main(){ float a[2][2], b[2][2], c[2][2]; int i,j; printf("Enter the elements of 1st matrix\n"); /* Reading two dimensional Array with the help of two for loop. If there was an array of 'n' dimension, 'n' numbers of loops are needed for inserting data to array.*/ for(i=0;i<2;++i) for(j=0;j<2;++j){ printf("Enter a%d%d: ",i+1,j+1); scanf("%f",&a[i][j]); } printf("Enter the elements of 2nd matrix\n"); for(i=0;i<2;++i) for(j=0;j<2;++j){ printf("Enter b%d%d: ",i+1,j+1); scanf("%f",&b[i][j]); } for(i=0;i<2;++i) for(j=0;j<2;++j){ /* Writing the elements of multidimensional array using loop. */ c[i][j]=a[i][j]+b[i][j]; /* Sum of corresponding elements of two arrays. */ } printf("\nSum Of Matrix:"); for(i=0;i<2;++i) for(j=0;j<2;++j){ printf("%.1f\t",c[i][j]); if(j==1) /* To display matrix sum in order. */ printf("\n"); } return 0; }


Ouput Enter the elements of 1st matrix Enter a11: 2; Enter a12: 0.5; Enter a21: -1.1; Enter a22: 2; Enter the elements of 2nd matrix Enter b11: 0.2; Enter b12: 0; Enter b21: 0.23; Enter b22: 23;

Sum Of Matrix: 2.2

0.5

-0.9

25.0

Strings


  

C Strings are nothing but array of characters ended with null character (‘\0’). This null character indicates the end of the string. Strings are always enclosed by double quotes. Whereas, character is enclosed by single quotes in C.

Example for C string:   

char string[20] = { ‘f’ , ’r’ , ‘e’ , ‘s’ , ‘h’ , ‘2’ , ‘r’ , ‘e’ , ‘f’ , ’r’ , ‘e’ , ‘s’ , ‘h’ , ‘\0’}; (or) char string[20] = “fresh2refresh”; (or) char string [] = “fresh2refresh”;

Difference between above declarations are, when we declare char as “string[20]“, 20 bytes of memory space is allocated for holding the string value. When we declare char as “string[]”, memory space will be allocated as per the requirement during execution of the program.

Example program for C string: #include <stdio.h> int main () { char string[20] = "fresh2refresh.com"; printf("The string is : %s \n", string ); return 0; } Output: The string is : fresh2refresh.com C String functions:  

S.no

String.h header file supports all the string functions in C language. All the string functions are given below. Click on each string function name below for detail description and example programs. String functions

Description

1

strcat ( )

Concatenates str2 at the end of str1.

2

strncat ( )

appends a portion of string to another


3

strcpy ( )

Copies str2 into str1

4

strncpy ( )

copies given number of characters of one string to another

5

strlen ( )

gives the length of str1.

6

strcmp ( )

Returns 0 if str1 is same as str2. Returns <0 if strl < str2. Returns >0 if str1 > str2.

7

strcmpi_(.)

Same as strcmp() function. But, this function negotiates case. “A” and “a” are treated as same.

8

strchr ( )

Returns pointer to first occurrence of char in str1.

9

strrchr ( )

last occurrence of given character in a string is found

10 strstr ( )

Returns pointer to first occurrence of str2 in str1.

11 strrstr ( )

Returns pointer to last occurrence of str2 in str1.

12 strdup ( )

duplicates the string

13 strlwr ( )

converts string to lowercase

14 strupr ( )

converts string to uppercase

15 strrev ( )

reverses the given string

16 strset ( )

sets all character in a string to given character

17 strnset ( )

It sets the portion of characters in a string to given character

18 strtok ( )

tokenizing given string using delimiter

Function


A function is a block of statements, which is used to perform a specific task. Suppose you are building an application in C language and in one of your program, you need to perform a same task more than once. So in such scenario you have two options – a) Use the same set of statements every time you want to perform the task b) Create a function, which would do the task, and just call it every time you need to perform the same task. Using option (b) is a good practice and a good programmer always uses functions while writing codes. Types of functions 1) Predefined standard library functions – such as puts(), gets(),printf(), scanf() etc – These are the functions which already have a definition in header files (.h files like stdio.h), so we just call them whenever there is a need to use them. 2) User Defined functions – The functions which we can create by ourselves, for example in the above code I have created a function abc and I called it int main() in order to use it. Why we need functions Functions are used because of following reasons – a) To improve the readability of code. b) Improves the reusability of the code, same function can be used in any program rather than writing the same code from scratch. c) Debugging of the code would be easier if you use functions as errors are easy to be traced. d) Reduces the size of the code, duplicate set of statements are replaced by function calls. Syntax of Defining a function return_type function_name (argument list)


{ Set of statements – Block of code } return_type: Return type can be of any data type such as int, double, char, void, short etc. Don’t worry you will understand these terms better once you go through the below examples. function_name: It can be anything, however it is advised to have a meaningful name for the functions so that it would be easy to understand the purpose of function just by seeing it’s name. argument list: Argument list contains variables names along with their data types. These arguments are kind of inputs for the function. For example – A function which is used to add two integer variables, will be having two integer argument. Block of code: Set of C statements, which will be executed whenever a call will be made to the function.

How to call a function? Consider the below program – Example1: int addition(int num1, int num2) { int sum /* Arguments are used here*/ sum = num1+num2; /* function return type is integer so I should return some integer value */ return sum } int main()


{ int var1, var2; printf("enter number 1: "); scanf("%d",&var1); printf("enter number 2: "); scanf("%d",&var2); /* calling function – function return type is integer so I would be * needing to store the returned value in some integer variable */ int res = addition(var1, var2); printf ("Output: %d", res); return 0; }

Pointers


Pointers in C are easy and fun to learn. Some C programming tasks are performed more easily with pointers, and other tasks, such as dynamic memory allocation, cannot be performed without using pointers. So it becomes necessary to learn pointers to become a perfect C programmer. Let's start learning them in simple and easy steps. As you know, every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator, which denotes an address in memory. Consider the following example, which will print the address of the variables defined: #include <stdio.h>

int main () { int

var1;

char var2[10];

printf("Address of var1 variable: %x\n", &var1

);

printf("Address of var2 variable: %x\n", &var2

);

return 0; } When the above code is compiled and executed, it produces result something as follows: Address of var1 variable: bff5a400 Address of var2 variable: bff5a3f6 So you understood what is memory address and how to access it, so base of the concept is over. Now let us see what is a pointer.

What Are Pointers? A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a


pointer before you can use it to store any variable address. The general form of a pointer variable declaration is: type *var-name; Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the pointer variable. The asterisk * you used to declare a pointer is the same asterisk that you use for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Following are the valid pointer declaration: int

*ip;

/* pointer to an integer */

double *dp;

/* pointer to a double */

float

*fp;

/* pointer to a float */

char

*ch

/* pointer to a character */

The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to. How to use Pointers? There are few important operations, which we will do with the help of pointers very frequently.(a) we define a pointer variable (b) assign the address of a variable to a pointer and (c) finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand. Following example makes use of these operations: #include <stdio.h>

int main () { int

var = 20;

/* actual variable declaration */

int

*ip;

/* pointer variable declaration */


ip = &var;

/* store address of var in pointer variable*/

printf("Address of var variable: %x\n", &var

);

/* address stored in pointer variable */ printf("Address stored in ip variable: %x\n", ip );

/* access the value using the pointer */ printf("Value of *ip variable: %d\n", *ip );

return 0; } When the above code is compiled and executed, it produces result something as follows: Address of var variable: bffd8b3c Address stored in ip variable: bffd8b3c Value of *ip variable: 20 NULL Pointers in C It is always a good practice to assign a NULL value to a pointer variable in case you do not have exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NULL is called a null pointer. The NULL pointer is a constant with a value of zero defined in several standard libraries. Consider the following program: #include <stdio.h>

int main () {


int

*ptr = NULL;

printf("The value of ptr is : %x\n", ptr

);

return 0; } When the above code is compiled and executed, it produces the following result: The value of ptr is 0 On most of the operating systems, programs are not permitted to access memory at address 0 because that memory is reserved by the operating system. However, the memory address 0 has special significance; it signals that the pointer is not intended to point to an accessible memory location. But by convention, if a pointer contains the null (zero) value, it is assumed to point to nothing. To check for a null pointer you can use an if statement as follows: if(ptr)

/* succeeds if p is not null */

if(!ptr)

/* succeeds if p is null */

C Pointers in Detail:

Pointers have many but easy concepts and they are very important to C programming. There are following few important pointer concepts which should be clear to a C programmer:

Concept

Description


C - Pointer arithmetic

There are four arithmetic operators that can be used on pointers: ++, --, +, -

C - Array of pointers

You can define arrays to hold a number of pointers.

C - Pointer to pointer

C allows you to have pointer on a pointer and so on.

Passing pointers to functions in C

Passing an argument by reference or by address both enable the passed argument to be changed in the calling function by the called function.

Return pointer from functions in C

C allows a function to return a pointer to local variable, static variable and dynamically allocated memory as well.


Structures

C arrays allow you to define type of variables that can hold several data items of the same kind but structure is another user defined data type available in C programming, which allows you to combine data items of different kinds. Structures are used to represent a record, suppose you want to keep track of your books in a library. You might want to track the following attributes about each book: 

Title

Author

Subject

Book ID

Defining a Structure To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member for your program. The format of the struct statement is this: struct [structure tag] { member definition; member definition; ... member definition; } [one or more structure variables]; The structure tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the structure's definition, before the final semicolon, you can specify one or more structure variables but it is optional. Here is the way you would declare the Book structure:


struct Books { char

title[50];

char

author[50];

char

subject[100];

int

book_id;

} book;

Accessing Structure Members To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use struct keyword to define variables of structure type. Following is the example to explain usage of structure: #include <stdio.h> #include <string.h>

struct Books { char

title[50];

char

author[50];

char

subject[100];

int

book_id;

};

int main( ) { struct Books Book1;

/* Declare Book1 of type Book */

struct Books Book2;

/* Declare Book2 of type Book */


/* book 1 specification */ strcpy( Book1.title, "C Programming"); strcpy( Book1.author, "Nuha Ali"); strcpy( Book1.subject, "C Programming Tutorial"); Book1.book_id = 6495407;

/* book 2 specification */ strcpy( Book2.title, "Telecom Billing"); strcpy( Book2.author, "Zara Ali"); strcpy( Book2.subject, "Telecom Billing Tutorial"); Book2.book_id = 6495700;

/* print Book1 info */ printf( "Book 1 title : %s\n", Book1.title); printf( "Book 1 author : %s\n", Book1.author); printf( "Book 1 subject : %s\n", Book1.subject); printf( "Book 1 book_id : %d\n", Book1.book_id);

/* print Book2 info */ printf( "Book 2 title : %s\n", Book2.title); printf( "Book 2 author : %s\n", Book2.author); printf( "Book 2 subject : %s\n", Book2.subject); printf( "Book 2 book_id : %d\n", Book2.book_id);

return 0; }


Union A union is a special data type available in C that enables you to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multi-purpose.

Defining a Union To define a union, you must use the union statement in very similar was as you did while defining structure. The union statement defines a new data type, with more than one member for your program. The format of the union statement is as follows: union [union tag] { member definition; member definition; ... member definition; } [one or more union variables]; The union tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the union's definition, before the final semicolon, you can specify one or more union variables but it is optional. Here is the way you would define a union type named Data which has the three members i, f, and str: union Data { int i; float f;


char

str[20];

} data; Now, a variable of Data type can store an integer, a floating-point number, or a string of characters. This means that a single variable ie. same memory location can be used to store multiple types of data. You can use any built-in or user defined data types inside a union based on your requirement.

File Handling in C Language A file represents a sequence of bytes on the disk where a group of related data is stored. File is created for permanent storage of data. It is a ready made structure. In C language, we use a structure pointer of file type to declare a file. FILE *fp; C provides a number of functions that helps to perform basic file operations. Following are the functions, Function

Description

fopen()

create a new file or open a existing file

fclose()

closes a file

getc()

reads a character from a file

putc()

writes a character to a file


fscanf()

reads a set of data from a file

fprintf()

writes a set of data to a file

getw()

reads a integer from a file

putw()

writes a integer to a file

fseek()

set the position to desire point

ftell()

gives current position in the file

rewind()

set the position to the begining point

Opening a File or Creating a File The fopen() function is used to create a new file or to open an existing file. General Syntax : *fp = FILE *fopen(const char *filename, const char *mode); Here filename is the name of the file to be opened and mode specifies the purpose of opening the file. Mode can be of following types, *fp is the FILE pointer ( FILE *fp ), which will hold the reference to the opened(or created) file. mode

description

r

opens a text file in reading mode


w

opens or create a text file in writing mode.

a

opens a text file in append mode

r+

opens a text file in both reading and writing mode

w+

opens a text file in both reading and writing mode

a+

opens a text file in both reading and writing mode

rb

opens a binary file in reading mode

wb

opens or create a binary file in writing mode

ab

opens a binary file in append mode

rb+

opens a binary file in both reading and writing mode

wb+

opens a binary file in both reading and writing mode

ab+

opens a binary file in both reading and writing mode

Closing a File The fclose() function is used to close an already opened file. General Syntax : int fclose( FILE *fp );


Here fclose() function closes the file and returns zero on success, or EOF if there is an error in closing the file. This EOF is a constant defined in the header file stdio.h.

Input/Output operation on File In the above table we have discussed about various file I/O functions to perform reading and writing on file. getc() and putc() are simplest functions used to read and write individual characters to a file. #include<stdio.h> #include<conio.h> main() { FILE *fp; char ch; fp = fopen("one.txt", "w"); printf("Enter data"); while( (ch = getchar()) != EOF) { putc(ch,fp); } fclose(fp); fp = fopen("one.txt", "r"); while( (ch = getc()) != EOF) printf("%c",ch); fclose(fp); }


BATRA COMPUTER CENTRE PHN NO:-8950829990


01714000670


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.