Google
 

C Programming

Tuesday, July 18, 2006

C Programming

CHAPTER 1
INTRODUCTION TO C PROGRAMMING


Why C Programming?

Computers can understand only machine language which is written in Binary Digits i.e. zero (0) & one (1). But instruding computers through machine language will be very diffault as we have to give instuction in machine language. However there is a easier way of instructing computers. This is done through High Level Languages High Level Languages use simple words in English to instruct computers. The following are High Level Langugages Basic, Cobol, Pascal, C, etc.

The C Language has been around for quite some time & has seen the introduction of newer programming languages like Java, C++ & C#. Many of these new languages are dribed, at least in part from C, but are much larger in size. The more compact C is better to start out in programming because it is simpler to learn.

It is easier to learn the newer languages one the principles of C Programming have been grapsed. For instance, C++ is an extension of C & can be difficult to learn unless you have learnt C programming first.


What is C Programming?
The steps taken to solve a particular problem is known as Program. The steps are written in a particular computer langugage.

Introduction to C Programming
When you know a language you can communicate with another person knowing the same language`. In the same language . In the same way, with a computer language we can communicate with the computer.

C is a compact general purpose programming language that was originally developed by Dennis Ritchie in 1972 at AT&T Bell Labs NewYork for the Unix Operating System. It was first implemented on the Digital Equipment Corporation PDP-11.

This new Programming Language was named 'C' as it succeded an earlier programming named 'B' that had been introduced around in 1970.

The Unix Operating System & virtually all Unix applications are written in the C languages. However, C is not limited to a particular platform & programs can be created on any machine that supports C, including those employing the Windows platform.

The flexibility & portability of C made it very popular & the language was formalized in 1988 by the American National Standards Institute (ANSI). The ANSI C standard unambiguously defined each aspect of C, thereby eliminating some uncertainity about the precise syntax of the language.

Advantages of C

Despite the extra features available in newer languages C remains popular because it is versatile & efficient. It is used today on a large number of platforms for everything on a large number of platforms for everything from microcontrollers to the most advanced scientific systems. Programmers around the world embrace C because it allows them maximum control & efficiency in their programs. It is easy to be read & maintained.

Compiler
A compiler is a program which translates a High Level Language into a machine language that a compiler can understand & execute. Every High Level Language will have a different compiler. The original program written in the High Level Language is called the source program & while the resulting compiled machine language program is called the object program.



CAPTER 2

STARTING C PROGRAMS
/* This program prints the line*/
#include <>
main()
{
printf("This is my first Program in C. This Program will print the new line\n");
return 0;
}

The first line is the remarks or comments line. This line is ignored by the compiler. The comments line helps us in understanding the program. You can put more than one line.

The second line is #include is called the preprocessor directive. It tells the C PreProcessor to look for a file & place the contents of that file in the location where #include appears.

Header Files
The files like stdio.h that are include in the #include directive are called header files because the #include directives are always placed at the beginning or head of C Programs. Besides stdio.h, there are many header files & their explanations are given below.


Library Description
stdio.h - Contains input and output functions type & macro definitions. This library is used by most C Programs and represents almost one third of the entire standard C library.
ctype.h - Contains function for testing characters
string.h-Contains function for manipulating strings.
math.h-Contains mathematical functions.
stdlib.h-Contains utility functions for number, conversion, storage, allocation etc.
assert.h - Contains a function that can be used to diagnostics to a program.
stdarg.h - Contains a function that can be used to step through a list of function arguments.
setjmp.h - Contains a function that can be used to avoid the normal call & return sequence.
signal.h - Contains functions for handling exceptional conditions that may arise in a program
time.h - Contains functions for manipulating date & time.
limits.h - Contains constantdefinitions for the size of C data types.
float.h - Contains constant definitions relating to floating point arithmetic.


The main() function
Every C Program must have a main() function and can have only one main() function. It indicates the start of a program. You can place the main() function anywhere in the C Program, but the execution of the program always starts with C - Program can have many other functions other than main() function.

Another important thing about main() is that every C Program ends with main i.e.the C Program ends when all the statements within the main function have been executed.

The { and } enclose the statements carried out by main(). Each line within the { } is known as a statement. Every statement must end by a; semicolon.

printf
The printf function is used to print the output.

The newcharacter \n
The \n in the printf function tells the computer to move the cursor to the beginning of the next line so that anything printed after the message will start on the next line.


The return statement
All functions in C can return values E.g. when you create such a function that returns the value of the addition. The return 0; means that 0 is returned from the main function and the program is terminated normally.

Excersises
Write a program to print your name and your college or school name on different lines.

Write a program to print the word "Hello World"

Write a program to print the name on first line, your standard and division on the second line and your Roll Number on the third line.


CHAPTER 3

CONSTANTS & VARIABLES

Constant means the value does not change during execution of the program. Constants are of two types 1) Integer Constants 2) Floating point Constants

Integer Constants
Integer Constants are numbers without any fractional part or decimal point. Integer numbers are also called whole number.

Rules: An integer constant must have at least one digit & must be written without a decimal point. It can have a + or - sign.
The following are valid integer constants 456 and -6792.
The following are invalid integer constants 5.75(decimal point not allowed)
Rs 1,000 (first character not a digit & comma not allowed)

Integer Format Specifier
%d is used to format an integer & is known as integer format specifier.

Floating Point Constants
Floating Point Constants have fractional part or decimal point. A floating point number is also called a real number.

Rules: A floating point contant must have at least one digit to the right of the decimal point. It can have a + or - sign.
The following are valid floating point constants 5.0 , -0.456 and 5000.0
The following are invalid floating point constants Rs 5.0 (chatacter not allowed)
1,000.00 (comma not allowed)

Using Scientific Notifications
C Language uses scientific notations to write lengthy floating point numbers. In scientific a number is shown by the combination. For example 5000 can be written as 5e3 or 5E3 in scientific notation. Corresponding, %e or %E is the format specifier to format a floating point number in scietific notation.

Character Constants
A character enclosed in signle Quotes (' ') is called a character constant. For example, 'a', 'b', 'A' are all character constants that have uniqe numeric values in ASCII character set.

Character Format Specifier
The format specifier %c is used to format the output.

Format Specifier
%d an integer whole number 100
%f a floating point number 0.123456
%c a single characters 'A'
%s a string characters "Hello world"
%p a machine memory address 0x0022FF5c
%e scientific calculation 5e3

Variables:
The value which changes during the execution of a program is called a variable. Each variable has a storage location in memory where its value is strored. The variable is given a name and the variable name is given a a name for the storage location.
e.g. area = 20, height =4

In C the word identifier is used for names given to variables, functions etc.


Rules for naming Variables
The First character in the identifier must be an alphabet. An identifier can contain alphabets & underscore. An identifier can contain both upper case and lower case alphabets (i.e. capital and small alphabets). An identifier Age and age are two different identifiers.
The Following are valid identifiers to name variables.
age, C5, height_a
The following are invalid identiers to name variables.
height * Characters other than alphabets
numbers, _ not allowed
float reserved word
4x first character is not an alaphabet


There are four basic data types in the C Language. These are defined using the C keywords which are listed in the following table, together with a description of each data type:

Data Types:

char a single byte, capable of holding one character example A
int an integer whole number example 100
float a floating point number correct up to six decimal places example 0.123456
double a floating point number, correct upto ten decimal places example 0.0123456789

The four data types allocate different amounts of machine memory for storing data. The smallest is char data type which allocates just a single byte of memory that the float data type does, so it should only be used when a precise lengthy floating point number is absoultely required.

Declaring variables
The following shows the basic declaration format
type variablename;

If you have more than one variable to declare, you can use
type variablename1;
type variablename2;
type variablename3;
or

type variablename1, variablename2, variablename3;

e.g.
int a,b,c;
float x,y;
char x,y;

Assigning values to a variable
The following statement declares age as an integer variable and assigns it a value.
int age=20;
or
int age;
age = 20;

What will be the output of the following?
#include
main()
{
int n1;
n1=52/10;
printf("The division of 52/10 is : %d\n",n1);
return 0;
}

#include
main()
{
float n1;
n1=52/10;
printf("The division of 52/10 is: %f\n", n1);
return 0;
}

#include
main()
{
int n1;
n1=52.0/10;
printf("The division of 52.0/10 is: %d\n", n1);
return 0;
}

#include
main()
{
int n1;
n1=52/10.0;
printf("The division of 52/10.0 is: %d\n", n1);
return 0;
}

#include
main()
{
float n1;
n1=52.0/10;
printf("The division of 52.0/10 is: %f\n", n1);
return 0;
}

#include
main()
{
float n1;
n1=52/10.0;
printf("The division of 52/10.0 is: %f\n", n1);
return 0;
}

#include
main()
{
double pi=3.1415926536;
printf("The value of pi is approximately %f", pi);
return 0;
}

#include
main()
{
int l,b,area;
l=2;
b=4;
area = l*b;
printf("area=%d\n", area);
return 0;
}

Arithmetical Operators
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus

Exercises
1. Write a program to print area of a circle (r=5, pi=3.14)
2. Write a program to print area of a triangle
3. Write program to print average of 3 numbers 5,10,15
4. Write a program to add two number 6 and 7(a=6 and b =7)



CHAPTER 4
HANDLING INPUT AND OUTPUT

The general form of an output function is printf(format - string, var1, var2.....) where format - string gives information on how many variables are to be printed & the types. The printf() function is sometimes used only to display the message.

e.g. printf("This is my first program");
the format string is This is my first program and there are no variables. After displaying the message, the cursor will remain at the end of the string. If we want to move the cursor to the next line, we should write
printf("This my first program\n");

Other examples of printf function
printf("The value of a is %d",a);
print the value of a has to be displayed as an integer.

printf("The value of a is %d, b is %f", a,b);

prints the value of a as integer & b as a decimal fraction.

Solved Example
/* to print characters*/
#include
main()
{
char a1, b1;
a1 ='x';
b1='y';
printf("The first character is %c\n", a1);
printf("The second character is %c\n",b1);
return 0;
}

/*to print numeric values of characters*/
#include
main()
{
char a1,b1;
a1='a';
b1='A';
printf("The value of first character is %d\n",a1);
printf("The value of sencond character is %d\n",b1);
return 0;
}
Note:- All the characters are stored in the form of bits(binary digits i.e. a combination of 0's and 1's.) Therefore each character has a unique numeric value to identify. Theref0re a and A are not equal and have a different numeric value. In the ASCII set there are unique numberic values for 255 characters.

/* to print the sum of two numbers*/
#include
main()
{
int a1, b1;
a1=10;
b1=20;
printf("The Sum of %d & %d is %d\n", a1, b1, a1+b1);
return 0;
}

Specifying the Minimum Field Width
You can add an integer between the % sign and the letter to specify the minimum field width. The integer is called the minimum field width specifier. For e.g. %5f makes sure that the output is 5 character spaces wide.

#include
main()
{
int a,b;
a=25;
b=1000;
printf("%d\n",a);
printf("%d\n",b);
printf("%5d\n",a);
printf("%05d\n",a);
return 0;
}

The first lines print normally. The third line %5d specifies 5 character spaces therefore three blank spaces are printed before 25.

You can also put a dot and an integer after the minimum width specifier to specify the number of decimal places for floating point numbers or to specify the maximum field width for integers.

#include
main()
{
int num=1;
printf("Using %%0d displays %0d\n",num);
printf("Using %%1d displays %1d\n",num);
printf("Using %%2d displays %2d\n",num);
printf("Using %%3d displays %3d\n",num);
printf("Using %%4d displays %4d\n",num);
printf("Using %%05d displays %05d\n",num);
printf("Using %%06d displays %06d\n",num);
printf("Using %%07d displays %07d\n",num);
return 0;
}

A program can ensure that output occupies a specific minimum number of spaces by specifying the required number in the format specifier. The number must be placed immediately after the % character in the format specifier. For instance, to ensure that an integer always fills at least 7 spaces the format specifier is %7d.

If it is preferable for the blank spaces to be filled with zeros just add a zero between the % character and the specified number. To ensure that an integer always fills at least 7 spaces and that any blank spaces are filled with zeros the format specifier is %07d.

#include
main()
{
float number = 7.123456;
printf("%-8.0f end\n",num);
printf("%-8.2f end\n",num);
printf("%-8.4f end\n",num);
printf("%-8.6f end\n",num);
return 0;
}

Greater control over the output appearance of floating point numbers can be gained by adding a precision specifier to the %f format specifier. This is simply a full stop followed by a number representing the desired number of decimal places to be displayed. For instance, a format specifier, of %2f will display a floating point number showing just 2 decimal places.

The minimum space specifier, described on the opposite page, can be combined with the precision specifier so that both number of minimum spaces and number of decimal places can be controlled. For instance, a format specifier of %07.2f decimal places, and any empty spaces would be filled with zeros.

By default, any empty spaces precede the number so it is right aligned. To have the number displayed left aligned, with any empty spaces added after the number, prefix the minimum space specifier with a minus sign as in the example above. The 'end' strings are just there to show that empty spaces have been added.

%8.3f means the minimum field width for floating point is 8 characters with 3 decimal places.

%2.7d means the minimum field width for integers is 2 and maximum field width is 7.


#include
main()
{
int a;
float b;
a=55;
b=22.222;
printf("%d\n",a);
printf("%2.7d\n",a);
printf("%f\n",b);
printf("%8.3f\n",b);
return 0;
}

Scanf Function

Till now, we have assigned values to variables within the program. Suppose we want to input the values during program execution, we can use the scanf() function. The general format of the input statement.
scanf(format-string, var1, var2....);
where format-string gives the information about the type of data and var1, var2.......gives the information about the number of variables.

For example, if you want to add any two numbers entered by the user, you would accept the two values by the statement.

scan("%d%d", &a,&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;b);
The two values will be stoered in the variables a and b. When you enter the two values they are to be seperated by a blank.

e.g. if you want to enter the two values 5 and 7, you will type it as 5 7. Similarly if you want to enter floating point numbers you type
scanf("%f %f",&a,&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;b);

The 'scanf()' function can be used to get in put into a program and it requires two arguments. First a formal specifier defines the type of data to be entered, then the name of the a variable in which the input will be stored. The variable name must be preceded by a '&' character, except when the data being entered is a string of text. The & character in this case, is the address of' operator that directs the input to be stored in the variable name that it precedes.

The scanf() function can set the value of multiple variables simultaneously too. The first argument must then contain a list of required format specifiers, each seperated by a space, and the entire list should be exclosed by double quotes. The second argument must contain a comma-seperated list of variable names to which each specified format applies.


#include
main()
{
char character;
int a,b;
printf("Enter anyone keyboard character\n");
scanf("%c",&character);
printf("Enter 2 integers seperated by a space\n");
scanf("The letter entered was %c\n",character);
printf("The letter enetered were %d and %d\n", a,b);
return 0;
}

#include
main()
{
int eng, hin, mar, maths, sc, ss;
printf("Enter the marks\n");
scanf("%d %d %d %d %d %d", &eng, &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;hin, &mar, &maths, &sc, &ss);
printf("\n Subjects English Hindi Marathi Maths Science Soc. Studies\n");
printf("Marks %d %d %d %d%d %d\n", eng, hin, mar, maths, sc, ss);
return 0;
}

Exercise
1. Write a program to input three number and print them on different lines

2. Write a program to input the marks of 6 subjects and print the total

3. Write a program to input the marks of 6 subjects and print the average

4. Write a program to input two alphabets and print it.


CHAPTER 5
DATA TYPE QUALIFIERS

When an int variable is declared it can by default contain either positive of negative integer values. The range of possible values is determined by your system.

If the int variable is created by default as a 'long' type it typically will have a possible range of values from a maximum of +2147483647 down to a minimum of -2147483648.

On the other hand, if the int variable is created by default as a 'short' type then typically the maximum possible will be +32767 and its minimum will be -32768.

The size can be specified when declaring the variable using the short and long keywords, as demonstrated in the code fragement:
short int num1; /* saves memory space*/

long int num2; /* allows bigger range*/

The limits.h header file contains implementation defined limits for the size of each data type. These are accessed via 'constant' values called INT_MAX and INT_MIN, for int variable declarations that do not specify a size. Similarly, SHRT_MAX and SHRT_MIN for short in variable declarations and LONG_MAX and LONG_MIN for long int variable declarations.

#include
#include
main()
{
printf("Max int: %d\t", INT_MAX);
printf("Min int: %d\n", INT_MIN);
printf("Max short:%d\t", SHRT_MAX);
printf("Min short:%d\n", SHRT_MIN);
printf("Max long:%d\t", SHRT_MAX);
printf("Min long:%d\n", SHRT_MIN);
return 0;
}

A non-negative 'unsigned' int can be declared with the unsigned keyword. An unsigned short int variable will typically have a possible range from 0 to 65535. An unsigned long int variable will typically have a possible range from 0 to 4,294,967,295.

The sizeof operator is used in this example to examine the amount of memory space allocated to various data types:

#include
main()
{
printf("Short int: %d bytes\t", sizeof(short int));
printf("Long int: %d bytes\n", sizeof(long int));
printf("unsigned long int:%d bytes\n", sizeof(unsigned long int));
printf("char: %d bytes \t", sizeof(char));
printf("float: %d bytes\t", sizeof(float));
printf("double: %d bytes\t\n", sizeof(double));
return 0;
}


CHAPTER 6
EXTERNAL VARIABLES

The extent to which a variable is accessible in a program is called the ‘variable scope. Variables declared internally inside a function are known as ‘local’ variables, whereas variables that are declared externally outside a function are known as ‘global’ variable.

Local variables can only be accessed by the function in which they are declared. They come into existence when the function is called and normally disappear when the function is exited.

Global variables on the other hand can be accessed by all functions in a program. They remain in existence permanently so are useful to communicate data between functions.

An external global variable must be defined exactly once at the start of the program. It must also be declared at the start of each function that wants to use it. Each declaration should begin with the extern keyword which denotes that it is for a global variable, rather than for a regular local variable. These declarations should not be used to initialize the global variable.

The example below demonstrates has to define declare and initialize an external global variable called ‘num’.

#include
int num; /*define an external variable*/
main()
{
extern int num; /*declare the external variable*/
num =5;
printf(“Global variable value is %d”, num);
return 0;
}


CHAPTER 7
STATIC VARIABLES

Larger C Programs consist of multiple source code files that are compiled together to create a final executable file. This is a very useful aspect of C Programming that allows source code to be modular so that it can be reused in different programs.

Global external variables, as described on the opposite page, would normally be accessible to any function in any of the files being compiled together. All functions are normally accessible globally too. Functions and, more usually external variables can have their accessibility limited to just the file in which they are created by the use of the static keyword.

Normally a program cannot employ more than one variable of any given name. Using static external variables, however, usefully allows external variables of the same name to coexist happily providing they are declared as static and are not in the same file. Programming with multiple source code file. Programming with multiple source code file can find a common external variable name duplicated in two files. Declaring these as static avoids the need to rename one of these variables in each occurence within the source code.

The example below creates a static global external variable that cannot be used by other source code files. Attempting to do so causes an error at compile time and the compilation will halt.

#include
static int num=100; /*define static external variable*/
main()
{
extern int num; /* declare the external variable*/
printf("Global variable: %d", num);
}



CHAPTER 8
MANIPULATING DATA

Arithmetic Assignment Operators:-
We have already worked with the assignment operator =. The value on the right hand side of the = operator is assigned to the variable on the left of the = operator.

e.g. x=a+b

or y=50+10

or z=20

In the above case, the value of a+b is assigned to the memory location x


or y is assigned the value 60



or 20 is stored in the memory location z.



Similarly, the statement x=y=10 assigns 10 to the integer variable y and then to integer variable x. After the execution of the statement

The expression works from right tor left therefore the expression 10=x will not work.

Now consider the expression x=x+y. The operator always works from right to left, so on the side the addition of x+y is executed and on the left side of =, the previous value of x is replaced by addition of x and y on the right side.

2 Comments:

Anonymous Anonymous said...

ce work.......May be many can take advantage of this

10:30 PM

 
Blogger Unknown said...

hii....gud job daa!!!!

1:19 AM

 

Post a Comment

<< Home