Programming in C - A glance

Programming in C
• Introduction to C Programming
• History of C
• Features of C
• Sample Program
o The "#include" preprocessor directive
o The "main" function
o The "printf" function
o The "return" statement
o Shortcut Keys
• Program Control using C
• Tokens
• Datatypes and Typecasting
• Operators
• Control Structures
o The "if" statement
o The "switch" statement
o Looping
 The "for" statement
 The "while" statement
 The "do"..."while" loop
o The "continue" statement
o The "break" statement
• User Input and Output
o Stdio header files
o Escape Sequences
o scanf
o printf
o getchar
o putchar
• Exercise 2
• Arrays
o What is an array?
o Array Declaration
o Array Initialization
o Accessing individual elements of an array
o Two Dimensional Arrays
o Accessing the elements of a two dimensional array
o More than two dimensional array
o Passing an array element to a function
o Rules of using an array
• Pointers
o What is a pointer?
o Declaring a Pointer variable
o Initializing a pointer variable
o Using a Pointer Variable
Pointer Arithmetic
Why use pointers
o As function arguments (By reference)
o Pointers and array
o Passing an entire array to a function
o Functions returning a Pointer Variable
• Exercise 3 - A Simple Calculator
• Exercise 4 - Printing a multiplication table
• Strings
o What is a String?
o String I/O
o String Functions
• Functions
• Summary

































Programming in C

Introduction to C Programming

• C is a simple programming language.
• It is most popular computer language today because it is a structured high level, machine independent language.

Program:
A computer program is a set of instructions for a computer to perform a specific task. The development of program is known as programming.
Software:
Set of programs

History of C

• In 1972, C was developed at Bell laboratories by Dennis Ritchie.
• Ken Thompson created a language which was based upon a language known as Basic Combined Programming Language (BCPL) and it was called as B. B language was created in 1969, basically for UNIX operating system Dennis Ritchie used ALGOL, BCPL and B as the basic reference language from which he created C.

Features of C

 C has all advantages of low level language(or assembly language) and all significant features of modern high level language (PASCAL,COBOL, FORTRAN), so it is called a middle level language.

 Security , Reusablity, High Efficiency

 C language is a very powerful and flexible language.

 It provides dynamic memory allocation.

 C compiler produces very fast object code.

 C language is a portable language. A code written in C on a particular machine can be compiled and run on another machine.

 C is a modularity language.

 Recursion: A function may call itself again and again. this feature is called as recursion, is supported by C.




Modularity:
Program whose structure consists of interrelated segments arranged in a logical and easily understandable order to form an integrated and complete unit, are called modular programs.

Uses of C language

Because of the above features of C, C was initially used for systems programming includes development of compilers, interpreters, operating systems etc., The UNIX OS was developed using C. Today C is being used for all kinds of tasks because of its portability and efficiently.

Structure of a C Program

Example 1: To display the text

/* Sample Program to display the text */

#include
#include
void main()
{
clrscr(); /* Clear the Screen */
printf("Welcome to BeatSoft");
getch();

}

Output
Welcome to BeatSoft

Step 1 : Comment Line ( Non executable statements)
The /* .... */ is a comment and will not be executed, the compiler simply ignores this statement. These are essential since it enhances the readability and understandability of the program. It is a very good practice to include comments in all the programs to make the users understand what is being done in the program
Step 2 : Header Files
#include -This line tells the compiler to include this header file for compilation.
The first line is a preprocessor command which adds the stdio header file into our program. Actually stdio stands for standard input output, this header file supports the input-output functions in a program. Some common header files are stdio.h,conio.h and math.h etc.,
Because this line starts with a #, it is called a preprocessor directive. The preprocessor reads your program before it is complied and only executes those lines beginning with a # symbol. The word inside the angular brackets <> is a header file name, which is required to do the work of Input / Output. The contents of stdio.h are included at the point where the #include statement appears. The preprocessor directives should not end with a semicolon because preprocessors are messages to the compiler.
The C program is a set of functions. The program execution begins by executing the function main ().C requires a semicolon at the end of the every statement.
Step 3 : Main() method
The second line main() tell the compiler that it is the starting point of the program, every program should essentially have the main function only once in the program. The opening and closing braces indicates the beginning and ending of the program. All the statements between these two braces form the function body. These statements are actually the C code which tells the computer to do something. Each statement is a instruction for the computer to perform specific task. We must have a main() function
Step 4 : To display the output
The next statement printf() statement is the only executable line in the above sample program. The printf() function is a standard inbuilt function for printing a given line which appears inside the double quotes.(printf() used to display the text that contains within double quotes) Therefore in the standard output device we can see the following line
Welcome to BeatSoft
Syntax:
printf(“text”);
printf(“access_specifier”,variable);
.
printf() can display variables by using the % conversion character. printf() function available from the stdio.h library. Finally, the getch() function is taken from the conio.h library, and waits for a key to be pressed, and returns the character representing the key that was pressed. In this case, the value returned is ignored, as we are just using the functions as a means to see what is on the console window before it disappears. Try removing the getch() command from the program and running it again.
stdio means "standard in/out" which means a standard way of getting data to and from input and output devices. In our case, we wish to take data in from the keyboard (a standard input device) and put data onto the screen or console (a standard output device).
conio means "console in/out" which means ways of getting data to and from the console device (which uses the keyboard and screen).
Some common header files are stdio.h, stdlib.h, unistd.h,string.h and math.h.

Shortcut Keys in C Language

Open - F3
Save - F2
Compilation - Alt + F9
Execution (Run) - Ctrl + F9
Display the output - Alt + F5
Exit - Alt + X




Program Control using C


The C Compilation Model



A Compiler is a program which converts the written program into the machine language.

Creating the program

First create a file containing the complete program, such as the below example. You can use any ordinary editor to create the file. One such editor is textedit which is available on most UNIX systems. The filename must have extension “.c” (full stop, lower case c), e.g. Sample.c.

Compilation

There are many C compilers are present around. The cc is being the default Sun compiler. The GNU C compiler gcc is popular and also available for many platforms. PC users may also be familiar with Borland bcc compiler.

Running the program
The next stage is to run your executable program.You simply type the name of the file containing it, in this case program (or Sample.out),to run an executable in UNIX.
This executes your program able to print any results to the screen. At this stage there may be run-time errors, such as it may become evident that the program has produced incorrect output or division by zero. If so, you must return to edit your program source, and compile it again, and run it again.


The C Character Set
A character denotes any alphabet, digit or special symbol used to represent information. The C character set can be defined as a set of characters permissible under the C language to represent information. Under C, the upper case letters A-Z, the lower case letters a-z, the digits 0-9 and certain special symbols are all valid characters that can be used as building blocks to construct basic program elements.
Following is a table of character sets that are available under C
Alphabets
A, B, C, ………………… Z
a, b, c, ………………… z
Digits
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Characters or Symbols
+ - * & ^ % $ # @ ! ? > < { } [ ] ( ) | \ / “ ‘ : ; . , _
Identifiers in C
In a C program every word is either classified as an identifier or a keyword. Identifiers are used to identify or name various program-elements such as variables, symbolic constants, functions, etc.
Rules for Identifiers
1. An identifier can contain letters or letters in any order except that the first character must begin with a letter.
2. C is case-sensitive; therefore upper-case identifiers are different from lower-case characters. E.g. name is different from NAME.
3. An identifier cannot contain any special character. The only exception is the under score character (_), which can also be taken as the first character of an identifier.
4. An identifier cannot be a keyword.
Example of valid identifiers
name, a1, a_2, _c, NAME
Example of invalid identifiers
1stname, my-name, a 2

Keywords
Keywords are words, which have special meaning for the C compiler. Keywords cannot be used as identifiers because the programmer would then change the meaning of its implementation. Keywords are also sometimes known as reserved words.
Following is a list of keywords in C
auto break case char const continue default do
double else enum extern float for goto if
int long register return short signed sizeof static
struct switch typedef union unsigned void volatile while

