Fundamentals of Computer Programming

1. Introduction to Computer

All digital computers are basically electronic devices that can transmit, store and manipulate information (data). The data may be numeric, character, graphic, and sound. So, a computer can be defined as it is an electronic device which gets raw data as input, processes it and gives result as output, all under instructions given to it.

To process a particular set of data, the computer must be given an appropriate set of instructions, called a program. Such instructions are written using codes which computer can understand. Such set of codes is known as language of computer.

Types of programming language
Many different languages can be used to program a computer. As we know that computer is composed of millions of switches which acts like electric switch. Such a switch has two states, ON and OFF, and can be represented with 1 and 0. So, a computer can understand only 0, and 1, which is known as Binary digits, in short BITS. So, language which uses these binary codes to instruct a computer is known as Machine language. Machine language is very rarely used to instruct a computer because it is very difficult and machine dependent (different machine may need different machine codes).

Instructions written in high level language is more compatible with human languages. Hence, it is easier to instruct computer using it, however it is necessary to be translated into machine codes using translator such as compiler and interpreter. Such programs written in High level language, are portable (can be used in any computer without or with some alteration).

A compiler or interpreter is itself a computer program that accepts a high level program as input and generates a corresponding machine language program as output. The original high level program is called the source program and the resulting machine language program is called the object program. Every high level language must have its own compiler or interpreter for a particular computer.

Introduction to C
It is a high level programming language. Instructions consist of algebraic expressions, English keywords such as if, else, for, do, while etc. In C, a program can be divided into small modules. It is also called as structured programming language.
  • Flexible to use as system programming as well as application programming.
  • Huge collection of operators and library functions.
  • User can create own user defined functions.
  • C compilers are commonly available for all types of computers and program developed in C, can be executed in any computer without or with some alteration, hence it's portable.
  • A program developed in C is compact and highly efficient.
  • Because of modularity, it is easy to debug (to find error).
  • It can also be used as low level language.
History of C
C was developed in the 1970's by Dennis Ritchie at Bell Lab. It was developed from earlier languages, called BCPL and B which were also developed at Bell Lab. It was confined within Bell Lab till 1978. Dennis Ritchie and Brian Kernighan further developed the language. By mid 80's, it became more popular. Later on, it was standardized by ANSI (American National Standard Institute).
Structure of a C program
Every C program consists of one or more functions, one of which must be called main. The program always begins by executing the main function however it contains other functions.
Each function must contain:
·         A function heading, that consists function name and arguments enclosed in parenthesis.
·         A pair of compound statement (curly braces).
·         It may consist of number of input/output statements.
·         Library file access
·         Comments
Program 1:
/* A program to print Hello*/
Comment
#include
Library file access
main( )
Call of main function
{
Compound statement start
printf("\n Hello");
Output statement
}
Compound statement end
Program 2:

/* A Program to find sum of two integer numbers 12, & 17 */

#include
void main( )
{
      int x=12, y= 17;
      z= x + y;
      printf(" sum is %d", z);
}
C Fundamentals
The basic elements of C includes  C character set, identifiers, keywords, data types, constants, variables, arrays, declarations, expressions and statements.
The C character set
C uses uppercase A to Z, the lowercase letters
a to z, the digits 0 to 9 and certain special characters such as:
!           ^          #          %         ^          &         *          (           )           ~ _       -
=          +          \           |           [           ]           {          }          ;           :           '
"           ,           <          .           >          /           ?          (blank)

Most versions of C also allow using @ $.

It can be combination of certain characters such as \n, \t to represent non-printable characters new line, horizontal tab respectively. Such character combination to print non printable character is known as escape sequence.

Identifiers
Identifiers are the names given to various element of program such as variables, functions and arrays. Identifiers consist of letters and digits. Rules are to be followed for identifiers:

Ø  It may consist of character, digits and underscore (_) but first character must be letter.
Ø  It permits uppercase and lowercase but they are not interchangeable.
Ø  It may begin with underscore (_) too.
Ø  Most of C allows 31 chars.
Ø  Space and other special character are not allowed.

eg.        x1, sum, _temp, Table etc.

Some invalid identifiers are
1x, "x", -temp, error flag etc.
Keywords
There are certain reserved words in C, which are called as keywords and such words has predefined meaning. These words can only be used for their intended purpose.

The standard keywords are:
auto
extern
sizeof
break
float
static
case
for
struct
char
goto
switch
const
if
typedef
int
union
default
long
continue
signed
unsigned
do
register
void
double
return
volatile
else
short
while
enum
                       

Some compilers may also include:
ada                         far                          near                       asm                     fortran
pascal                    entry                      huge

Note: keywords must be in lowercase.
Constant
Constant is a basic element of C which doesn't change its value during execution of program. Four basic types of constant in C are:

constant type
example
illegal
integer
200, -5
12,200; 3.0; 10 20; 090; 1-2
floating-point
20.5; -2.5; 1.6e+8
1; 1,00.0; 2e+10.2
character
'a'; '3'; ' '; '\n'
3
string
"anuj"
'st xavier's'

Variables
A variable is an identifier that is used to represent some specified type of information within a designated portion of the program. A variable represents a single data item, that is, a numerical quantity, or a character constant. Such data item can be accessed later in any portion of program by referring name of variable.
Array
An array is an identifier that refers to a collection of data items which all have the same name with different subscript but same data type (i.e. integer, floating point or character). Individual data item in an array is known as array element.

e.g.
            int  a=4, b=5, c=2, d= -5, e=0;
            In terms of array, it can be expressed as follows:
            int  x[5] = {4, 5, 2, -5, 0};
where,
            x[0] = 4
            x[1] = 5
            x[2] = 2
            x[3] = -5
            x[4] = 0
Data types
C supports different types of data, each of which may be represented differently within the computer's memory. But memory requirement for each data type may vary from one compiler to another.

Data type
Description
Memory in bytes
int
integer quantity
2
char
single character
1
float
floating point number
4
double
double precision floating point number
8

Declaration
All variables must be declared before they appear in a program in order to reserve memory space for each data item. A declaration may consist of one or more variables of same data type. A declaration begins with data type following with one or more variables and finally ends with a semicolon.
e.g.
            int   x=6, y=7, z;
            float  a=3.0, b=1.5e+5, c;
            char section='a', name[20] = "Xavier";
Program 3:
/* A Program to find sum of any two input integer numbers */
#include
void main( )
{
      int  x, y;
      printf("\n Enter a number");
      scanf(" %d",&x);
      printf("\n Enter another number");
      scanf("%d",&y);
      z= x + y;
      printf(" sum is %d", z);
}

Program 4:
/* A Program to find area of a circle for input radius */

#include
void main( )
{
      float a, r;
      printf("\n Enter radius");
      scanf(" %d",&r);
      a = 3.1415 * r * r;       
      printf(" \n area of circle is %f", a);
}
Expression
An expression represents a single data item, such as a number or a character. The expression may consist of a single entity, such as a constant, a variable, an array element or a reference to a function. It may consist of some combination of such entities interconnected by one or more operators.
            a > b
            c = a + b
Statement
A statement causes the computer to carry out some action. Three different types of statements are:

Expression statement :
            An expression statement consist of an expression followed with a semicolon.
e.g.
            c = a + b;

Compound statement :
            A compound statement consists of several individual statements enclosed within a pair of braces ( { and }).
e.g.
            {
                        int  x=3;
                        printf ("%d", x);
            }
Control statement :
            A control statement is such a statement which controls execution of other statements.
e.g.
            if(x>0)
                        printf(" x is positive");
           
Symbolic Constant
A symbolic constant is name that substitutes for a sequence of characters. The characters may be numeric, character or string constant. It replaces in place of numeric, character or string constant in the program. While compiling the program, each occurrence of a symbolic constant is replaced with its corresponding character sequence.

A symbolic constant is defined by writing
# define   name    text
e.g.
# define              PI           3.1415
#define               NAME     "Kathmandu"
Program 5:
/* A Program to find area and perimeter of a circle for input radius */

# include
# define  PI  3.1415
void main( )
{
      float a, r, p;
      printf("\n Enter radius of circle");
      scanf("%f",&r);
      a = PI * r * r;
      p = 2*PI*r;
      printf(" \n area of circle is %f", a);
      printf(" \n perimeter of circle is %f", p);
}

Problem 1:             Write a program to find area of a triangle for input base and height.
Problem 2:             Write a program to find Total Amount for input Rate and Quantity.
Problem 3:             Write a program to convert length in cm to inch for input length.
Problem 4:             Write a program to convert temperature in Celsius to temperature in Fahrenheit for input temperature.

2. Operator
Operator is a symbol that is used to combine data items such as constant, variable, function reference and array element to form an expression. The data item that acts upon is called Operand.
e.g.
c = a + b
In this expression, = and + are the operators which combines variables a, b and c.

UNARY OPERATOR
Operator that acts upon a single operand is known as Unary Operator. Some unary operators are -, ++, --, sizeof, type
e.g.
            -x;        i++; sizeof(a); (float) 5/3;

Program 1.
/* Program to differentiate use of unary operator as prefix and suffix */

#include
void main()
{
            int x=5;
            printf("%d",x);
            printf("%d",x++);
            printf("%d",x);
           
printf("%d",++x);
            printf("%d",x);

}

Program 2.
/* Program to illustrate use of sizeof and type operators */

#include
void main()
{
            int x=5,y=4;
            float z;
            printf("size of x is %d bytes",sizeof(x));
            printf("%d",x/y);
            printf("size of z is %d bytes",sizeof(z));
            printf("%f",(float)x/y);
}

ARITHMETIC OPERATOR
The operators which are used for general mathematical operations, are called as Arithmetic operators. The five arithmetic operators are +, -, *, /, %.
Here, % is known as modulus operator which returns reminder after integer division.

Program 3.
/* to differentiate /(division) and % (modulus operator)*/
void main()
{
            int x=5,y=2, z1,z2;
            z1=x/y;
            z2=x%y;
            printf("\n Quotient : %d",z1);
            printf("\n Remainder : %d",z2);
}
RELATIONAL OPERATOR
Relational operators are used to compare two data items. There are four relational operators, they are >, <, >=, <=.
e.g.
            (x>y)

Program 4.

/* Program to check whether user can or cannot vote*/
main()
{
            int age=25;
if(age>=18)
                        printf("\n You can vote.");
else
                        printf("\n You cannot vote.");
}

EQUALITY OPERATOR
Equality operator is also used to compare two data items whether they are equal or not. There are two equality operators, ==, !=.

Program 5.
/* Program to show whether input number is positive, zero or negative*/

void main()
{
            int n;
if(n>0)
                        printf("\n %d is positive.",n);
else if(n==0)
                        printf("\n %d is zero.",n);
            else
                        printf("\n The number %d is negative");
}

LOGICAL OPERATOR
The logical operator acts upon operands those are themselves logical expression. Such logical expressions are combined together to form more complex expression. The two logical operators are logical and (&&) and Logical or (||).

Program 6.
/* Program to find highest number among three input integer numbers */

void main()
{
            int x,y,z;

printf("\n enter three integer numbers");
scanf("%d%d%d",&x,&y,&z);

if(x>y && x>z)
                        printf("%d is the highest number",x);
else if(y>x && y>z)
                        printf("%d is the highest number",y);
else
                        printf("%d is the highest number",z);

}

Program 7.
/* Program to check whether user can or cannot apply for DV */

#include