Variables
A variable is a named data storage location in your computer's memory. By using a variable's name in your program, you are, in effect, referring to the data stored there.
Variable Names
To use variables in your C programs, you must know how to create variable names. In C, variable names must adhere to the following rules:
• The name can contain letters, digits, and the underscore character (_).
• The first character of the name must be a letter. The underscore is also a legal first character, but its use is not recommended.
• Case Sensitive (that is, upper- and lowercase letters). Thus, the names count and Count refer to two different variables.
• C keywords can't be used as variable names. A keyword is a word that is part of the C language.
• White space is not allowed.
Variable Declarations
Before you can use a variable in a C program, it must be declared. A variable declaration tells the compiler the name and type of a variable and optionally initializes the variable to a specific value. If your program attempts to use a variable that hasn't been declared, the compiler generates an error message.
A variable declaration has the following form:
Datatype varname;
data type specifies the variable data type and varname is the variable name. You can declare multiple variables of the same type on one line by separating the variable names with commas:
int a, b, c; /* three integer variables */
float total, avg; /* two float variables */

Data types :

Data types are used to store various types of data that is processed by program.

1. Integer Data types
The integer data type is used to store whole numbers only. Fractional numbers are not allowed in an int data type.
Data type Size Range
short int 2 bytes -32768 to 32767
signed short int 2 bytes -32768 to 32767
unsigned short int 2 bytes 0 to 65535
int 2 bytes -32768 to 32767
signed int 2 bytes -32768 to 32767
unsigned int 2 bytes 0 to 65535
long int 4 bytes -2147483648 to 2147483647
signed long int 4 bytes -2147483648 to 2147483647
unsigned long int 4 bytes 0 to 4294967295

2. Floating Point Data type
The float data type is used to store floating point numbers or fractional numbers. This data type is 4 Bytes in size. Floating point numbers can also be expressed in the scientific notation e.g. 1.7e4 represents the number 1.7 x 104. The double data type is also used to store floating point numbers or a fractional numbers. This data type is 8 Bytes in size. This data type can hold a large value.

Data type Size Range
float 4 bytes -3.4e38 to +3.4e38
double 8 bytes -1.7e308 to +1.7e308
long double 10 bytes -1.7e4932 to +1.7e4932

3. Character Data types

 It is stored as a single character .
 The character value should be enclosing with single quotes.
 Characters are usually stored in 8 bits(1 byte) of internal storage
 The qualifier signed or unsigned may be explicitly applied to char.
 Unsigned chars have values between 0 and 255,Signed chars have values -128 to 127

Data type Size Range
char 1 byte -128 to 127
signed char 1 byte -128 to 127
unsigned char 1 byte 0 to 255

signed
By default all data types are declared as signed. Signed means that the data type is capable of storing negative values.
unsigned
To modify a data type’s behavior so that it can only store positive values, we require to use the data type unsigned.
For example, if we were to declare a variable age, we know that an age cannot be represented by negative values and hence, we can modify the default behavior of the int data type as follows:
unsigned int age;
Format Specifiers :
The format specifiers are used in C programming to specify the format of the datatypes.The various format specifiers used in C programming are as follows;


%d : Used for getting integer.
%c : Used for getting character output.
%f : For float value.
%ld : For long integer.
%s : For a string.
%lf : double
Example 2: Display the integer value

/* Display the integer value */
#include
#include
void main()
{
int a;
a=10;
clrscr();
printf("The value of a is %d",a);
getch();
}

Output:
The value of a is 10
Here we are declaring a variable a with its initial value 10. 10 here is an integer constant and every time you try to execute this program, the output will always be 10.

Example 3: Multiple Declarations

/* Multiple Declarations */
#include
#include
void main()
{
int a,b;
a=10;
b=5;
clrscr();
printf("A=%d \nB=%d",a,b);
getch();
}

Output
A=10
B=5

Example 4: Adding two numbers

/* Sample Program to add a value */

#include
#include
void main()
{
int a=10,b=5,c;
clrscr();
c=a+b;
printf("SUM = %d ",c);
getch();

}

Output
SUM = 15

Example 5: Adding two numbers during runtime

/* Sample Program to add a value */

#include
#include
void main()
{
int a,b,c;
clrscr();
printf("Enter A : ");
scanf("%d",&a);
printf("Enter B : ");
scanf("%d",&b);
c=a+b;
printf("SUM = %d ",c);
getch();

}

Output



Example 6: Adding two floating point numbers


#include
#include
void main()
{
float a,b,c;
clrscr();
printf("Enter A : ");
scanf("%f",&a);
printf("Enter B : ");
scanf("%f",&b);
c=a+b;
printf("SUM = %0.2f ",c);
getch();
}

Output
Enter A : 23.5
Enter B : 12.3
SUM = 35.80

Example 7: To display the character

/* Display the Character */
#include
#include
void main()
{
char ch='B';
clrscr();
printf("Given Character is %c",ch);
getch();
}

Output
Given Character is B

Example 8: To display the ASCII value

/* Display the ASCII value */
#include
#include
void main()
{
char ch='B';
clrscr();
printf("The ASCII value of B is %d",ch);
getch();
}

Output
The ASCII value of B is 66

Example 9: To display the character

/* Using Character datatype */
#include
#include
void main()
{
char c;
clrscr();
printf("Enter the character : ");
scanf("%c",&c);
printf("The Character is %c ",c);
getch();
}

Output
Enter the character : B
The Character is B

Example 10: To display the character

/* Display the Character */
#include
#include
void main()
{
char ch[]="Bharathi\nBeatSoft Solutions";
clrscr();
printf("%s",ch);
getch();
}

Output
Bharathi
BeatSoft Solutions


Example 11: To display the character

/* Using Character datatype*/
#include
#include
void main()
{
char c[10];
clrscr();
printf("Enter Name : ");
scanf("%s",&c);
printf("Name is %s ",c);
getch();
}
Output:
Enter Name : Bharathi
Name is Bharathi

getchar()
It is used to reads a character from the standard input device.
putchar()
It is used to writes a character to the standard output device.

Example 12: To display the character

/* getchar() and putchar() */
#include
#include
void main()
{
char ch;
clrscr();
printf("Enter Character : ");
ch=getchar();
printf("Given Character is ");
putchar(ch);
getch();
}
Output
Enter Character : B
Given Character is B

gets()
It is used to receives the string from the standard input device.
puts()
It is used to output the string to the standard output device.

Example 13: To display the String

/* gets() and puts() */
#include
#include
void main()
{
char ch[80];
clrscr();
printf("Enter the name : ");
gets(ch);
printf("The name is ");
puts(ch);
getch();
}
Output :
Enter the name : BeatSoft
The name is BeatSoft

Constant Variables
A constant variable is also called a named constant. A named constant is really a variable whose content is read-only and cannot be changed while the program is running. Here is a declaration of a named constant.
const float pi = 3.14;
It looks just like a regular variable declaration except that the word const appears before the data type name. const is a qualifier that tells the compiler to make the variable read only. Its value will remain constant throughout the programs execution.
An initialization value must be given when declaring a variable with the const qualifier, or an error will result when the program is compiled. A compiler error will also result if there are any statements in the program that attempt to change the contents of a named constant
Operators:
An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations.

Types of operators
1. Arithmetic Operators
2. Assignment Operators
3. Relational / Comparison Operators
4. Logical Operators
5. Bitwise Logical Operators
6. Conditional Operator
7. Increment / Decrement Operator
8. Special Operators
Arithmetic Operators
It is used to performing arithmetic operations.

Operator Meaning
+ Addition or Unary plus
- Subtraction or Unary minus
* Multiplication
/ Division
% Modulus Operator

Example 14 : Program to calculate Simple interest

/* Calculating Simple Interest */
#include
#include
void main()
{
int n;
float p,r,i;
clrscr();
printf("Enter the Principal : ");
scanf("%f",&p);
printf("Enter the no of year : ");
scanf("%d",&n);
printf("Enter the Rate of Interest: ");
scanf("%f",&r);
i=(p*n*r)/100;
printf("\nThe Simple interest is %0.2f",i);
getch();
}

Output:



Example 15 : Program to Convert days to months and days
/* Program to convert Days to Months and Days */
#include
#include
void main()
{
int m,d;
clrscr();
printf("Enter Days : ");
scanf("%d",&d);
m=d / 30;
d=d % 30;
printf("Month = %d , Days = %d ",m,d);
getch();
}

Output
Enter Days :365
Month = 12 , Days = 5

Assignment Operator
An assignment operator (=) is used to assign a constant or a value of one variable to another.
Multiple assignments:
You can use the assignment for multiple assignments as follows:
a = b= c = 10;
At the end of this expression all variables a, b and c will have the value 10. Here the order of evaluation is from right to left. First 10 is assigned to c, hence the value of c now becomes 10. After that, the value of c (which is now 10) is assigned to b, hence the value of b becomes 10. Finally, the value of b (which is now 10) is assigned to a, hence the value of a becomes 10.
Arithmetic Assignment Operators
Arithmetic Assignment operators are a combination of arithmetic and the assignment operator. With this operator, the arithmetic operation happens first and then the result of the operation is assigned.
Statement with simple
assignment operator
Statement with
shorthand operator

a = a + 1
a += 1

a = a – 1
a -= 1

a = a *1
a *= 1

a = a % b
a %= b
Note:
Remember that there is a remarkable difference between the equality operator (==) and the assignment operator (=). The equality operator is used to compare the two operands for equality (same value), whereas the assignment operator is used for the purposes of assignment.
Example 16: Adding two numbers

/* Sample Program to add a value */

#include
#include
void main()
{
int a,b,c;
clrscr();
printf("Enter A : ");
scanf("%d",&a);
printf("Enter B : ");
scanf("%d",&b);
a+=b; /* a=a+b; */
printf("SUM = %d ",a);
getch();

}

Output
Enter A :10
Enter B :5
SUM = 15

Relational Operators :
Relational operators compare between two operands and return in terms of true or false i.e. 1 or 0. In C and many other languages a true value is denoted by the integer 1 and a false value is denoted by the integer 0. Relational operators are used in conjunction with logical operators and conditional & looping statements.
Following are the various relational operators
Operator Meaning
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to

Example 17 : Relational Operators

/* Relational Operators */
#include
#include
void main()
{
int a,b;
clrscr();
printf("Enter A : ");
scanf("%d",&a);
printf("Enter B : ");
scanf("%d",&b);
printf("True is 1 and False is 0");
printf("\na>b is %d",a>b);
printf("\na>=b is %d",a>=b);
printf("\na printf("\na<=b is %d",a<=b);
printf("\na==b is %d",a==b);
printf("\na!=b is %d",a!=b);
getch();
}

Output


Example 18 : Relational Operators

/* Relational Operators */
#include
#include
void main()
{
int a,b;
clrscr();
printf("Enter A : ");
scanf("%d",&a);
printf("Enter B : ");
scanf("%d",&b);
if(a>b)
{
printf("A is biggest number");
}
else
{
printf("B is biggest number");
}
getch();
}

Output:
Enter A : 23
Enter B : 12
A is biggest number

Logical Operators
A logical operator is used to compare or evaluate logical and relational expressions. There are three logical operators available in the C language.
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT



Truth table for Logical AND

A B Output
(A|| B)
False False False
False True False
True False False
True True True

Truth table for Logical OR

A B Output
(A&&B)
False False False
False True True
True False True
True True True


Truth table for Logical NOT

A Output(!A)
False True
True False

Example 19 : Program to find biggest in three numbers

/* Logical Operators */
#include
#include
void main()
{
int a,b,c;
clrscr();
printf("Enter A : ");
scanf("%d",&a);
printf("Enter B : ");
scanf("%d",&b);
printf("Enter C : ");
scanf("%d",&c);
if(a>b && a>c)
{
printf("A is biggest number");
}
else if(b>c)
{
printf("B is biggest number");
}
else
{
printf("C is biggest number");
}
getch();
}

Output:
Enter A : 43
Enter B : 23
Enter C : 56
C is biggest number


Let us take three variables a, b, and c and assume a = 10,b=15 and c=7
a>b && a>c
Here a>b will return false hence 0 and a>c will return true hence 1. Therefore, looking at the truth table 0 AND 1 will be 0. From this we can understand, that this expression will evaluate to false.
The ! (Logical NOT) operator is a unary operator. This operator inverses a logical result.
E.g. if a = 5 and b = 7, then
!(a == b)
will evaluate to be true. This expression works as follows, a==b evaluates to be false, now because of the ! (NOT) operator, the false is inverted to be true.
Bitwise Logical Operators
C has a distinction of supporting special operators known as bitwise operators for manipulation data at bit level. A bitwise operator operates on each bit of data. Those operators are used for testing, complementing or shifting bits to the right on left. Bitwise operators may not be applied to a float or double.

Operator
Meaning

&
Bitwise AND

|
Bitwise OR

^
Bitwise Exclusive

<<
Shift left

>>
Shift right


Example 20 : Bitwise Logical Operators

/* Using Bitwise Logical Operators */
#include
#include
void main()
{
int a=2,b=3,c;
clrscr();
c=a&b;
printf("\nThe Bitwise Logical AND is %d",c);
c=a|b;
printf("\n\nThe Bitwise Logical OR is %d ",c);
c=a^b;
printf("\n\nThe Bitwise Logical XOR is %d",c);
c=a>>1;
printf("\n\n Left Shift of a is %d",c);
getch();
}

Output
The Bitwise Logical AND is 2
The Bitwise Logical OR is 3
The Bitwise Logical XOR is 1
Left Shift of a is 1
Conditional Operator or Ternary Operator
A conditional operator checks for an expression, which returns either a true or a false value. If the condition evaluated is true, it returns the value of the true section of the operator, otherwise it returns the value of the false section of the operator. Its general structure is as follows:
Expression1 ? expression 2 (True Section): expression3 (False Section)
Example:
a=3,b=5,c;

c = (a>b) ? a : b;
The variable c will have the value 5, because when the expression (a>b) is checked, it is evaluated as false. Now because the evaluation is false, the expression b is executed and the result is returned to c using the assignment operator.
Example 21 : Conditional Operators

/* Using Conditional Operator */
#include
#include
void main()
{
int a,b,c;
clrscr();
printf("Enter A : ");
scanf("%d",&a);
printf("Enter B : ");
scanf("%d",&b);
c=a>b?a:b;
printf("The greatest value is %d",c);
getch();
}

Output
Enter A : 23
Enter B : 41
The greatest value is 41

Increment and Decrement Operators
The increment and decrement operators are one of the unary operators which are very useful in C language. They are extensively used in for and while loops. The syntax of the operators is given below
1. ++ variable name
2. variable name++
3. – –variable name
4. variable name– –

The increment operator ++ adds the value 1 to the current value of operand and the decrement operator – – subtracts the value 1 from the current value of operand. ++variable name and variable name++ mean the same thing when they form statements independently, they behave differently when they are used in expression on the right hand side of an assignment statement.

Consider the following
m = 5;
y = ++m; (prefix)

In this case the value of y and m would be 6

Suppose if we rewrite the above statement as

m = 5;
y = m++; (post fix)

Then the value of y will be 5 and that of m will be 6. A prefix operator first adds 1 to the operand and then the result is assigned to the variable on the left. On the other hand, a postfix operator first assigns the value to the variable on the left and then increments the operand.

Example 22 : Increment Operator

/* Using Increment Operator */
#include
#include
void main()
{
int a=10,b=10;
clrscr();
printf("A is %d",a);
printf("\nB is %d",b);
printf("\nA++ is %d",a++);
printf("\n++B is %d",++b);
printf("\nA is %d",a);
printf("\nB is %d",b);
getch();
}

Output


Special Operators
C supports some special operators of interest such as comma operator, size of operator, pointer operators (& and *) and member selection operators (. and ->).
The size of Operator
The operator size of gives the size of the data type or variable in terms of bytes occupied in the memory. The operand may be a variable, a constant or a data type qualifier.
Example
m = sizeof (sum);
n = sizeof (long int);
k = sizeof (235L);
The size of operator is normally used to determine the lengths of arrays and structures when their sizes are not known to the programmer. It is also used to allocate memory space dynamically to variables during the execution of the program.
Example 23 : A program that displays the size of variable types

/* Program to tell the size of the C datatype in bytes */
#include
#include
void main()
{
clrscr();
printf("\n A char is %d byte",sizeof(char));
printf("\n A short is %d bytes",sizeof(short));
printf("\n A short int is %d bytes",sizeof(short int));
printf("\n An int is %d bytes",sizeof(int));
printf("\n A long is %d bytes",sizeof(long));
printf("\n A float is %d bytes",sizeof(float));
printf("\n A double is %d bytes",sizeof(double));
printf("\n A long double is %d bytes",sizeof(long double));
getch();
}
Output:



The Comma Operator
The comma operator can be used to link related expressions together. A comma-linked list of expressions are evaluated left to right and value of right most expression is the value of the combined expression.

Example 24 : Get Maximum and Minimum values of data type

/* Get maximum and minimum values of datatype */
#include
#include
void main()
{
int i=1,j;
clrscr();
while(i>0)
{
j=i;
i++;
}
printf("The minimum value of integer is %d",i);
printf("\n\nThe maximum value of integer is %d",j);
getch();
}

Output
The minimum value of integer is -32768
The maximum value of integer is 32767
Type Casting
Type casting means to convert a higher data type to a lower data type. For the purpose of type casting we require to use the type case operator, which lets you manually promote or demote a value. It is a unary operator which appears as the data type name followed by the operand inside a set of parentheses.
E.g. val = (int)number;

Control Structures
1. Conditional Statements
2. Unconditional Statements
3. Looping Statements
if Statement:
The simplest form of the control statement is the If statement. It is very frequently used in decision making and allowing the flow of program execution.
The If structure has the following syntax
if (condition)
statement;
Nested if Statement
The if statement may itself contain another if statement is known as nested if statement.
Syntax:
if (condition1)
if (condition2)
statement-1;
else
statement-2;
else
statement-3;


Example 25 :Program to find whether given number is even or odd

/* if - else */
#include
#include
void main()
{
int n;
clrscr();
printf("Enter the Number : ");
scanf("%d",&n);
if((n%2)==0)
{
printf("%d is an Even number",n);
}
else
{
printf("%d is an Odd number",n);
}
getch();
}

Output :
Enter the Number : 12
12 is an Even number

Looping Statements

For Loop

Example 26 :
/* for loop */
#include
#include
void main()
{
int i;
clrscr();
for(i=1;i<=5;i++)
{
printf("%d\n",i);
}
getch();
}

Output:
1
2
3
4
5

Example 27 :
/* for loop */
#include
#include
void main()
{
int n,i;
clrscr();
printf("Enter the Number : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\t%d ",3*i);
}
getch();
}