void main()
{
            int age;

printf("\n enter your age");
scanf("%d",&age);

printf("\n enter your qualification (no. of years)");
scanf("%d",&qual);

printf("\n enter your experience (no. of years)");
scanf("%d",&exp);

if(age >= 18 && (qual >= 12 || exp >= 2)
                        printf(" You can apply");
else
                        printf("You cannot apply ");

}

CONDITIONAL OPERATOR
Simple conditional operator can be carried out with conditional operator (? :). It can be written in place of if...else statement. It can be used in this form.
expression1 ? expression2 : expression3;
e.g.
            (n>0) ? printf("+ve no.") : printf("-ve no.");
ASSIGNMENT OPERATOR
This type of operator assigns some value to left of operator after executing expression to its right. Some assignment operators are =, +=, -=, *=, /=, %=.

e.g.
            x+=2                            equivalent to                                                             x=x+2
            x-=3                             equivalent to                                                             x=x-3
            x*=2                            equivalent to                                                             x=x*2
            x/=2                             equivalent to                                                             x=x/2
            x%=2                           equivalent to                                                             x=x%2
  
Operator precedence
            Precedence is the hierarchical order of operators. Operation with higher precedence group is carried out before lower precedence group.
            Another important consideration is the order in which consecutive operations within the same precedence group are carried out. This is known as associativity.

Type
Operators
Associativity
Unary
-, ++, --, sizeof, type
R à L
Arithmetic
*, /, %
L à R

+, -
L à R
Relational
<, <=, >, >=
L à R
Equality
==, !=
L à R
Logical
&&
L à R

| |
L à R
Conditional
? :
R à L
Assignment
=, +=, -=, *=, /=, %=
R à L

e.g.  a – b/c * d
            First, it evaluates b/c then multiplies with d and finally result is subtracted from a.

            c+= (a>0 && a<=10) ? ++a : a/b;
            if a, b & c have values 1, 2 & 3 respectively, then result will be c=5;
            if a, b & c have values 50, 10 & 20 respectively, then result will be c=25;

3. Library Functions

Library functions are pre-defined module in header files which can easily be accessed anywhere in the program by including its respective header file. Library function is the one of the important feature of C language. Because of huge collection of library function, it makes easier for the programmers while programming.

Library functions are defined for
Ø       commonly used operations such as sqrt to find square root, pow to find power of any base etc.
Ø       machine dependent standard input/output operations.


A library function is accessed simply by writing the function name, followed with list of arguments that represents information being passed to the function. The arguments must be enclosed in parentheses and separated by comma(s). The argument can be constant, or variable. But the parentheses must be present, even if there is no argument.

Some commonly used library functions:
abs(i)                  -      returns absolute value of i
clrscr()               -      to clear screen
getch()               -      to input a character without echo
getche()             -      to input a character with echo
tolower(c)         –      to convert a letter to lowercase
toupper(c)         –     to convert a letter to uppercase
sin(d)                 -       return sine of d
cos(d)                -      return cosine of d
tan(d)                -     return tangent of d
sqrt(d)               -     return square root of d
pow(d1,d2)       -     return d1 raised to power d2
log(d)                -     return natural logarithm to d
exp(d)               -   return e raise to power d

Program 8.
/*To convert an input char to capital letter*/

 #include
 #include
 #include
 void main()
 {
            char c;
            c=getche();
            putch(toupper(c));
}

Program 9.
/*To find value of sine of angle 30 degree*/
 #include
 #include
 #include
 #define PI 3.141593

 void main()
 {
            float x=30;
            clrscr();
            printf("%f",sin(x*(PI/180)));
            getch();
 }

Program 10.
/*To find value of antilog of log of specified no.*/
 #include
 #include
 #include
 void main()
 {
            float x=1,y;
            clrscr();
printf("%f",log(x));

            printf("%f",exp(log(x)));
            getch();
 }

Input data using Scanf Function
This function can be used to enter any combination of numerical values, single characters and strings. The function returns the number of data items that have been entered successfully.

scanf(control string, arg1,arg2,...argn)
            where control string refers to a string containing certain required formatting information. arg1, arg2, ... argn represents the individual input data items.

Within the control string comprises individual group of characters, with one character group of each input data item.  Each character group must begin with a percent sign (%) followed with a conversion character which indicates the type of the corresponding data items.

Conversion
character                             Meaning
c                               data item is a single character
d                               data item is an integer without decimal
e                               data item is a floating point value in exponent form
f                                data item is a floating point value
g                               data item is a floating point value without trailing zeros.

h                               data item is a short integer
i                                data item is a signed integer number
l                                data item is long integer
o                               data item is an octal integer
s                                data item is a string followed by a whitespace character
u                               data item is unsigned integer
x                               data item is a hexadecimal integer
[...]                            data item is a string which may include white space

/* To print a line of input text without white space */

#include
#include

void main()
{

char x[20];

printf("\n Enter a string");
scanf("%s",x);

printf("%s",x);

getch();
}

/* To print a line of input text with white space */

#include
#include

void main()
{

char x[20];

printf("\n Enter a string");
scanf("%[^\n]",x);

printf("%s",x);

getch();
}


/*displaying a floating point number with diff format*/
#include
#include
void main()
{
float x=123.456;
printf("%f %.2f ",x,x);
printf("%e %.2e",x,x);
printf("%g %.2g",x,x);

getch();
}

Output:
123.456000                                               123.46
1.234560e+02                                           1.23e+02
123.456                                                     1.23e+02


Program 11.
/* To convert an integer number into hexadecimal number */
#include
#include
void main()
{
            int x=65;
            clrscr();

            printf("%d",x);
            printf("%c",x);
            printf("%x",x);
            printf("%o",x);

}

Program 12.
/* To print unsigned integer and long integer number */
#include
#include
void main()
{
            unsigned int x=65535;
            long int y=2000000000;

            printf("\n%u",x);
            printf("\n%ld",y);

      getch();
}
4. Control Statement

There may be a statement in a program which control the execution of other statement, such type of statement is known as Control Statement. It controls the sequence of execution of program.
Some logical test may be carried out at particular point of program. Then one action will be carried out depending upon the outcome of logical test which is known as conditional execution. It may execute a group of statements among several groups of statements, which is known as selection.
Examples of control statements are if...else, for, while, do...while, switch...case, break, continue, goto.
Many programs require that a group of instructions can be executed repeatedly, until some logical condition is satisfied. This is known as looping.
if...else statement
It carries out a logical test and then takes one of two possible actions, depending upon the outcome of test. But the else portion is optional.
if
{
            Statement1; Statement2; ...     Statement n;
}
else
{
            Statement1; Statement2; ...     Statement n;
}

If the expression is TRUE, it executes the group following if statement, otherwise executes the groups of statement following else statement.

/* To check whether input character is capital or small letter */
#include
#include
void main()
{
char x;
clrscr();
printf("Press any alphabet key");
x=getch();

if(x>='A'&&x<='Z')
            printf("\nIt's capital letter");
else
            printf("\nIt's small letter");
getch();
}

if...else if ... else statement
It carries out logical tests and then takes of one of number of possible actions, depending upon the outcome of test.
if
{
            S1; S2; ...         Sn;
}
else if
{
            S1; S2; ...         Sn;
}
....
else if
{
            S1; S2; ...         Sn;
}

else
{
            S1; S2; ...         Sn;
}


/* To check whether input character is capital, small, digit or other character */
#include
#include
void main()
{
char x;
clrscr();
printf("Press any alphabet key");
x=getch();
if(x>='A'&&x<='Z')
            printf("\nIt's capital letter");
else if(x>='a'&&x<='z')
            printf("\nIt's small letter");
else if(x>='0'&&x<='9')
            printf("\nIt's digit");
else
            printf("\nIt's other character");
getch();
}

goto statement
The goto statement is used to alter normal sequence of program execution by transferring its control to some other part of program.
syntax:
            goto label;
                        where, label is an identifier to which the control is to be transferred. Label should be given at any part of program where the control is to be transferred, followed with a colon(:).

/* To print integer numbers from 1 to 10 */
#include
main()
{
            int i=1;
start:
            if(i<=10)
            {         
printf("\n %d",i);
                        i++;
                        goto start;
            }
}

for statement
The for statement is the most commonly used as looping statement. It includes 3 expressions in which first expression initializes index (counter), second expression determines whether the loop is to be continued or not and third expression modifies index (counter) value. So, third expression is generally unary or assignment expression is used.

The general form of for statement is as follows:
for(expression 1; expression 2; expression 3)

When for loop is executed, first it initializes counter as specified in expression 1, then evaluates the expression 2 whether the loop is to be continued or not. If the expression 2 is satisfied (TRUE or 1) then only the group of statements within the loop is executed. And finally, only the expression 3 is executed by modifying the counter. So, the loop is continued until expression 2 is FALSE or 0.

/* To display a message 10 times */
#include
main( )
{
            int i;
            for(i=0; i<10 b="" i="">

            {
                        printf("\n Good Morning");
            }
}


/* To print 10 consecutive integer numbers */
#include
main( )
{
            int i;
            for(i=1; i<=10; i++)
            {
                        printf("\n %d", i);
            }
}

/* To print odd integer numbers between 1 to 50 */
#include
main( )
{
            int i;
            for(i=1; i<=50; i+=2)
            {
                        printf("\n %d", i);
            }
}

Infinite For loop
Infinite loop occurs when the expression 2 in the For loop is TRUE for infinite times.
e.g.
            for(i=0;i<10 b="">
But,
            for(i=0;i<10 b="" i--="">
            is not infinite loop.
Null Loop
            It executes without any embedded statements.
            for(i=0;i<10 b="" i="">
                        This loop executes 10 times without executing any other statements. But final value of counter will be 11 after completion of loop.

           
While Statement
The While loop is also used to carry out looping operations. Generally it is used for prior unknown steps of loops to be executed whereas the For loop is used for prior known steps of loops to be executed.
The general form of While statement is :

while(expression)
The while loop is executed repeatedly till the expression is TRUE (not zero). So, it is used for unknown loops till some condition is not satisfied within the While loop.

Counter is initialized before the loop and modified within the loop, if necessary.

/* To print 10 consecutive integer numbers using while loop */
#include
main( )
{
            int i=1;
            while(i<=10)
            {
                        printf("\n %d", i);
                        i++;
            }
}


/* To find sum of positive integer numbers until negative number is entered */

#include
#include

void main()
{
            int x=0,sum=0;

            while(x>=0)
            {
                        sum+=x;
scanf("%d",&x);
            }
            printf("\n%d",sum);
            getch();
}
do... while statement
Nested loops
When a loop is written using while or for statements, the condition is checked at the beginning of each pass. Whereas, it may require to write such a loop in which condition is to be checked at end of each pass whether the loop is to be continued. So, such a loop can be achieved by means of do... while statement.
The general form of do...while statement is:
do{
            statements;
            }while(expression);

The statements within the loop will be executed as long as the expression is TRUE. The statements will be executed at least once however the expression is never satisfied. It is better to test the condition before the continuation of loop. So, for & while statements are frequently used with comparing to do...while statement.
If necessary to initialize & modify counter, it can be performed as in while statement.
/* To print 1 to 10 consecutive integer numbers */
#include
#include
void main()
{
            int i=1;
            do{
                        printf("\n %d",i);
                        i++;
            }while(i<=10);
            getch();
}
/* To convert a line of input lowercase text to uppercase */
#include
#include
#include
void main()
{
            char x[80];
            int i=-1;
            clrscr();
            do        {
                                    i++;
                        } while((x[i]=getchar())!='\n');

            k=i;
            i=0;
            while(i
            {
                        putchar(toupper(x[i]));
                        i++;
            }
            getch();
}
One loop can be embedded within another loop without overlapping each other, is known as Nested loops. It may be consist of different control statements as inner loop and outer loop, but index must be different for different loop.
/* To print multiplication tables of integer numbers 1 to 10 */
#include
#include
void main()
{
            int i,k;
            for(k=1;k<=10;k++)
            {
                        for(i=1;i<=10;i++)
                        {
                                    printf("\n %d x %d = %d",i,k,i*k);
                        }
getch();
}
}
Switch Statement
The switch statement is used to execute particular group of statement among available groups of statements. The selection depends upon the current value of expression following switch statement.
The general form of switch statement is:
switch (expression)
{
            case label1:
            {
                        statements;
                        break;
            }
            case label2:
            {
                        statements;
                        break;
            }
            .......................
            .......................
            case labeln:
            {
                        statements;
                        break;
            }
            default:
            {
                        statements;
            }

            where, expression may be int or char type.

Switch statement is similar to if...else if...else statement, but switch statement executes faster with comparing to if...else if...else because it directly executes the matching group of statement from the available groups of statements. But, the case label (case prefix) must be unique for each group.

/* To find sum, difference, product or quotient of any two input integer numbers using integer type expression*/

#include
#include
#include

void main()
{
            clrscr();
            int n,m,r=0;
            int c;
            printf("enter 2 no.");
            scanf("%d%d",&n,&m);
start:
            printf("\n1. sum");
            printf("\n2. diff");
            printf("\n3. product");
            printf("\n4. quotient");
            printf("\n Select numbers (1-4)");
            scanf("%d",&c);
            switch(c)
            {
                        case 1:
                        {
                                    printf("\nsum is %d",n+m);
                                    break;
                        }

                        case 2:
                        {
                                    printf("\n Difference is %d",n-m);
                                    break ;
                        }
                        case 3:
                        {         
                                    printf("\n Product is %d",n*m);
                                    break;
                        }

                        case 4:
                        {
                                    printf("\n Quotient is %f",(float)n/m);
                                    break;
                        }

                        default:
                        {
                                    printf("\n wrong selection");
                                    goto start;                   
                        }
            }
getch();
}



/* To find sum, difference, product or quotient of any two input integer numbers using char type expression*/

#include
#include
#include

void main()
{
            clrscr();
            int n,m,r=0;
            char c;
            printf("enter 2 no.");
            scanf("%d%d",&n,&m);
start:
            printf("\n1. sum");
            printf("\n2. diff");
            printf("\n3. product");
            printf("\n4. quotient");
            printf("\n Select numbers (1-4) or first char(s,d,p or q)");

            c=getch();
           
            switch(toupper(c))
            {
                        case 'S':
                        case '1':
                        {
                                    printf("\nsum is %d",n+m);
                                    break;
                        }

                        case 'D':
                        case '2':
                        {
                                    printf("\difference is %d",n-m);
                                    break ;
                        }
                       
                        case 'P':
                        case '3':
                        {
                                    printf("\nproduct is %d",n*m);
                                    break;
                        }
                        case 'Q':
                        case '4':
                        {
                                    printf("\nquotient is %f",(float)n/m);
                                    break;
                        }
                        default:
                        {
                                    printf("\n wrong selection");
                                    goto start;
                        }
            }

getch();
}
break statement
The break statement is used to exit from a loop or from switch statement by transferring control out of entire loop or switch. It can be used within for, while, do...while or switch control statement.

It can be simply called as,
            break;

continue statement
The continue statement is used to bypass the remainder statements of current step of loop but it continues the remaining steps of loop. So, it only skips the remaining statements of current step of loop.

It can also be used within for, while or do...while control statement as break statement.

/* To find sum of non negative integer numbers until negative number is entered*/
#include
#include
void main()
{
            int i,sum=0,x;
            printf("\nEnter integer numbers");
            for(i=0;i<10 b="" i="">
            {
                        scanf("%d",&x);

                        if(x<0 b="">
                                    break;
                        sum+=x;
            }
            printf("\n Total is: %d",sum);
}

/* To find sum of non negative integer numbers among 10 input integer numbers*/
#include

void main()
{
            int i,sum=0,x;
            printf("\nEnter integer numbers");
            for(i=0;i<10 b="" i="">
            {
                        scanf("%d",&x);
                        if(x<0 b="">
                                    continue;
                        sum+=x;
            }
            printf("\n Total is: %d",sum);
}

The comma operator
The comma operator is used to permit two expressions where generally one expression is used. Such as:

for(expn1a,expn1b;expn2;expn3a,expn3b)
            where, expn1a and expn1b are the two expressions which initializes two counters(index); expn2 checks whether the loop is to be continued or not; and finally, expn3a & expn3b modifies the counters.

/* To check whether the input string is palindrome or not */

#include
#include
#define EOL '\n'
#define TRUE 1
#define FALSE 0
void main()
{
            char x[80];
            int tag,i, k,flag;
            flag=TRUE;
            printf("\nPlease enter a word, phrase or sentence");

            /* To input a string */
            for(i=0;(x[i]=getchar())!=EOL;i++)
                        ;
            tag=i-1;

/* To check whether input string is palindrome/not */
            for((i=0,k=tag);i<=tag/2;(i++,k--))
            {
                        if(x[i]!=x[k])
                        {
                                    flag=FALSE;
                                    break;
                        }
            }
/* To display the string */
            for(i=0;i<=tag;i++)
            {
                        putchar(x[i]);
            }

            if(flag)
                        printf(" is a palindrome");
            else
                        printf(" is not a palindrome");
}

 5. Program Structure
            In earlier chapters, we've used local variables, which have scope within the single function in which the variable is defined. Such variable is not recognized in other functions. However, the same name is used in other functions; it is required to re-define the variable. In other words, it reserves different memory for both the variables however same name is used.
            But, in some situations, it may require to define a variable in such a way so that the scope of variable remains more than one function or throughout the program from the point of its definition.

            So, permanence of a variable and its scope within the program is characterized with Storage Class. It shows the portion of program over which the variable is recognized.
            Hence, we can say that a variable has two characteristics, one data type and another storage class.
            The four types of storage class are –
            automatic, external, static and register which can be defined using keywords auto, extern, static and register respectively. Some typical variables can be declared as follows:

auto int a,b,c;
extern char name[10];
static int x;

Automatic variable
Automatic variables are always declared within a function and its scope retains within the function only in which they are declared. So, same name can be used as variables in different functions and different memories are allocated for them. Hence such variables are also known as local variables. While declaring automatic variable within a function, it is not required to use auto keyword i.e. auto is optional.

#include
#include
#include

float quad(int a, int b,int c, int i)
{
            float x=(-b+i*(sqrt(pow(b,2)-4*a*c)))/(2*a);
            return x;
}

void main()
{
            clrscr();
            auto int a=4,b=5,c=1;
            float x,y;

            x=quad(a,b,c,1);
            y=quad(a,b,c,-1);

            printf("\n %f",x);
            printf("\n %f",y);

getch();
}


External variables
The scope of external variable extends from the point of definition throughout the remainder of program. Since the variable is recognized throughout the program from the point of declaration, it retains its values. Hence, external variable can be assigned a value within a function and can be used within another function. It provides a convenient way for transferring information back and forth between functions without using arguments. One more, it can return more than one data items from a function without using RETURN statement.

/* To find real roots of quadratic equation */
#include
#include
#include

int a=4,b=5,c=1;

float quad(int i)
{
            float x=(-b+i*(sqrt(pow(b,2)-4*a*c)))/(2*a);
            return x;
}

void main()
{
            clrscr();

            float x,y;

            x=quad(1);
            y=quad(-1);

            printf("\n %f",x);
            printf("\n %f",y);
getch();
}

/* To find real root of quadratic equation */

#include
#include
#include


extern int a=4,b=5,c=1;

float x,y;

void quad()
{
            x=(-b+(sqrt(pow(b,2)-4*a*c)))/(2*a);
            y=(-b-(sqrt(pow(b,2)-4*a*c)))/(2*a);

}

void main()
{
            clrscr();
            quad();
           
            printf("\n %f",x);
            printf("\n %f",y);

getch();
}

Static Variable
            Static variable is defined within individual functions and therefore has the same scope as automatic variable. So, it is similar to automatic variable i.e. local to the current function in which it is defined. But, Static variable retains its previous values throughout the life of program however the function (in which static variables are defined) is re-called after exit.
            Static variable is defined in the same way as automatic variable with keyword static before data type of variables which shows static storage class.

#include
#include
long int fact(int i)
{
            static long int x=1;
            return(x*=i);
}

void main()
{
            long int y;
            int a=6;
            for(int i=1;i<=a;i++)
                        y=fact(i);

            printf("\n %ld",y);
}

It's unusual to define automatic or static variable having the same names as external variables. If happened, local variables will take precedence over the external variables. But it doesn't affect the values of external variables.

Here is one skeletal structure of a C program showing various storage class.

float a,b,c;

main()
{
            static float a;
            void dummy(void);
            ....
}

void dummy(void)
{
            static int a;
            int b;
            ........
}

6. Array
Some programs may need to handle same type of different number of data  having same characteristics. In such situation, it will be easier to handle such data in Array, where same name is shared for all data with different subscripts. In an array, all the data items must be of same type and same storage class. Eg. either int, floating point or characters
Each array element (individual array element) is denoted with a name followed by one or more subscripts (where each subscript must be non negative integers within a pair of square bracket).
The number of subscript depends on the dimensionality of the array. Eg. a[i] refers to an element of one dimensional array. Whereas b[i][j] refers to an array element of two dimensional array. In the same manner c[i][j][k] for three dimensional array.
Defining an array
Array is also defined in the same manner as ordinary variables, but it should also include the size of specification that shows the maximum size of elements in that array. The size must be defined with a constant ie. cannot be used any variable as subscript while defining an array. But it can be a symbolic constant while defining size of an array.
It is defined such as follows:
Storage_class data_type array[expression];
e.g.      int x [5];
            float y[3][4];
            char name [MAX];      where MAX is symbolic constant.

Prog 1:
To store integer nos in an array and print them (1 dim)

#include

void main()
{
            int i, x[10]={4,5,2,8,4,7,9,6,5};

            printf("\n The stored numbers in the array are:");
           
            for(i=0;i<10 b="" i="">
            {
                        printf("\n %d", x [ i ] );
            }
}


Prog 4:
To sort a list of integer numbers in ascending order.

#include

void main()
{
            int i,k, temp, x[10];

            printf("\n Enter numbers to be sorted :");
           
            for(i=0; i<10 b="" i="">
            {
                        scanf("%d", &x [ i ] );
            }

            for(i=0;i<9 b="" i="">
            {
                        for(k=i+1;k<10 b="" k="">
                        {
                                    if(x [ i ] > x [ k ]  )
                                    {
                                                temp = x [ i ];
                                                x [ i ]= x [ k ];
                                                x [ k ]= temp;
                                    }
                        }
            }



            printf("\n The sorted numbers are:");
           
            for(i=0;i<10 b="" i="">
            {
                        printf("\n %d", x [ i ] );
            }
}



Two dimensional array
Prog 5:
To store numbers in a two dimensional array and print them
#include
#include


void main()
{
            int i,k,x[2][3]={1,2,3,4,5,6};
            for(i=0;i<4 b="" i="">
            {
                        for(k=0;k<4 b="" k="">
                        {
                                    printf("%d\t",x[i][k]);
                        }
                        printf("\n");
            }
}

Prog 7:
Write a program to find out sum of two matrices of size 2x3

#include
#include
void main()
{
            int i,k,x[2][3],y[2][3],z[2][3];

            for(i=0;i<4 b="" i="">
            {
                        for(k=0;k<4 b="" k="">
                        {
                                    scanf("%d",&x[i]);
                        }
            }

            for(i=0;i<4 b="" i="">
            {
                        for(k=0;k<4 b="" k="">
                        {
                                    scanf("%d",&y[i]);
                        }
            }

            for(i=0;i<4 b="" i="">
            {
                        for(k=0;k<4 b="" k="">
                        {
                                    z[i][k]=x[i][k] + y[i][k];
                                    printf("%d\t",z[i][k]);
                        }
                        printf("\n");
            }
}


Modify it for any size.

Prog 8:
To find out product of two matrices of size 3x2 & 2x3.

Passing array to a function

Prog 9:
To pass a list of numbers into user defined function to change values of array.

#include

void modify (int x[ ])
{
            int i;
            for(i=0;i<3 b="" i="">
            {
                        x [ i ]=9;
            }


}

void main()
{
            int i, x[10];

            printf("\n Enter numbers to be stored in the array :");
            for(i=0;i<3 b="" i="">
            {
                        scanf("%d", &x [ i ] );
            }

            modify(x);
            printf("\n The stored numbers in the array are:");
           
            for(i=0;i<3 b="" i="">
            {
                        printf("\n %d", x [ i ] );
            }
}

Prog 10:
7. Structure
Sometime, it may require to process multiple data stucture whose individual data elements  can be differ in type. In a single structure may contain integer element, floating point   element and character element. It may consists of arrays, pointers and other structures as element of the structure.
So, a combination of data structure with various type of elements within the same storage class, is known as structure in C.
Defining a structure
It is a little bit difficult to define a structure with comparing to an array. Since in a structure, it may consist of various data elements and each data element is to be defined separately within the structure such as:
struct tag {
            member 1;
member 2;
member 3;
…………..
………….
member m;
};

where struct is a keyword which defines the following combination is a structure.
tag represents the name of structure of combined members included within compound statement.
and, member 1,member 2, member 3,……..member m are the individual declaration of elements of current structure.
  • The individual member can be ordinary variable, array, pointer or other structure.
  • The name must be distinct from another structure.
  • But the member name of the structure and outside the structure may be same but refers to different identity.
  • Storage class can not be defined for individual members and also cannot be initialized individual members within the structure.

Once the composition of structure has been defined, individual structure type variables can be declared as follows:

storage_class struct tag variable 1, variable 2, variable 3, ……., variable n;

where, storage class is optional.
struct is required keyword to declare following variables as structures.
tag is the name of the structure
and variable 1, variable 2, variable 3 are the structure variables.
e.g.
struct account {
            int acctno;
            char acct_type;
char name[80];
            float balance;
};

struct account oldcustomer, newcustomer;

It is also possible to combine the declaration of structure with structure variables as follows:

storage_class struct tag {
member 1;
member 2;
member 3;
…………..
………….
member m;
}variable 1, variable 2, variable 3, ……., variable n;

Note : tag is optional in this case.

struct account {
int acctno;
char acct_type;
char name[80];
float balance;
} oldcustomer, newcustomer;

A structure may also consist of another structure as a member of structure but the embedded structure must be declared before the outer structure.
eg.
struct  date {
            int month;
            int day;
            int year;
};

struct account {
int acctno;
char acct_type;
char name[80];
float balance;
struct date lastpayment;
} oldcustomer, newcustomer;

The member of a structure can not be initialized within the structure. It can be initialized in the same order as they are defined within the structure as follows:

storage_class struct tag variable={value 1, value 2, value 3......., value m};

e.g.
struct  date {
            int month;
            int day;
            int year;
};

struct account {
int acctno;
char acct_type;
char name[80];
float balance;
struct date lastpayment;
};

static struct account customer = {101,’S’, “Anup”, 10000.50, 5, 15, 04};

Array of structure
It can also be defined an array of structures upon which each element  of the array represents a structure.

e.g.
struct  date {
            int month;
            int day;
            int year;
};

struct account {
int acctno;
char acct_type;
char name[80];
float balance;
struct date lastpayment;
}customer[100];


In this declaration, each element of array represents  a structure of a customer. So, we have 100 structures for 100 customers. That means, we can store 100 records of customer in this data structure.

Processing a structure
The members of a structure are usually processed individually, as separate entities. So, each member of a structure can be accessed individually as follows:

variable.member
where variable refers to name of a structure type variable
and, member refers to name of a member of the structure.

e.g.
            customer.acctno
where, customer refers to name of structure
and accno refer to member of the structure
similarly,
            customer.name
            customer.balance
            etc.....

let’s see some expressions
            ++customer.balance
            customer.balance++
            &customer.balance

Similarly, it can also be accessed sub-member of a structure as follows:

variable.member.submember
where variable refers to name of a structure type variable
member refers to name of a member within outer structure
and, submember refers to name of the member within the embedded structure.
e.g.
            customer.lastpayment.month


/* to read input of a customer and write out it’s information again */

#include
struct  date {
            int month;
            int day;
            int year;
};

struct account {
int acctno;
char acct_type;
char name[80];
int balance;
struct date lastpayment;
}customer[100];

main()
{
            int i,n;
printf(“\n How many no. of cusstomer?”);
scanf(“%d”,&n);
for(i=0;i
                        readinput();

for(i=0;i
                        witeoutput();
}
void writeoutput(int i)
{
            printf(“\n Customer No.: %d”,i+1);
            printf(“Name : %s”,customer[i].name );
            printf(“Account Number : %d “,customer[i].acctno );
            printf(“Account Type :  %c “,customer[i].acct_type );
            printf(“Balance : %d “,customer[i].balance );
printf(“Payment Date : %d/%d/%d “,customer[i].lastpayment.month, customer[i].lastpayment.day, customer[i].lastpayment.year);
}

void readinput(int i)
{
            printf(“\n Customer No.: %d”,i+1);
            printf(“Name :  “);
            scanf(“%[^n] “,customer[i].name );
            printf(“Account Number : “);
            scanf(“%d “,&customer[i].acctno );
            printf(“Account Type :  “);
            scanf(“%c “,&customer[i].acct_type );

            printf(“Balance :  “);
            scanf(“%d “,&customer[i].balance );

            printf(“Payment Date :  “);
scanf(“%d/%d/%d“,&customer[i].lastpayment.month, &customer.lastpayment.day, &customer.lastpayment.year);
}
User Defined data types (typedef)
In c, the data type of any identity can be customized by the user. i.e. new data type can also be made so that such type can be used to define any identities. typedef is the keyword, which enables users to define new data type equivalent to existing data types. Such user defined data types can be used to define any other variables, arrays, structures. New data type can be defined as follows:

typedef  type  new_type;
 e.g.

typedef  int age;
age male female;

and, is equivalent to
int male, female;

Similarly,
typedef float cust[100];
cust newcust,oldcust;

or,
typedef float cust;
cust newcust[100],oldcust[100];

By the same way, it can also be used to define a structure too. It removes the repeatition of struct tag.
In general,
typdef struct{
            member 1;
            member 2;
            ...............
            member m;
}new_type;

e.g.
typedef struct{
            int acctno;
            char acct_type;
            name[80];
            float balance;
}record;
record oldcustomer,newcustomer;

Here, record is defined as new structure data type and newly define data type is used to define structure variables oldcustomer and newcustomer.

Different ways of declaration of structures
typedef struct {
            int month;
            int day;
            int year;
}date;

typedef struct {
            int acctno;
char acct_type;
char name[80];
            float balance;
            date lastpayment;
}record;
record  customer[100];

typedef struct {
            int month;
            int day;
            int year;
}date;
typedef struct {
            int acctno;
            char acct_type;
char name[80];
            float balance;
            date lastpayment;
}record[100];
record  customer;
typedef struct {
            int month;
            int day;
            int year;
}date;

struct {
            int acctno;
            char acct_type;
char name[80];
            float balance;
            date lastpayment;
}customer[100];


Structures and Pointers
The beginning address of a structure can also be accessed in the same manner as other address, using &(address) operator. So, a variable represents a structure, it can also be represented its address as &variable and pointer to the structure can be denoted as *variable.
such as
type *ptvar;

A pointer to a structure can be defined as follows:




e.g.

typedef struct {
            int acctno;
            char acct_type;
            char name[80];
            float balance;
            date lastpayment;
}account;
account customer, *pc=&customer;

typedef struct {
            int acctno;
            char acct_type;
            char name[80];
            float balance;
            date lastpayment;
} customer, *pc=&customer;



Here, customer is a structure variable of type account and pc is a pointer variable whose object is account type structure. The beginning address of the structure can be accessed as
pc=&customer;

Generally, each member of structure can be accessed by using selection operator as
            ptvar -> member
which is equivalent to
variable.member

The -> operator can be combined to period (.) operator and their associativity is left to right. Similarly, it can be used for array too.
ptvar ->member[expn]

typedef struct {
            int month;
            int day;
            int year;
}date;

struct {
            int acctno;
            char acct_type;
            char name[80];
            float balance;
            date lastpayment;
} customer, *pc=&customer;

So, if we want to access customer’s account number, then we can write any one of these
            customer.acctno                                  pc->acctno                  (*pc).acct_no

Similary, for month of last payment,

customer.lastpayment.month             
pc->lastpayment.month         
(*pc).lastpayment.month

If the structure is defined as:
struct {
            int *acctno;
            char *acct_type;
            char *name;
            float *balance;
            date lastpayment;
} customer, *pc=&customer;


So, if we want to access customer’s account number, then we can write any one of these

            *customer.acctno        *pc->acctno    *(*pc).acct_no
struct2.cpp
/* To access data items from members of structure */
#include
#include
void main()
{
int n=111;
char t='c';
float b=99.99;
char name[20]="srijan";
int d=25;

typedef struct {
            int *month;
            int *day;
            int *year;
}date;

struct {
            int *acctno;
            char *acct_type;
            char *name;
            float *balance;
            date lastpayment;
}customer,*pc=&customer;

pc->acctno=&n;
customer.acct_type=&t;
customer.name=name;
customer.balance=&b;
*customer.lastpayment.day=25;
clrscr();

printf("\n%d  %c  %s  %.2f  %d", *customer.acctno, *customer.acct_type, customer.name, *customer.balance, *customer.lastpayment.day);

printf("\n%d  %c  %s  %.2f %d",*pc->acctno,*pc->acct_type,
            pc->name,*pc->balance,*pc->lastpayment.day);

printf("\n%d  %c  %s  %.2f %d",*(*pc).acctno,*(*pc).acct_type,
            (*pc).name,*(*pc).balance,*(*pc).lastpayment.day);
            getch();
}
struct3.cpp
/* To determine the size of a structure and it's address */

#include
#include
void main()
{
clrscr();
typedef struct {
            int month;
            int day;
            int year;
}date;

struct {
            int acctno;
            char acct_type;
            char name[80];
            float balance;
            date lastpayment;
}customer, *pc=&customer;
printf("\nNumber of bytes  %d",sizeof *pc);
printf("\nstarting address : %d",pc);
printf("\nstarting address : %d",++pc);
getch();
}

Passing structure to a function
A structure can generally be passed to a function by two ways. Either, individual members can be passed to a function or entire structure can be passed to a function. By the same way a single member can be returned back to the function reference or entire structure.

In general,
void main()
{
typedef struct {
            int month;
            int day;
            int year;
}date;

struct {
            int acctno;
            char acct_type;
            char name[80];
            float balance;
            date lastpayment;
}customer;
float modify(char name[], int acctno, float balance);

....................
customer.balance = modify(name, acctno, balance);
....................
}

float modify(char name[], int acctno, float balance)
{
            float newbalance;
            ....................
            newbalance = .........;
            return(newbalance);
}

In this example, individual member is passed to a function and the new value is returned back to a member of a structure.

struct4.cpp

/* To pass an entire structure to a function*/

#include
#include

typedef struct {
            int acctno;
            char acct_type;
            char *name;
            float balance;
}record;

void main()
{
void modify(record *pc);
record customer={101,'c',"Anup",5000.00};

            printf("\n%d  %c  %s  %.2f",customer.acctno,customer.acct_type,customer.name,customer.balance);
                        modify(&customer);
                        printf("\n\n%d  %c  %s  %.2f", customer.acctno, customer.acct_type, customer.name, customer.balance);
            getch();
}
void modify(record *pc)
{
            pc->acctno=999;
            pc->acct_type='d';
            pc->name="Sabin";
            pc->balance=99999.99;
}
In this example, it passes entire structure to the function with it's address, then modifies values of member of the structure and finally returns back to the function reference with modified values of the structure.
struct5.cpp
/*to illustrate how an array of structure is passed to a function, and how a pointer to a particular structure is returned */
#include
#include
#define N 3
typedef struct {
            int acctno;
            char acct_type;
            char *name;
            float balance;
}record;
void main()
{
static record customer[N]={
                                                            {101,'c',"Anup",5000.00},
                                                            {102,'d',"Anil",9000.00},
                                                            {103,'o',"Sabina",7000.00}
};
            int ano;
            record *pc;
            record *search(record table[N], int ano);

            do{
                        printf("\n Enter the record no. to be searched, type 0 to end");
                        scanf("%d",&ano);
                        pc=search(customer,ano);

                        if(pc!=0)
                        {
                                    printf("\n Name : %s",pc->name);
                                    printf("\n Account No. : %d",pc->acctno);
                                    printf("\n Account type : %c",pc->acct_type);
                                    printf("\n Balance : %.2f",pc->balance);
                        }
                        else
                                    printf("\n Error - Record not found");
            } while(ano!=0)
}

record *search(record table[N], int ano)
{
            int i;
            for(i=0;i

                        if(table[i].acctno==ano)

                                    return(&table[i]);
            return(0);
}
Unions

It is similar to a structure which may contain individual data item may be different data types of same storage class. Each member of the structure is assigned its own unique storage area in memory whereas all members of a union share the same storage area in memory. It reserves the space equivalent to that of member which requires highest memory. So, it is used to conserve memory. It is useful to such applications, where all members need not to be assigned value at the same time. If assigned, it will produce meaningless result.

In general,
union tag {
                        member 1;
                        member 2;
                        ...............
                        member m;
                        };

storage-class union tag variable1, variable2, ..........variable n;

or, combined form,
storage-class union tag {
                        member 1;
                        member 2;
                        ...............
                        member m;
                        }variable1, variable2, ..........variable n;

e.g.
union id{
                        char color[12];
                        int size;
            }shirt, blouse;

            Here we've two union variables, shirt and blouse of type id and occupies 12 bytes in memory, however value is assigned to any union variable.

e.g.
union id{
                        char color[12];
                        int size;
            };

struct clothes{
            char manufacturer[20];
            float cost;
            union id description;
            }shirt, blouse;

            Here, shirt and blouse are structure clothes type variables. Each variable contains manufacturer, cost and either of color or size.
            Each individual member can be accessed in the same way as structure using . and -> operators.

struct6.cpp

/* a program using union */
# include
#include
void main()
{
clrscr();
union id{
                                    char color[12];
                                    int size;
            };

struct clothes{
            char manufacturer[20];
            float cost;
            union id description;
            }shirt, pant;

printf("%d",sizeof(union id));

scanf("%s",shirt.description.color);
printf("\n %s %d ", shirt.description.color, shirt.description.size);

shirt.description.size=12;
printf("\n %s %d ", shirt.description.color, shirt.description.size);
getch();
}





struct7.cpp
#include
#include
#include

typedef union {
            float fexp;       // floating point exponent
            int nexp;          // integer exponent
}nvals;

typedef struct{
            float x;
            char flag;
            nvals exp;
}values;

void main()
{
                  values a;
                  float power(values a);
                  int i;
                  float n,y;

                  printf("y=x^n\n enter value of x:");
                  scanf("%f",&a.x);
                  printf("enter value for n: ");
                  scanf("%f",&n);

                  i=(int) n;
                  a.flag=(i==n) ?'i' : 'f';
                  if(a.flag == 'i')
                              a.exp.nexp = i;
                  else
                              a.exp.fexp=n;

                  if(a.flag=='f' && a.x<=0.0)
                              printf("ERROR cannot raise negative no. to a floating point power ");
                  else
                  {
                              y=power(a);
                              printf("\n y=%.4f",y);
                  }         
                  getch();

}

float power(values a)
{
                  int i;
                  float y=a.x;
                  if(a.flag=='i')
                  {
                              if(a.exp.nexp==0)
                                    y=1.0;
                              else
                              {
                                    for(i=1;i
                                    {
                                                y*=a.x;
                                                if(a.exp.nexp<0 b="">
                                                            y=1.0/y;
                                    }
                              }
                  }
                  else
                              y=exp(a.exp.fexp*log(a.x));  //y=exp(n(log(x)))
                  return(y);
}

8. Self-Referential Structures
It is sometimes desirable to include within a structure one member that is a pointer to the parent structure type.
Generally,
struct tag {
            member 1;
            member 2;
            ...........
            struct tag *name;
            };

            where name refers to the name of a pointer variable. Thus the structure of type tag will have a member that points to another structure of type tag. Such structure is known as Self-referential structure.

eg.
struct list{
            char item[40];
            struct list *name;
            };

Introduction
Generally, some data manipulated during the programming, are to be stored in auxiliary storage devices such as hard disk, floppy disk so that such data can be retrieved, processed and saved into disk whenever it is required. So, such information are stored in disk as data file. There are two types of data files
  • Stream oriented

  • System oriented

Stream oriented data file can also divided into two types.
            One is comprising consecutive characters in which characters can be interpreted as individual data items or as component of strings or numbers. Such data are interpreted  using particular library functions such as fscanf and fprintf.
            Second is unformatted data files, organising data into blocks containing continuous bytes of information. These blocks represent data structure such as array and structure. Certain library functions are used to process such block of information to and fro from the data file.
           
Opening and Closing of data files
            While using a data file, it is necessary to establish buffer area to store information temporarily during transferring data to and fro between data file and computer's memory. Such buffer can be established by writing

FILE *ptvar;
            where, FILE is a file control structure to establish buffer area
            ptvar represents pointer to starting of buffer area

After establishing buffer, it is required to open the data file with its buffer area specifying whether the file is read only, write only or read/write. In general, it can be written as follow:

ptvar = fopen(filename, file_type);
            Here, fopen is a library function, file_type specifies the

File type must be one as listed below:
r           open an existing file for read only
w         open a new file for write only. If the specified file exists, then old one will be destroyed
a          open an existing file for appending. A new file'll be created if the file doesn't exist
r+         open an existing file for reading and writing
w+       open a new file for reading and writing, if the specified file exists, the old one will be destoryed.
a+        open an existing file for both reading and appending. A new file is created if doesn't exist

Note: fopen function returns a pointer to the beginning of the buffer associated with the file. If the file cannot be opened, it returns NULL (0).

            After completion of job, the file need to be closed using library function fclose however the C compiler automatically closes the file for safety. In general,
fclose(ptvar);

e.g.
#include
void main()
{
            FILE *fpt;

            fpt =  fopen("sample.dat", "w");
            …………..
            fclose(fpt);
}
Now, it creates a new file named sample.dat

Creating a data file
            Here is a program to create a data file, reads a line of lowercase text into computer's memory and write out upppercase text into the file.

//fio1.cpp

#include
void main()
{
FILE *fpt;
char c;

fpt =  fopen ("test.dat","w");

do{
            putc (toupper(c = getchar()),fpt);
}while(c!='\n');

fclose (fpt);
}

Reading a data file
/* a program to read a line of text from a data file character by character and displays the text on the screen */

//fio2.cpp

#include
#define NULL 0
main()
{
                        FILE *fpt;
                        char c;

                        fpt =  fopen ("test.dat","r");

                        if((fpt = fopen("test.dat","r"))==NULL)
                                    printf("\n ERROR file cannot open");
                        else
                                    do{
                                                putchar(c=getc(fpt));
                                    }while(c!='\n');

                        fclose (fpt);
}
Here is a program to create a data file containing customer records
FIO3.CPP

#include
#include
#include

#define TRUE 1

typedef struct{
            int month;
            int day;
            int year;
}date;

typedef struct{
            char name[80];
            char street[80];
            char city[80];
            int acctno;
            char acct_type;
            float balance;
            float newbal;
            float pay;
            date lastpay;
}record;

FILE *fpt;

void main()
{
            int flag =TRUE;
            record customer;
            record readscreen(record customer);
            void writefile(record customer);

            clrscr();
            fpt=fopen("records.txt","w");
            printf("\n CUSTOMER BILLING SYSTEM\n");
            printf("Enter today's date:");
            scanf("%d%d%d",      &customer.lastpay.month,
                                                &customer.lastpay.day,
                                                &customer.lastpay.year);

            flushall();
            customer.newbal=0;
            customer.pay=0;
            customer.acct_type='c';

            while(flag){
                        printf("\n Enter name of customer, type \'end\' when finished");
                        scanf("%[^\n]",customer.name);
                        flushall();

                        if(strcmpi(customer.name,"END")==0)
                                    break;
                        customer=readscreen(customer);
                        writefile(customer);
            }
            fclose(fpt);
}
record readscreen(record customer)
{
            printf("Street :");
            scanf("%[^\n]",customer.street);
            flushall();

            printf("City :");
            scanf("%[^\n]",customer.city);
            flushall();

            printf("Account Number : ");
            scanf("%d",&customer.acctno);
            flushall();
            printf("Current balance : ");
            scanf("%f",&customer.balance);
            flushall();
            return(customer);
}

void writefile(record customer)
{
            fprintf(fpt,"%s\n",customer.name);
fprintf(fpt,"%s\n",customer.street);
            fprintf(fpt,"%s\n",customer.city);
            fprintf(fpt,"%d\n",customer.acctno);
            fprintf(fpt,"%c\n",customer.acct_type);
            fprintf(fpt,"%.2f\n",customer.balance);
            fprintf(fpt,"%.2f\n",customer.newbal);
            fprintf(fpt,"%.2f\n",customer.pay);
            fprintf(fpt,"%d%d%d\n",customer.lastpay.month,customer.lastpay.day,
                        stomer.lastpay.year);
}

Here is a program to update a data file containing customer records

#include
#include
#include

#define TRUE 1
#define NULL 0

typedef struct{
            int month;
            int day;
            int year;
}date;

typedef struct{
            char name[80];
            char street[80];
            char city[80];
            int acctno;
            char acct_type;
            float balance;
            float newbal;
            float pay;
            date lastpay;
}record;

FILE *ptold,*ptnew;

void main()
{
            int flag =TRUE;
            record customer;
            record update(record customer);
            void writefile(record customer);

            clrscr();
            if((ptold=fopen("records.txt","r"))==NULL)
            {
                        printf("\n Error file cannnot be opened");
                        return;
            }
            ptnew=fopen("records.new","w");

            fscanf(ptold,"%s",customer.name);
            printf("\nName : %s",customer.name);
            flushall();
            fscanf(ptold,"%s",customer.street);
            printf("\nstreet : %s",customer.street);

            fscanf(ptold, "%s",customer.city);
            fscanf(ptold, "%d",&customer.acctno);

            fscanf(ptold, "%s",customer.acct_type);
            fscanf(ptold, "%f",&customer.balance);
            fscanf(ptold, "%f",&customer.newbal);
            fscanf(ptold, "%f",&customer.pay);
            fscanf(ptold, "%d%d%d",&customer.lastpay.month,
&customer.lastpay.day, &customer.lastpay.year);

            printf("\n city : %s",customer.city);
            printf("\n account no. : %d",customer.acctno);
            printf("\n old balance : %.2f",customer.balance);
            printf("\naccount type : %c",customer.acct_type);
            printf("\n new balance : %.2f",customer.newbal);
           
customer=update(customer);

            writefile(customer);
            fclose(ptold);
            fclose(ptnew);
            remove("records.txt");
            rename("records.new","records.txt");
}

record update(record customer)
{
            printf("\n updated Name : %s\n",customer.name);
            printf("\n Account Number : %d\n",customer.acctno);
            printf("\n Old balance : %.2f\n",customer.balance);
            printf("\n Current Payment : \n");
            scanf("%f",&customer.pay);

            customer.newbal=customer.balance-customer.pay;
            printf("\n New balance : %.2f",customer.newbal);
            return(customer);
}

void writefile(record customer)
{
            fprintf(ptnew,"%s\n",customer.street);
            fprintf(ptnew,"%s\n",customer.city);
            fprintf(ptnew,"%d\n",customer.acctno);
            fprintf(ptnew,"%c\n",customer.acct_type);
            fprintf(ptnew,"%.2f\n",customer.balance);
            fprintf(ptnew,"%.2f\n",customer.newbal);
            fprintf(ptnew,"%.2f\n",customer.pay);
            fprintf(ptnew,"%d%d%d\n",customer.lastpay.month,
                        customer.lastpay.day, customer.lastpay.year);
}

Unformatted data files

Some applications involve the use of data files to store blocks of data, where each block consists of a fixed number of contiguous bytes. Each block will generally represent a complex data structure, such as a structure or an array. If a data file contains a multiple structures having same members, in such case, it reads entire block of structure at a time from the data file. Such unformatted data file can be read and written by using fread and fwrite functions. Each of these functions require four arguments, such as:

fread(&customer,sizeof(record),1,fpt);
            where, &customer is pointer to data block
            sizeof(record) shows size of each block
            1 represents number of data blocks
            fpt shows  stream pointer of the data file

Here is an example to create an unformatted data file containing customer records
FIO5.CPP
#include
#include
#include

#define TRUE 1

typedef struct{
            int month;
            int day;
            int year;
}date;

typedef struct{
            char name[80];
            char street[80];
            char city[80];
            int acctno;
            char acct_type;
            float balance;
            float pay;
            date lastpay;
}record;

FILE *fpt;

void main()
{
            int flag =TRUE;
            record customer;
            record readscreen(record customer);

            clrscr();
            fpt=fopen("recun.txt","w");
            printf("\n CUSTOMER BILLING SYSTEM\n");
            printf("Enter today's date:");
            scanf("%d%d%d",      &customer.lastpay.month,
                        &customer.lastpay.day,&customer.lastpay.year);
            flushall();
            customer.balance=0;
            customer.pay=0;
            customer.acct_type='c';

            while(flag){
                        printf("\n Enter name of customer, type \'end\' when finished");
                        scanf("%[^\n]",customer.name);
                        flushall();

                        if(strcmpi(customer.name,"END")==0)
                                    break;
                        customer=readscreen(customer);
                        fwrite(&customer,sizeof(record),1,fpt);
            }
            fclose(fpt);
}


record readscreen(record customer)
{
            printf("Street :");
            scanf("%[^\n]",customer.street);
            flushall();

            printf("City :");
            scanf("%[^\n]",customer.city);
            flushall();

            printf("Account Number : ");
            scanf("%d",&customer.acctno);
            flushall();

            printf("Current balance : ");
            scanf("%f",&customer.balance);
            flushall();

            return(customer);
}

Here is an example to update an unformatted data file containing customer records
FIO6.CPP
#include
#include
#include

#define TRUE 1
#define NULL 0

typedef struct{
            int month;
            int day;
            int year;
}date;


typedef struct{
            char name[80];
            char street[80];
            char city[80];
            int acctno;
            char acct_type;
            float balance;
            float pay;
            date lastpay;
}record;

FILE *ptold,*ptnew;
int month, day, year;

void main()
{
            record customer;
            record update(record customer);

            clrscr();
            if((ptold=fopen("recun.txt","r"))==NULL)
            {
                        printf("\n Error file cannnot be opened");
                        return;
            }
            ptnew=fopen("reconew.txt","w");

            printf("\n CUSTOMER BILLING SYSTEM UPDATE \n");

                        fread(&customer,sizeof(record),1,ptold);
                        while(!feof(ptold))
                        {
                                    customer=update(customer);
                                    fwrite(&customer,sizeof(record),1,ptnew);
                                    fread(&customer,sizeof(record),1,ptold);
                        }
            fclose(ptold);
            fclose(ptnew);
            remove("recun.txt");
            rename("reconew.txt","recun.txt");
}

record update(record customer)
{
            printf("\n updated Name : %s\n",customer.name);
            printf("\n Account Number : %d\n",customer.acctno);
            printf("\n Old balance : %.2f\n",customer.balance);
            printf("\n Current Payment : \n");
            scanf("%f",&customer.pay);
            customer.balance=customer.balance-customer.pay;
            printf("\n New balance : %7.2f",customer.balance);
            return(customer);
}

9. Computer graphics

Computer graphics is one of the most powerful and interesting facet of computers. There is a lot that you can do in graphics apart from drawing figures of various shapes. All video games, animation, multimedia predominantly give you a feel of how some of these things are achieved in C. The aim of this chapter is to make you comfortable with basic concept of graphics functions.
Before carrying any graphic activity, first it needs to switch to graphics mode. But switching into graphics mode, depends upon the adapter and monitor that is installed in the computer. Depending upon the adapter and monitor, only some modes are available and offers the best resolution. The number of dots or picture elements available to us on the screen in the graphics mode is called resolution.

So to switch over to the graphics mode that offers the best resolution, we need to call the function initgraph()//initialize graphic mode. It figures out the best resolution and puts the number corresponding to that mode in the variable gm. 2 parameters:-gm and gd The gm number tells us which monitor we are using, and its resolution, the number of video pages it supports and the colors those are available.

To understand gd, it needs to understand device drivers. Device drivers are small programs which talk directly to the hardware. Graphic drivers are subset of device drivers which is to be initialized while changing into graphics mode. Thus, EGAVGA. BGI file is used as the graphics drivers for VGA adapter.

DETECT macro is assigned to gdriver then by asking  initgraph() to figure out which BGI file is needed.  This file is then loaded into memory. When it is changed into graphics mode, two things happens
  • Cursor disappears, since the conventional cursor is not supported in graphics mode.
  • Coordinate system is established according the resolution.
So, after changing into graphics mode, it can be used graphics functions to draw shapes in C.  Such as putpixel(), line(), circle(), ellipse(), arc() and drawpoly()

/* A program to draw a line */
#include
#include
#include
#include
int main(void)
{
   /* request auto detection */
   int gdriver = DETECT, gmode, errorcode;
   /* initialize graphics mode */
   initgraph(&gdriver, &gmode, "");
            /* read result of initialization */
            errorcode = graphresult();
            if (errorcode != grOk)  /* an error occurred */
            {
                        printf("Graphics error “);
                        printf("Press any key to halt:");
                        getch();
                        exit(1);             /* return with error code */
            }
            /* draw a line */
            line(0, 0, getmaxx(), getmaxy());
            /* clean up */
            getch();
            closegraph();
            return 0;
}
/* A program to draw a circle */
#include
#include
#include
#include

int main(void)
{
   /* request auto detection */
   int gdriver = DETECT, gmode, errorcode;
   int midx, midy;
   int radius = 100;

            /* initialize graphics and local variables */
   initgraph(&gdriver, &gmode, "");

   /* read result of initialization */
   errorcode = graphresult();
   if (errorcode != grOk)  /* an error occurred */
   {
      printf("Graphics error: %s\n", grapherrormsg(errorcode));
      printf("Press any key to halt:");
      getch();
      exit(1); /* terminate with an error code */
   }

   midx = getmaxx() / 2;
   midy = getmaxy() / 2;
   setcolor(RED)

   /* draw the circle */
   circle(midx, midy, radius);

   /* clean up */
   getch();
   closegraph();
   return 0;
}
/* A program using putpixel */
#include
#include
#include
#include
#include
#define PIXEL_COUNT 1000
#define DELAY_TIME  100  /* in milliseconds */

int main(void)
{
   /* request auto detection */
   int gdriver = DETECT, gmode, errorcode;
   int i, x, y, color, maxx, maxy,
       maxcolor, seed;

/* initialize graphics and local variables */
   initgraph(&gdriver, &gmode, "");

/* read result of initialization */
   errorcode = graphresult();
/* an error occurred */
   if (errorcode != grOk)
   {
      printf("Graphics error: %s\n", grapherrormsg(errorcode));
      printf("Press any key to halt:");
      getch();
/* terminate with an error code */
      exit(1);
   }

   maxx = getmaxx() + 1;
   maxy = getmaxy() + 1;
   maxcolor = getmaxcolor() + 1;

   while (!kbhit())
   {
/* seed the random number generator */
      seed = random(32767);
      srand(seed);
      for (i=0; i
      {
         x = random(maxx);
         y = random(maxy);
         color = random(maxcolor);
         putpixel(x, y, color);
      }

      delay(DELAY_TIME);
      srand(seed);
      for (i=0; i
      {
         x = random(maxx);
         y = random(maxy);
         color = random(maxcolor);
         if (color == getpixel(x, y))
            putpixel(x, y, 0);
      }
   }

/* clean up */
   getch();
   closegraph();
   return 0;
}



No comments:

Post a Comment