Output
Enter the Number : 5
3 6 9 12 15
Example 28 :

/* for loop */
#include
#include
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("%d ",i);
}
printf("\n");
}
getch();
}

Output
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

Example 29 : Sum of Digits

/* for loop */
#include
#include
void main()
{
int i,n,sum=0;
clrscr();
printf("Enter the Number : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
sum+=i; /* sum=sum+i; */
}
printf("The sum of first %d numbers is %d",n,sum);
getch();
}

Output
Enter the Number :10
The sum of first 10 numbers is 55

Example 30 : Sum of Digits
/* for loop */
#include
#include
void main()
{
int n,i,sum;
clrscr();
printf("Enter the Number : ");
scanf("%d",&n);
for(i=0,sum=0;i {
printf("\n Sum = %d ",sum);
}
getch();
}

Output:
Enter the Number :5
Sum = 0
Sum = 1
Sum = 3
Sum = 6
Sum = 10
Example 31 : Factorial

/* for loop */
#include
#include
void main()
{
int i,n,fact=1;
clrscr();
printf("Enter the Number : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
fact*=i; /* fact=fact*i; */
}
printf("The factorial of %d is %d",n,fact);
getch();
}

Output
Enter the Number : 5
The factorial of 5 is 120
Example 32 :
/* While Loop */
#include
#include
void main()
{
int i=1;
clrscr();
while(i<=5)
{
printf("\nBeatSoft Solutions,Chennai");
i++;
}
getch();
}

Output
BeatSoft Solutions,Chennai
BeatSoft Solutions,Chennai
BeatSoft Solutions,Chennai
BeatSoft Solutions,Chennai
BeatSoft Solutions,Chennai
Example 33 :
/* While Loop */
#include
#include
void main()
{
char name[20],ch='y';
clrscr();
while(ch=='y' || ch=='Y')
{
fflush(stdin); /* fflush() used to clear the Input Stream */
printf("\nEnter the Name : ");
gets(name);
printf("\n\t Do u want to continue(y/n) : ");
scanf("%c",&ch);
}
getch();
}

Output


Example 34 : Program to display arithmetic operator using switch case
/* Switch Case */
#include
#include
void main()
{
int a,b,n,c;
clrscr();
printf("Enter A : ");
scanf("%d",&a);
printf("Enter B : ");
scanf("%d",&b);
printf("\n Select any one case");
printf("\n 1. Addition");
printf("\n 2. Subraction");
printf("\n 3. Multiplication");
printf("\nEnter the Case : ");
scanf("%d",&n);
switch(n)
{
case 1:
c=a+b;
break;
case 2:
c=a-b;
break;
case 3:
c=a*b;
break;
default:
printf("Block terminated");
break;
}
printf("The result is %d",c);
getch();
}

Output
Enter A : 12
Enter B : 23
Select any one case
1. Addition
2. Subraction
3. Multiplication
Enter the Case :1
The result is 35

Example 35 :
/* Switch Case */
#include
#include
void main()
{
int a,b,c;
char op;
clrscr();
printf("Enter A : ");
scanf("%d",&a);
printf("Enter B : ");
scanf("%d",&b);
printf("\n Select any one Operator");
printf("\n + Addition");
printf("\n - Subraction");
printf("\n * Multiplication");
printf("\n Enter the Operator : ");
scanf("%s",&op);
switch(op)
{
case '+':
c=a+b;
break;
case '-':
c=a-b;
break;
case '*':
c=a*b;
break;
default:
printf("Block terminated");
break;
}
printf("The result is %d",c);
getch();
}
Output
Enter A : 12
Enter B : 23
Select any one Operator
+ Addition
- Subraction
* Multiplication
Enter the Operator :+
The result is 35

Example 36 :

/* Switch Case */
#include
#include
void main()
{
char ch;
clrscr();
printf("\n Do u want to continue? (Y/N) : ");
scanf("%c",&ch);
switch(ch)
{
case 'Y':
case 'y':
printf("Welcome to BeatSoft");
break;
case 'N':
case 'n':
exit(0);
break;
default:
printf("Enter Y/N");
break;
}
getch();
}


Arrays
Arrays are collection of similar items (i.e. ints, floats, chars) whose memory is
allocated in a contiguous block of memory.
Example:
Int a=10;
a=20;
printf(“%d”,a);
In the above example,the value of a printed is 20.The value 10 assigned to a before assigning 20 to it.When we assign 20 to a then the value stored in a is replaced with the new value.hence ordinary variables are capable of storing one value at a time.this fact is same for all the datatypes.but in many applications the variables must be assigned to more than one value.This can be obtained with the help of arrays.Array variables are able to store more than one value at a time.

Declare an array
Arrays must be declared before they are used like any other variable
The general form of declaration is:
datatype variable-name[SIZE];

The data type specify the type of the elements that will be contained in the array, such as int,float or char and the size indicate the maximum number of elements that can be stored inside the array.

Types of array
1. One dimensional array
2. Two dimensional array
3. Multi dimensional array

Example 37:
/* Using one dimensional Array */
#include
#include
void main()
{
int i;
float sal[5],sum=0,avg;
clrscr();
printf("\nEnter Salary for 5 Employees : \n");
for(i=0;i<5;i++)
{
scanf("%f",&sal[i]);
}
clrscr();
printf("\n List of Salary \n");
for(i=0;i<5;i++)
{
printf("\n\t%-5.2f",sal[i]);
sum+=sal[i];
}
avg=sum/5;
printf("\nSum of Salary :%-10.2f",sum);
printf("\nAverage of Salary :%-5.2f",avg);
getch();
}

Output
Enter Salary for 5 Employees :
25000
12000
23000
27000
13000

List of Salary
25000.00
12000.00
23000.00
27000.00
13000.00
Sum of Salary : 100000.00
Average of Salary : 20000.00

Example 38 : Ascending Order
/* Sorting Order */
#include
#include
void main()
{
int a[5]={23,21,25,27,17};
int i,j;
clrscr();
printf("Given values are\n\n");
for(i=0;i<5;i++)
{
printf("\t%d",a[i]);
}
for(i=0;i<5;i++)
{
for(j=i+1;j<5;j++)
{
if(a[i]>a[j])
{
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("\n\nThe ascending order is \n\n");
for(i=0;i<5;i++)
{
printf("\t%d",a[i]);
}
getch();
}

Output
Given values are

23 21 25 27 17

The ascending order is

17 21 23 25 27

Example 39:
/* Using one dimensional Array */
#include
#include
#define SIZE 50
void main()
{
char ch[SIZE];
int i;
clrscr();
printf("Enter any String for 50 characters \n\n");
for(i=0;i {
ch[i]=getchar();
}
for(i=0;i {
putchar(toupper(ch[i]));
}
getch();
}
Output



Example 40:Used to find out the length of the String
/* Using one dimensional Array */
#include
#include
void main()
{
char s[20];
int i,length=0;
clrscr();
printf("\nEnter the String : ");
gets(s);
for(i=0;s[i]!='\0';i++)
{
length++;
}
printf("\nLength of %s is %d",s,length);
getch();
}

Output
Enter the String : Bharathi
Length of Bharathi is 8

Example 41: Used to find out the reverse of the String
/* Using one dimensional Array */
#include
#include
void main()
{
char s[20];
int i,len=0;
clrscr();
printf("\nEnter the String : ");
gets(s);
for(i=0;s[i]!='\0';i++)
{
len++;
}
printf("The reverse String is ");
while(len>=0)
{
printf("%c",s[len]);
len--;
}
getch();
}

Output:
Enter the String : Bharathi
The reverse String is ihtarahB

Example 42:

String
A String is an array of characters including alphanumeric and special characters enclosed within double quotation.Every String is terminated with the ‘\0’(null) character.Each character of the string occupies 1 byte of memory.

Declaration and Initialization of String
The above string can also be initialized as follows
Char name[]=”BeatSoft”;
The compiler inserts the null(\o) character automatically at the end of the string.so the initialization of null character is not essential.
Or
Also, character arrays can be initialized as follows
char name[9]={‘B’,’e’,’a’,’t’,’S’,’o’,’f’,’t’};

Display of String with different formats:
The printf() function is used for displaying the various datatypes.The printf() function with %s format specifier is to be used for displaying the string on the screen.
Printf(“%s\n”,name);

String Library Functions
Strlen() - Determines the length of the string
Strcpy() - Copies a string from source to destination
Strncpy() – Copies characters of a String to another String upto the
specified length
Stricmp() –Compares character of two Strings
Strcmp() – Compares Two Strings
Strncmp() - Compares character of two Strings upto the specified length
Strnicmp() – Ignores Case
Strlwr() – Converts Upper case to Lower case
Strupr() – Converts Lower case to Upper case
Strdup() – Duplicates a String
Strchr() – Determines the first occurrence of a given character in a string
Strrchr() – Determines the last occurrence of a given character in a String
Strstr() – Determines the first occurrence of a given String in another String
Strcat() – concatenating two Strings
Strncat() – concatenating two Strings upto specified Length
Strrev() – Reverses all Character of a String
Strset() – Sets all characters of a string with a given argument or symbol
Strnset() – sets specified no of characters of a string with a given argument or symbol
Strspn() – finds upto what length two strings are identical
Strpbrk() – searches the first occurrence of the character in a given string & then display the string starts from that character



File Handling
C supports a number of functions that have the ability to perform basic file operations, which include:
1. Naming a file
2. Opening a file
3. Reading from a file
4. Writing data into a file
5. Closing a file
• Real life situations involve large volume of data and in such cases, the console oriented I/O operations pose two major problems
• It becomes cumbersome and time consuming to handle large volumes of data through terminals.
• The entire data is lost when either the program is terminated or computer is turned off therefore it is necessary to have more flexible approach where data can be stored on the disks and read whenever necessary, without destroying the data. This method employs the concept of files to store data.
File operation functions in C:
Function Name
Operation

fopen()
Creates a new file for use
Opens a new existing file for use

fclose
Closes a file which has been opened for use

getc()
Reads a character from a file

putc()
Writes a character to a file

fprintf()
Writes a set of data values to a file

fscanf()
Reads a set of data values from a file

getw()
Reads a integer from a file

putw()
Writes an integer to the file

fseek()
Sets the position to a desired point in the file

ftell()
Gives the current position in the file

rewind()
Sets the position to the begining of the file
Defining and opening a file:
If we want to store data in a file into the secondary memory, we must specify certain things about the file to the operating system. They include the fielname, data structure, purpose.
The general format of the function used for opening a file is
FILE *fp;
fp=fopen(“filename”,”mode”);

The first statement declares the variable fp as a pointer to the data type FILE. As stated earlier, File is a structure that is defined in the I/O Library. The second statement opens the file named filename and assigns an identifierto the FILE type pointer fp. This pointer, which contains all the information about the file, is subsequently used as a communication link between the system and the program.
The second statement also specifies the purpose of opening the file. The mode does this job.

R open the file for read only.
W open the file for writing only.
A open the file for appending data to it.
For example:
FILE *fp;
To open a file you need to use the fopen function, which returns a FILE pointer. Once you've opened a file, you can use the FILE pointer to let the compiler perform input and output functions on the file.
FILE *fopen(const char *filename, const char *mode);
In the filename, if you use a string literal as the argument, you need to remember to use double backslashes rather than a single backslash as you otherwise risk an escape character such as \t. Using double backslashes \\ escapes the \ key, so the string works as it is expected. Your users, of course, do not need to do this! It's just the way quoted strings are handled in C and C++.

The modes are as follows:
r - open for reading
w - open for writing (file need not exist)
a - open for appending (file need not exist)
r+ - open for reading and writing, start at beginning
w+ - open for reading and writing (overwrite file)
a+ - open for reading and writing (append if file exists)


Consider the following statements:
FILE *p1, *p2;
p1=fopen(“data”,”r”);
p2=fopen(“results”,”w”);
In these statements the p1 and p2 are created and assigned to open the files data and results respectively the file data is opened for reading and result is opened for writing. In case the results file already exists, its contents are deleted and the files are opened as a new file. If data file does not exist error will occur.
Closing a file:
The input output library supports the function to close a file; it is in the following format.
fclose(file_pointer);

A file must be closed as soon as all operations on it have been completed. This would close the file associated with the file pointer.
Observe the following program.
fclose returns zero if the file is closed successfully.

An example of fclose is
fclose(fp);

….
FILE *p1 *p2;
p1=fopen (“Input”,”w”);
p2=fopen (“Output”,”r”);
….

fclose(p1);
fclose(p2)

The above program opens two files and closes them after all operations on them are completed, once a file is closed its file pointer can be reversed on other file.

The getc and putc functions are analogous to getchar and putchar functions and handle one character at a time. The putc function writes the character contained in character variable c to the file associated with the pointer fp1. ex putc(c,fp1); similarly getc function is used to read a character from a file that has been open in read mode. c=getc(fp2).
The program shown below displays use of a file operations. The data enter through the keyboard and the program writes it. Character by character, to the file input. The end of the data is indicated by entering an EOF character, which is control-z. the file input is closed at this signal.

#include< stdio.h >
main()
{
file *f1;
printf(“Data input output”);
f1=fopen(“Input”,”w”); /*Open the file Input*/
while((c=getchar())!=EOF) /*get a character from key board*/
putc(c,f1); /*write a character to input*/
fclose(f1); /*close the file input*/
printf(“\nData output\n”);
f1=fopen(“INPUT”,”r”); /*Reopen the file input*/
while((c=getc(f1))!=EOF)
printf(“%c”,c);
fclose(f1);
}

The getw and putw functions:
These are integer-oriented functions. They are similar to get c and putc functions and are used to read and write integer values. These functions would be usefull when we deal with only integer data. The general forms of getw and putw are:
putw(integer,fp);
getw(fp);
/*Example program for using getw and putw functions*/
#include< stdio.h >
main()
{
FILE *f1,*f2,*f3;
int number I;
printf(“Contents of the data file\n\n”);
f1=fopen(“DATA”,”W”);
for(I=1;I< 30;I++)
{
scanf(“%d”,&number);
if(number==-1)
break;
putw(number,f1);
}
fclose(f1);
f1=fopen(“DATA”,”r”);
f2=fopen(“ODD”,”w”);
f3=fopen(“EVEN”,”w”);
while((number=getw(f1))!=EOF)/* Read from data file*/
{
if(number%2==0)
putw(number,f3);/*Write to even file*/
else
putw(number,f2);/*write to odd file*/
}
fclose(f1);
fclose(f2);
fclose(f3);
f2=fopen(“ODD”,”r”);
f3=fopen(“EVEN”,”r”);
printf(“\n\nContents of the odd file\n\n”);
while(number=getw(f2))!=EOF)
printf(“%d%d”,number);
printf(“\n\nContents of the even file”);
while(number=getw(f3))!=EOF)
printf(“%d”,number);
fclose(f2);
fclose(f3);
}

The fprintf & fscanf functions:
The fprintf and scanf functions are identical to printf and scanf functions except that they work on files. The first argument of theses functions is a file pointer which specifies the file to be used. The general form of fprintf is
fprintf(fp,”control string”, list);
Where fp id a file pointer associated with a file that has been opened for writing. The control string is file output specifications list may include variable, constant and string.
fprintf(f1,%s%d%f”,name,age,7.5);
Here name is an array variable of type char and age is an int variable
The general format of fscanf is
fscanf(fp,”controlstring”,list);
This statement would cause the reading of items in the control string.

Example:

fscanf(f2,”5s%d”,item,&quantity”);
Like scanf, fscanf also returns the number of items that are successfully read.

/*Program to handle mixed data types*/
#include< stdio.h >
main()
{
FILE *fp;
int num,qty,I;
float price,value;
char item[10],filename[10];
printf(“Input filename”);
scanf(“%s”,filename);
fp=fopen(filename,”w”);
printf(“Input inventory data\n\n”0;
printf(“Item namem number price quantity\n”);
for I=1;I< =3;I++)
{
fscanf(stdin,”%s%d%f%d”,item,&number,&price,&quality);
fprintf(fp,”%s%d%f%d”,itemnumber,price,quality);
}
fclose (fp);
fprintf(stdout,”\n\n”);
fp=fopen(filename,”r”);
printf(“Item name number price quantity value”);
for(I=1;I< =3;I++)
{
fscanf(fp,”%s%d%f%d”,item,&number,&prince,&quality);
value=price*quantity”);
fprintf(“stdout,”%s%d%f%d%d\n”,item,number,price,quantity,value);
}
fclose(fp);
}

Random access to files:
Sometimes it is required to access only a particular part of the and not the complete file. This can be accomplished by using the following function:
1 > fseek
fseek function:
The general format of fseek function is a s follows:
fseek(file pointer,offset, position);
This function is used to move the file position to a desired location within the file. Fileptr
is a pointer to the file concerned. Offset is a number or variable of type long, and position in an integer number. Offset specifies the number of positions (bytes) to be moved from the location specified bt the position. The position can take the 3 values.
Value Meaning
0 Beginning of the file
1 Current position
2 End of the file.
Creating a file and output some data
In order to create files we have to learn about File I/O i.e. how to write data into a file and how to read data from a file. We will start this section with an example of writing data to a file. We begin as before with the include statement for stdio.h, then define some variables for use in the example including a rather strange looking new type.

Example 4: File handling
/* Program to create a file and write some data the file */
#include
#include
main( )
{
FILE *fp;
char stuff[25];
int index;
fp = fopen("a.TXT","w"); /* open for writing */
strcpy(stuff,"This is an example line.");
for (index = 1; index <= 10; index++)
fprintf(fp,"%s Line number %d\n", stuff, index);
fclose(fp); /* close the file before ending program */
getch();
}

Output:
Open a.txt file
Reading (r)
When an r is used, the file is opened for reading, a w is used to indicate a file to be used for writing, and an a indicates that you desire to append additional data to the data already in an existing file. Most C compilers have other file attributes available; check your Reference Manual for details. Using the r indicates that the file is assumed to be a text file. Opening a file for reading requires that the file already exist. If it does not exist, the file pointer will be set to NULL and can be checked by the program.
Here is a small program that reads a file and display its contents on screen.

Example 4: File handling

/* Program to display the contents of a file on screen */
#include
void main()
{
FILE *fopen(), *fp;
int c;
clrscr();
fp = fopen("a.txt","r");
c = getc(fp) ;
while (c!= EOF)
{
putchar(c);
c = getc(fp);
}
fclose(fp);
getch();
}
Writing (w)
When a file is opened for writing, it will be created if it does not already exist and it will be reset if it does, resulting in the deletion of any data already there. Using the w indicates that the file is assumed to be a text file.
Here is the program to create a file and write some data into the file.
Example 4: File handling
#include
void main()
{
FILE *fp;
fp = fopen("a.txt","w");
/*Create a file and add text*/
fprintf(fp,"%s","This is just an example :)"); /*writes data to the file*/
fclose(fp); /*done!*/
getch();
}

Example 4: File handling


/* Sample Program to add a value */

#include
#include
void main()
{
FILE *f1,*f2;
char ch;
clrscr();
f1=fopen("Sample.txt","r");
if(f1==NULL)
{
printf("\n File doesn't open");
exit(0);
}
f2=fopen("Sample1.txt","w");
if(f2==NULL)
{
printf("Unable to create");
exit(2);
}
while(1)
{
ch=fgetc(f1);
if(ch==EOF)
break;
else
fputc(ch,f2);
}
printf("\n File Copied");
fclose(f1);
fclose(f2);
getch();

}


Output

File Copied


Appending (a)
When a file is opened for appending, it will be created if it does not already exist and it will be initially empty. If it does exist, the data input point will be positioned at the end of the present data so that any new data will be added to any data that already exists in the file. Using the a indicates that the file is assumed to be a text file.
Here is a program that will add text to a file which already exists and there is some text in the file.
#include
void main()
{
FILE *fp;
fp = fopen("a.txt","a");
fprintf(fp,"%s","This is just an example :)"); /*append some text*/
fclose(fp); /*done!*/
getch();
}
Outputting to the file
The job of actually outputting to the file is nearly identical to the outputting we have already done to the standard output device. The only real differences are the new function names and the addition of the file pointer as one of the function arguments. In the example program, fprintf replaces our familiar printf function name, and the file pointer defined earlier is the first argument within the parentheses. The remainder of the statement looks like, and in fact is identical to, the printf statement.
Closing a file
To close a file you simply use the function fclose with the file pointer in the parentheses. Actually, in this simple program, it is not necessary to close the file because the system will close all open files before returning to DOS, but it is good programming practice for you to close all files in spite of the fact that they will be closed automatically, because that would act as a reminder to you of what files are open at the end of each program.
You can open a file for writing, close it, and reopen it for reading, then close it, and open it again for appending, etc. Each time you open it, you could use the same file pointer, or you could use a different one. The file pointer is simply a tool that you use to point to a file and you decide what file it will point to. Compile and run this program. When you run it, you will not get any output to the monitor because it doesn̢۪t generate any. After running it, look at your directory for a file named TENLINES.TXT and type it; that is where your output will be. Compare the output with that specified in the program; they should agree! Do not erase the file named TENLINES.TXT yet; we will use it in
some of the other examples in this section.
Reading from a text file
Now for our first program that reads from a file. This program begins with the familiar include, some data definitions, and the file opening statement which should require no explanation except for the fact that an r is used here because we want to read it.

Functions
A function is a block of code that has a name and it has a property that it is reusable i.e. it can be executed from as many different points in a C Program as required.
Function groups a number of program statements into a unit and gives it a name. This unit can be invoked from other parts of a program. A computer program cannot handle all the tasks by it self. Instead its requests other program like entities – called functions in C – to get its tasks done. A function is a self contained block of statements that perform a coherent task of same kind
The name of the function is unique in a C Program and is Global. It neams that a function can be accessed from any location with in a C Program. We pass information to the function called arguments specified when the function is called. And the function either returns some value to the point it was called from or returns nothing.
We can divide a long C program into small blocks which can perform a certain task. A function is a self contained block of statements that perform a coherent task of same kind
It has three main parts
1. The name of the function i.e. sum
2. The parameters of the function enclosed in paranthesis
3. Return value type i.e. int
Function Body
What ever is written with in { } in the above example is the body of the function.
Function Prototypes
The prototype of a function provides the basic information about a function which tells the compiler that the function is used correctly or not. It contains the same information as the function header contains. The prototype of the function in the above example would be like
int sum (int x, int y);
The only difference between the header and the prototype is the semicolon ; there must the a semicolon at the end of the prototype.






Pointers
In c,a pointer is a variable that points to or references a memory location in which data is stored. In the computer, each memory cell has an address that can be used to access that location so a pointer variable points to a memory location we can access and change the contents of this memory location via the pointer.

Pointer declaration:
A pointer is a variable that contains the memory location of another variable in which data is stored. Using pointer,you start by specifying the type of data stored in the location. The asterisk helps to tell the compiler that you are creating a pointer variable. Finally you have to give the name of the variable. The syntax is as shown below.
Datatype * variablename;

Example
int *pt;

Address operator:
Once we declare a pointer variable then we must point it to something we can do this by assigning to the pointer the address of the variable you want to point as in the following example:
pt=#


This places the address where num is stores into the variable ptr. If num is stored in memory 21260 address then the variable ptr has the value 21260.

/* A program to illustrate pointer declaration*/

main()
{
int *ptr;
int sum;
sum=45;
ptr=∑
printf (“\n Sum is %d\n”, sum);
printf (“\n The sum pointer is %d”, ptr);
}
we will get the same result by assigning the address of num to a regular(non pointer) variable. The benefit is that we can also refer to the pointer variable as *ptr the asterisk tells to the computer that we are not interested in the value 21260 but in the value stored in that memory location. While the value of pointer is 21260 the value of sum is 45 howeverwe can assign a value to the pointer * ptr as in *ptr=45.

This means place the value 45 in the memory address pointer by the variable ptr. Since the pointer contains the address 21260 the value 45 is placed in that memory location. And since this is the location of the variable num the value also becomes 45. this shows howwe can change the value of pointer directly using a pointer and the indirection pointer.
/* Program to display the contents of the variable their address using pointer variable*/

include< stdio.h >
{
int num, *intptr;
float x, *floptr;
char ch, *cptr;
num=123;
x=12.34;
ch=’a’;
intptr=&x;
cptr=&ch;
floptr=&x;
printf(“Num %d stored at address %u\n”,*intptr,intptr);
printf(“Value %f stored at address %u\n”,*floptr,floptr);
printf(“Character %c stored at address %u\n”,*cptr,cptr);
}
Pointer expressions & pointer arithmetic:
Like other variables pointer variables can be used in expressions. For example if p1 and p2 are properly declared and initializedpointers, then the following statements are valid.

y=*p1**p2;
sum=sum+*p1;
z= 5* - *p2/p1;
*p2= *p2 + 10;

C allows us to add integers to or subtract integers from pointers as well as to subtract one pointer from the other. We can also use short hand operators with the pointers p1+=; sum+=*p2; etc.,
we can also compare pointers by using relational operators the expressions such as p1 >p2 , p1==p2 and p1!=p2 are allowed.

/*Program to illustrate the pointer expression and pointer arithmetic*/
#include< stdio.h >
main()
{
int ptr1,ptr2;
int a,b,x,y,z;
a=30;b=6;
ptr1=&a;
ptr2=&b;
x=*ptr1+ *ptr2 –6;
y=6*- *ptr1/ *ptr2 +30;
printf(“\nAddress of a +%u”,ptr1);
printf(“\nAddress of b %u”,ptr2);
printf(“\na=%d, b=%d”,a,b);
printf(“\nx=%d,y=%d”,x,y);
ptr1=ptr1 + 70;
ptr2= ptr2;
printf(“\na=%d, b=%d”,a,b);
}
Pointers and function:
The pointer are very much used in a function declaration. Sometimes only with a pointer a complex function can be easily represented and success. The usage of the pointers in a function definition may be classified into two groups.
1. Call by reference
2. Call by value.

Call by value:
We have seen that a function is invoked there will be a link established between the formal and actual parameters. A temporary storage is created where the value of actual parameters is stored. The formal parameters picks up its value from storage area the mechanism of data transfer between actual and formal parameters allows the actual parameters mechanism of data transfer is referred as call by value. The corresponding formal parameter represents a local variable in the calledfunction . The current value of corresponding actual parameter becomes the initial value of formal parameter. The value of formal parameter may be changed in the body of the actual parameter. The value of formal parameter may be changed in the body of the subprogram by assignment or input statements. This will not change the value of actual parameters.
/* Include< stdio.h >
void main()
{
int x,y;
x=20;
y=30;
printf(“\n Value of a and b before function call =%d %d”,a,b);
fncn(x,y);
printf(“\n Value of a and b after function call =%d %d”,a,b);
}

fncn(p,q)
int p,q;
{
p=p+p;
q=q+q;
}
Call by Reference:
When we pass address to a function the parameters receiving the address should be pointers. The process of calling a function by using pointers to pass the address of the variable is known as call by reference. The function which is called by reference can change the values of the variable used in the call.

/* example of call by reference*?

/* Include< stdio.h >
void main()
{
int x,y;
x=20;
y=30;
printf(“\n Value of a and b before function call =%d %d”,a,b);
fncn(&x,&y);
printf(“\n Value of a and b after function call =%d %d”,a,b);
}

fncn(p,q)
int p,q;
{
*p=*p+*p;
*q=*q+*q;
}
Pointer to arrays:
an array is actually very much like pointer. We can declare the arrays first element as a[0] or as int *a because a[0] is an address and *a is also an address the form of declaration is equivalent. The difference is pointer is a variable and can appear on the left of the assignment operator that is lvalue. The array name is constant and cannot appear as the left side of assignment operator.

/* A program to display the contents of array using pointer*/
main()
{
int a[100];
int i,j,n;
printf(“\nEnter the elements of the array\n”);
scanf(“%d”,&n);
printf(“Enter the array elements”);
for(I=0;I< n;I++)
scanf(“%d”,&a[I]);
printf(“Array element are”);
for(ptr=a,ptr< (a+n);ptr++)
printf(“Value of a[%d]=%d stored at address %u”,j+=,*ptr,ptr);
}

Strings are characters arrays and here last element is \0 arrays and pointers to char arrays can be used to perform a number of string functions.
Pointers and structures:
We know the name of an array stands for the address of its zeroth element the same concept applies for names of arrays of structures. Suppose item is an array variable of struct type. Consider the following declaration:

struct products
{
char name[30];
int manufac;
float net;
item[2],*ptr;

this statement declares item as array of two elements, each type struct products and ptr as a pointer data objects of type struct products, the

assignment ptr=item;

would assign the address of zeroth element to product[0]. Its members can be accessed by using the following notation.

ptr- >name;
ptr- >manufac;
ptr- >net;

The symbol - > is called arrow pointer and is made up of minus sign and greater than sign. Note that ptr- > is simple another way of writing product[0].

When the pointer is incremented by one it is made to pint to next record ie item[1]. The following statement will print the values of members of all the elements of the product array.

for(ptr=item; ptr< item+2;ptr++)
printf(“%s%d%f\n”,ptr- >name,ptr- >manufac,ptr- >net);

We could also use the notation

(*ptr).number

to access the member number. The parenthesis around ptr are necessary because the member operator ‘.’ Has a higher precedence than the operator *.
Pointers on pointer:
While pointers provide enormous power and flexibility to the programmers, they may use cause manufactures if it not properly handled. Consider the following precaustions usingpointers to prevent errors. We should make sure that we know where each pointer is pointing in a program. Here are some general observations and common errors that might be useful to remember.

A pointer contains garbage until it is initialized. Since compilers cannot detect uninitialized or wrongly initialized pointers, the errors may not be known until we execute the program remember that even if we are able to locate a wrong result, it may not provide any evidence for us to suspect problems in thepointers.


Structures

Arrays are used to store large set of data and manipulate them but the disadvantage is that all the elements stored in an array are to be of the same data type. If we need to use a collection of different data type items it is not possible using an array. When we require using a collection of different data items of different data types we can use a structure. Structure is a method of packing data of different types. A structure is a convenient method of handling a group of related data items of different data types.

structure definition:
general format:
struct tag_name
{
data type member1;
data type member2;


}

Example:
struct lib_books
{
char title[20];
char author[15];
int pages;
float price;
};

the keyword struct declares a structure to holds the details of four fields namely title, author pages and price. These are members of the structures. Each member may belong to different or samedata type. The tag name can be used to define objects that have the tag names structure. The structure we just declared is not a variable by itself but a template for the structure.

We can declare structure variables using the tag name any where in the program. For example the statement,

struct lib_books book1,book2,book3;

declares book1,book2,book3 as variables of type struct lib_books each declaration has four elements of the structure lib_books. The complete structure declaration might look like this

struct lib_books
{
char title[20];
char author[15];
int pages;
float price;
};

struct lib_books, book1, book2, book3;

structures do not occupy any memory until it is associated with the structure variable such as book1. the template is terminated with a semicolon. While the entire declaration is considered as a statement, each member is declared independently for its name and type in a separate statement inside the template. Thetag name such as lib_books can be used to declare structure variables of its data type later in the program.

We can also combine both template declaration and variables declaration in one statement, the declaration

struct lib_books
{
char title[20];
char author[15];
int pages;
float price;
} book1,book2,book3;
is valid. The use of tag name is optional for example
struct
{



}

book1, book2, book3 declares book1,book2,book3 as structure variables representing 3 books but does not include a tag name for use in the declaration.

A structure is usually defines before main along with macro definitions. In such cases the structure assumes global status and all the functions can access the structure.
Giving values to members:
As mentioned earlier the members themselves are not variables they should be linked to structure variables in order to make them meaningful members. The link between a member and a variable is established using the member operator ‘.’ Which is known as dot operator or period operator.

For example:

Book1.price

Is the variable representing the price of book1 and can be treated like any other ordinary variable. We can use scanf statement to assign values like

scanf(“%s”,book1.file);
scanf(“%d”,& book1.pages);

Or we can assign variables to the members of book1

strcpy(book1.title,”basic”);
strcpy(book1.author,”Balagurusamy”);
book1.pages=250;
book1.price=28.50;

/* Example program for using a structure*/
#include< stdio.h >
void main()
{
int id_no;
char name[20];
char address[20];
char combination[3];
int age;
}newstudent;
printf(“Enter the student information”);
printf(“Now Enter the student id_no”);
scanf(“%d”,&newstudent.id_no);
printf(“Enter the name of the student”);
scanf(“%s”,&new student.name);
printf(“Enter the address of the student”);
scanf(“%s”,&new student.address);

printf(“Enter the cmbination of the student”);
scanf(“%d”,&new student.combination);

printf(“Enter the age of the student”);
scanf(“%d”,&new student.age);
printf(“Student information\n”);
printf(“student id_number=%d\n”,newstudent.id_no);
printf(“student name=%s\n”,newstudent.name);
printf(“student Address=%s\n”,newstudent.address);
printf(“students combination=%s\n”,newstudent.combination);
printf(“Age of student=%d\n”,newstudent.age);
}

Initializing structure:
Like other data type we can initialize structure when we declare them. As for initalization goes structure obeys the same set of rules as arrays we initalize the fields of a structure by the following structure declaration with a list containing values for weach fileds as with arrays these values must be evaluate at compile time.

Example:

Struct student newstudent
{
12345,
“kapildev”
“Pes college”;
“Cse”;
19;
};

this initializes the id_no field to 12345, the name field to “kapildev”, the address field to “pes college” the field combination to “cse” and the age field to 19.

Functions and structures:
We can pass structures as arguments to functions. Unlike array names however, which always point to the start of the array, structure names are not pointers. As a result, when we change structure parameter inside a function, we don’t effect its corresponding argument.

Passing structure to elements to functions:
A structure may be passed into a function as individual member or a separate variable.
A program example to display the contents of a structure passing the individual elements to a function is shown below.

# include < stdio.h >
void main()
{
int emp_id;
char name[25];
char department[10];
float salary;
};

static struct emp1={125,”sampath”,”operator”,7500.00};
/* pass only emp_id and name to display function*/
display(emp1.emp_id,emp1.name);
}
/* function to display structure variables*/
display(e_no,e_name)
int e_no,e_name;
{
printf(“%d%s”,e_no,e_name);

in the declaration of structure type, emp_id and name have been declared as integer and character array. When we call the function display() using display(emp1.emp_id,emp1.name);
we are sending the emp_id and name to function display(0);
it can be immediately realized that to pass individual elements would become more tedious as the number of structure elements go on increasing a better way would be to pass the entire structure variable at a time.

Passing entire function to functions:
In case of structures having to having numerous structure elements passing these individual elements would be a tedious task. In such cases we may pass whole structure to a function as shown below:

# include stdio.h>
{
int emp_id;
char name[25];
char department[10];
float salary;
};

void main()
{
static struct employee emp1=
{
12,
“sadanand”,
“computer”,
7500.00
};

/*sending entire employee structure*/
display(emp1);
}

/*function to pass entire structure variable*/
display(empf)
struct employee empf
{
printf(“%d%s,%s,%f”, empf.empid,empf.name,empf.department,empf.salary);
}

Arrays of structure:
It is possible to define a array of structures for example if we are maintaining information of all the students in the college and if 100 students are studying in the college. We need to use an array than single variables.We can define an array of structures as shown in the following example:

structure information
{
int id_no;
char name[20];
char address[20];
char combination[3];
int age;
}
student[100];

An array of structures can be assigned initial values just as any other array can. Remember that each element is a structure that must be assigned corresponding initial values as illustrated below.

#include< stdio.h >
{
struct info
{
int id_no;
char name[20];
char address[20];
char combination[3];
int age;
}
struct info std[100];
int I,n;
printf(“Enter the number of students”);
scanf(“%d”,&n);
printf(“ Enter Id_no,name address combination age\m”);
for(I=0;I < n;I++)
scanf(%d%s%s%s%d”,&std[I].id_no,std[I].name,std[I].address,std[I].combination,&std[I].age);
printf(“\n Student information”);
for (I=0;I< n;I++)
printf(“%d%s%s%s%d\n”, ”,std[I].id_no,std[I].name,std[I].address,std[I].combination,std[I].age);
}

Structure within a structure:
A structure may be defined as a member of another structure. In such structures the declaration of the embedded structure must appear before the declarations of other structures.

struct date
{
int day;
int month;
int year;
};
struct student
{
int id_no;
char name[20];
char address[20];
char combination[3];
int age;
structure date def;
structure date doa;
}oldstudent, newstudent;

the sturucture student constains another structure date as its one of its members.

Union:
Unions like structure contain members whose individual data types may differ from one another. However the members that compose a union all share the same storage area within the computers memory where as each member within a structure is assigned its own unique storage area. Thus unions are used to observe memory. They are useful for application involving multiple members. Where values need not be assigned to all the members at any one time. Like structures union can be declared using the keyword union as follows:

union item
{
int m;
float p;
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 because if only one location is allocated for union variable irrespective of size. The compiler allocates a piece of storage that is large enough to access a union member we can use the same syntax that we use to access structure members. That is

code.m
code.p
code.c

are all valid member variables. During accessing we should make sure that we are accessing the member whose value is currently stored.
For example a statement such as

code.m=456;
code.p=456.78;
printf(“%d”,code.m);
Would prodece erroneous result.
In effect a union creates a storage location that can be used by one of its members at a time. When a different number is assigned a new value the new value supercedes the previous members value. Unions may be used in all places where a structure is allowed. The notation for accessing a union member that is nested inside a structure remains the same as for the nested structure.

Exercises
1. Write a program to display your name on the monitor.
2. Modify the program to display your address and phone number on separate lines by adding two additional printf() statements.
3. Write a program that writes your name on the monitor ten times. Write this program three times, once with each looping method.
4. Write a program that counts from one to ten, prints the values on a separate line for each, and includes a message of your choice when the count is 3 and a different message when the count is 7

Comments

Join as a footSigns Travel Writer...

Name

Email *

Message *