Search This Blog

Monday, June 11, 2012

Parts of a function


Parts of a function

A function basically consists of two parts: Function header and Body.

Header


The header consists of three parts: Function return type, Function name and Parameter list.

E.g. Return Type Function Name (Parameter List)

The function return type can be any of C’s data types: int, float, char, long etc. You can also define
a function that does not return a value by using ‘void’.

E.g. void function(…)                Returns nothing

Note: function(void)                   Returns no argument

Arguments and Parameters

An argument is an actual value passed to the function by calling program. Parameter is an entry in a function header. It acts as the placeholder for an argument. Parameters of a function are fixed and do not change during program execution.

Body


Function body is the part that is enclosed in braces {…}. The body contains the statements that perform the actual work. When a function is called, execution begins at the start of the body and continues until a return statement or a closing brace is reached. The return statement not only terminates a function but also returns the value to the calling program if any. A function can contain multiple return statements. The first return is the only one that has any effect.

Friday, June 8, 2012

Functions


Functions


A function is a self-contained block of program that performs a coherent task of some kind. A function provides a convenient way to encapsulate some computation in a black box which can then be used without worrying about its innards.

  •  Every C program can be thought as a collection of functions.
  •  Any C program would contain at least one function
  •  If a C program contains only one function it must be main()
  •  Program execution always begins with main()
  • There is no limit on the numbers of functions that might be present in a C program.
  • main() will usually invoke other functions to perform its job, some coming from the same program and other from libraries of pre-written functions.
  •  Functions can appear in either order and in one source file or two
  •  Not all functions produce an integer value.

Structured Programming


Functions can be used in structured programming: a program discipline in which individual tasks are
performed by independent modules of program code. A specific program module can be a function
definition.


Top Down Design
Functions are really the only way to cope with the potential complexity of large programs. Structured
programming enables programmers to take the advantage of top down design methodology. In this case a
complex programming problem is broken up into a number of much simpler and manageable tasks in a
hierarchical way. Each task can be assigned a function in which program code and variables used are
isolated from the rest of the program.

Tuesday, June 5, 2012

File Inclusions , Conditional Compilation


File Inclusions 


This directive Causes one file to be included in another.

Eg. #Include “file name”
This causes the whole content of the above file to be inserted into the source code at that point in a program. It is used in two occasions.

a) When there is a very large program, the code in divided into several files. This feature also
enables the modularity in a program.
b) In a situation where some functions or some macros are needed in our programs. In this case
those files can simply be included.

#include <filename.c> in a specified directory
#include ”filename.c”
#include <filename.h> .h says it is a header file and go to head of a c program.


Conditional Compilation


By inserting some preprocessor directives we can skip over part of a source code.
e.g. #ifdef macro name
Statement 1;
Statement 2;

#endif

The block code will be processed as usual if the macro name has been defined. but not otherwise. #ifdef
is used when you want to compile only a part of your program.

It is also used to improve the portability of a program. Suppose you want to install a program in two
different types of computers without modifying the source code, you can isolate the lines of codes that
should be different for each machine using #ifdef and #endif

e.g. #ifdef PENTIUM
code suitable for Pentium
#else
code suitable for MAC
#endif
code suitable for both
e.g # if linux
# include <getopt.h>
#endif
#ifndef can also be used in the same way but behaves opposite to #ifdef

Sunday, June 3, 2012

Macro Expansions


Macro Expansions


A macro consist of a define directive, a template and a macro expansion.

Eg: #define TOWN “Borella”
#define MAX 212
#define AND &&

During preprocessing the C preprocessor replaces the every occurrence of TOWN in the program
with “Borella”

e.g.
 // Alphabetic character count
#include<stdio.h>
#include<conio.h>
#define isalpha(c) ((c>=’a’ && c<=’z’ ) || (c >=’A’ && c <= ‘Z’))
void main()
{
int ch, nc=0;
puts(“Enter a word or a sentence:”)
while (ch = getchar() != ‘\n’)
if (isalpha(ch)) nc++;
printf(“Your word or sentence contains %d alphabetic characters \n”, nc);
}

Friday, June 1, 2012

The ‘C’ Preprocessor


The ‘C’ Preprocessor


Before a C program is being executed, there are several prior steps involved. One of them is Preprocessing. The Preprocessor is the program that processes our source program before it is available to the compiler. The preprocessor offers several features known as preprocessor directives. They direct the compiler in various ways.

A directive starts with a # symbol and guides the compiler to behave in a special way. The directives are usually placed at the beginning of a program before the main() function, though it can be placed anywhere before a beginning of a function.

Preprocessing involves the directives

a) Macro expansion
b) File inclusions
c) Conditional compilation

Friday, May 25, 2012

Program Library


Program Library


In programming a collection of pre-compiled routines that a program can use is known as a Program Library.
These routines are stored in object format. They are known as library functions or routines. Libraries are especially useful for storing frequently used routines because you do not have to explicitly link them to every program that uses them. The linker automatically looks in libraries for routines that it does not find elsewhere.


Runtime Library


Runtime refers to the event that a program is being executed. The library routines (functions) that are bound to the program during execution are known as runtime library. A linker links the object code of a program to the runtime library in order to produce an executable code of a program.


Linker


Many programming languages allow you to write different pieces of code called modules separately. This
technique simplifies the programming task because you can break a large program into small more manageable tasks; also called divide and conquer. However, finally you need to put all these modules together. This is done by a program known as a linker.

A linker is also called a link editor (binder). So a linker combines all object modules into one executable
program.

A linker also does another job. It replaces the symbolic addresses you use with real addresses. Therefore
even if your program contains one module it has to be linked.

Saturday, May 12, 2012

Reading a character


Reading a character


getc()

getc() is a macro that reads one character from a stream.

getchar()
getchar() is a macro that gets a character from stdin. It returns the next character on the input stream stdin.

Eg:-1
/* Reading a character from the keyboard */
#include <stdio.h>
void main()
{
char ch;
printf("Enter a character:");
ch = getc(stdin);
printf("You have entered the character %c\n",ch);
}

Friday, May 11, 2012

Header files



Header files



C/C++ has a number of header files that hold the information it needs to know about the library functions. They provide function prototype declarations for library functions. Data types and symbolic constants used with the library functions are also defined in them; along with global variables defined by the library functions. Header files are required by the include directives because include directives are always placed at the head of a C program. The < > (angle bracket) around a header file tells the C preprocessor to look for the header file in a directory other than the “code”.



Frequently used Header Files


Some of the frequently used header files, and library functions they contain are listed below.
<stdio.h>        Defines the standard I/O predefined streams, stdin, stdout, stdprn and stderr and declares
                      stream-level I/O routines.
<stdlib.h>       Declares several commonly used routines: conversion routines, search/sort routines and other
                       miscellany.
<string.h>       Declares several string and memory manipulation routines.
<search.h>     Declares functions for searching and sorting.
<memory.h>   Declares memory manipulation functions
<mem.h>        Declares memory manipulation functions
<math.h>        Declares prototypes for the math functions
<malloc.h>     Declares memory management functions and variables.
<io.h>            Contains structures and declarations for low level input/output routines.
<graphics.h>   Declares prototypes for graphics functions
<float.h>          Contains parameters for floating point routines.
<errno.h>         Defines constant mnemonics for the error codes.
<dos.h>           Defines various constants and gives declarations needed for DOS and 8086 specific calls.
<dir.h>             Contains structures, macros and functions for working with directories and path names.
<ctype.h>         Contains information used by the character classification and character conversion macros.
<conio.h>         Declares various functions used in calling the DOS console I/O routines.
<complex.h>    Declares the C++ complex math functions.
<bios.h>           Declares various functions used in calling IBM-PC ROM BIOS routines.
<alloc.h>         Declares memory management functions. (allocation, deallocation etc.)
<time.h>          Defines a structure filled in by the time conversion routines and a type used by other time
                      routines also provides prototypes for these routines.

Friday, May 4, 2012

Standard Input


3.

/* Employee Data */
#include <stdio.h>
#include <conio.h>
void main()
{ int empnum;
char name[10];
int dd, mm , yyyy;
float salary;
clrscr();
printf("Enter employee number:");
scanf("%d",&empnum);
printf("Enter name :");
scanf("%10s", &name);
printf("Enter date dd/mm/yyyy :");
scanf("%2d %2d %4d", &dd, &mm, &yyyy);
printf("Enter salary :");
scanf("%f",&salary);
printf("\n");`
printf("Emp Num :%d \n", empnum);
printf("Name :%s\n", name);
printf("Date of employment :%d%c%d%c%d\n", dd,'/',mm,'/', yyyy);
printf("Salary :%7.2f\n",salary);
}

Monday, April 30, 2012

Standard Input


Standard Input

scanf() Function

scanf() function reads data from a standard input device into arguments specified by the format string.


scanf(format string, arguments)

1.


/* Input through the keyboard */
#include <stdio.h>
#include <conio.h>
void main()
{
int x,y,sum;
clrscr();
printf("Enter an Integer:");
scanf("%d",&x);
printf("Enter another:");
scanf("%d",&y);
sum = x + y ;
printf("sum =%d \n",sum);
}

2.



/* Floating point Numbers */
#include <stdio.h>
#include <conio.h>
main()
{
float x,y,sum;
clrscr();
printf("Enter a number:");
scanf("%f",&x);
printf("Enter another:");
scanf("%f",&y);
sum = x + y ;
printf("sum =%.2f \n",sum);
}

Friday, April 27, 2012

putchar()


putchar()

Try these codes........

putchar() - putchar() is a macro that outputs a character on stdout.

Eg:-1
/* Output a Character */
#include <stdio.h>
#include <conio.h>
#define msg "End of Program"
void main()
{
char a ;
clrscr();
a =100;
printf("%d\n",a);
putchar(a);
putchar(10);
putchar(13);
putchar(a+1);
puts(msg);
}


Eg :-2

/* Area of a circle */
#include <stdio.h>
#include <conio.h>
void main()
{
int r ;
float pi;
clrscr();
pi = 22/7.;
r = 7;
printf("%s%5.2f \n","The area of the circle =" ,pi*r*r);
}


Friday, April 13, 2012

Variable Declaration


Variable Declaration


some examples for you to try..........

Eg.1

 /* Adding two integers */
#include <stdio.h>
#define msg “End of Program”
void main()
{
int a,b,c;
clrscr();
a=2;
b=3;
c=a+b;
printf(“%d%s%d%s%d\n”,a,”+”,b,”=”,c);
puts(msg);
}



Eg:2

/* Adding Two Floating Point Numbers */
#include <stdio.h>
#define msg "End of Program"
#include <conio.h>
void main()
{ int a ;
float b;
clrscr();
a=123;
b=123;
printf("%5d\n",a);
printf("%+05d\n",a);
printf("%.5f\n",b);
puts(msg);
}

Saturday, April 7, 2012

Variable


Variable


 A variable is a named memory location in the computer’s memory where different values of a certain type of data can be stored.

Variable Names

In C, a name given to a variable must satisfy the following rules.

 The name can contain letters, digits and the underscore character.

The first character of the name must be an alphabet or an underscore. However the use of
an underscore is not recommended.

 C is case sensitive. So C treats X and x as two different variables.

Keywords cannot be used as variable names

C compilers allow long variable names. However most of the C compilers recognize the first 32 characters.
In C / C++ it is necessary to declare variables before they are used in a program. When a variable is
declared it is designated as belonging to one of the data types used in C. The compiler allocates memory
for the variable according to its data type.

                     Declaration                              Memory Allocation in Bytes
Eg:                     int a;                                                            2
                          char ch;                                                       1
                         float salary;                                                   4

Sunday, April 1, 2012

Symbolic Constants


Symbolic Constants


A symbolic constant is a constant that is represented by a symbol (name) in a program. A non numeric constant may consist of letters, digits, and other characters.

The literals enclosed in single quotes are referred to as character values. Others those enclosed in double quotes are called character strings. In C you can use a name to represent a constant. The value associated with a constant cannot be changed or reassigned.


‘a’, ‘b’, ‘,’, ‘;’ - character constants.
“Hello”, “Information”, “31/12/1999” - string constants.

Numeric constants in C are made up of digits and can include decimal points and contain letters and do not
have single or double quotes.

Constants can be defined by using by using the # define construct.


 # define a 10
# define ch ‘a’
# define msg “End of Program”

Friday, March 30, 2012

Constants and Variables-Constants


Constants

The C language is composed of seven basic types of code: Constants, Variables, Operators, Punctuations,
Keywords, Functions and Labels – collectively known as Tokens.

A constant is a named storage location in the memory where the compiler keeps unchanged data during program execution. Constants are of two types: Literal Constants and Symbolic Constants. A literal constant is a value that is directly used in the source code wherever it is needed.

E.g. int max = 100; integer constant
float tax = 0.05; floating point constant.
float multiplier = 2.03E-2 floating point constant (in scientific notation)

Integer constants can be written in three different notations.

  1. An integer constant starting with any digit other than 0 is treated as a decimal integer. It can contain a leading + 
  2. A constant starting with a 0 is treated as an octal integer. It can contain a leading + 
  3. A constant starting with a 0x or 0X is treated as a Hexadecimal integer. It can contain digits from 0 to 9 the letters A to F and a leading + or -.

Comments in a Program


Comments in a Program

Any text that you enter between /* and */ is considered to be a comment and is ignored by the compiler.

White Space Characters

The characters - space, Tab, Carriage Return (CR), Line Feed (LF) and Back Space are considered to be white space characters and they will be ignored by the compiler.



printf() Function

The printf() function is one of the most widely used functions in C. The purpose is to output its argument list to the standard output device. All the characters within a pair of double quotes will be treated as a string constant
except for escape sequences and conversion specifications.

Saturday, March 24, 2012

Directives in a Program


Directives in a Program

A directive is a special statement that can control the features of a compiler.
E.g.

a) #include <stdio.h>

provides a convenient way of telling the compiler that all the I/O functions have been included.

b) #include <math.h>

provides the standard math library.

c) #define

defines a symbolic name or a constant.

Thursday, March 8, 2012

Stages in Creating a C program


Stages in Creating a C program


1. Designing

2.Coding

You must first create a file which contain the C source code. For this you may use any text editor. The file name could be any legal name accepted by the DOS / UNIX and must have an extension of C.
E.g. pro1.c


The source code that you enter must obey the structures, the syntax and semantics of the C language.

3.Compiling

The C compiler receives the source code from the pre-processor and translates it in to assembly code.

 4.Assembling

The assembler creates object code. In MS-DOS the object files are seen with .obj extension


5.Linking

If a source file references library functions defined in other source files, the link editor combines these functions with main() to create an executable file (.EXE)


Saturday, March 3, 2012

Structure of a Function


Structure of a Function


Function name (parameters)
{
local variables ;
statements ;
}

The Minimum C Program

main()
{
}

Saturday, February 25, 2012

Introduction to C


Introduction to C


C is a general purpose high-level language developed by Dennis Ritchie and Brain Kernighan at AT&T Bell Laboratories of USA in 1972. Originally it was designed to run on a PDP-11 under UNIX operating system. C was influenced by two related languages BCPL and B. Although it was originally intended to run under UNIX, there has been a great interest in running it under MS-DOS on IBM-PC. Many high-level languages like Pascal are highly disciplined and structured. C is much more flexible and free-wheeling. This freedom gives C much more power that experienced users can employ.


C has been a popular language due to its simplicity of expression, the compactness of the code, extensive use of function calls and the wide range of applicability. C is cryptic in nature. It allows the programmer a wide range of operations from high-level up to low-level.

Structure of a C Program

A, C program basically has the following structure.

  • Pre-processor commands
  • Type definitions
  • Function prototypes
  • Variables
  • Functions


Saturday, February 18, 2012

Object Oriented Programming


Object Oriented Programming


Object Oriented Programming is a modern, popular approach to programming which transcends the different generations, and represents an approach and methodology which is becoming the norm rather than the exception.

C++ is the object oriented extension of the C language.

Note that C++ (which we use) incorporates C, meaning that it is possible to use OO languages to program in a procedural manner

In procedural programming, the main emphasis is on the tasks necessary to effect a solution to the problem - the data on which the procedures act is the secondary focus.

In object-oriented programming the emphasis is reversed with the data being of prime importance and the procedures that act on that data assuming secondary focus.

The OO approach is seen as essential as software projects become more complex.

Saturday, February 11, 2012

Structured Programming


Structured Programming


Structured programming can be seen as a subset or sub-discipline of Procedural programming, one of the major paradigms (and probably the most popular one) for programming computers. It is possible to do structured programming in almost any procedural programming language, but since about 1970 when structured programming began to gain popularity as a methodology, most new procedural programming languages have included features to encourage structured programming, (and sometimes have left out features that would make unstructured programming easy). Some of the better known structured programming languages are : Pascal, Ada At the level of relatively small pieces of code, structured programming typically recommends simple,
hierarchical program flow structures. These can be obtained in most modern languages by using only structured looping constructs, often named "while", "repeat", "for". Often it is recommended that each loop should only have one entry point and one exit point, and a few languages enforce this.

Friday, February 3, 2012

Procedural Programming


Procedural Programming


A procedure or function is a self-contained program module that executes a set of specific instructions. The procedural approach focuses on the procedures that must be enacted in order to solve a particular problem. Thus a program can be viewed as a sequence of procedure calls. A procedure calls another (calling procedure) for services. After the sequence of statements in the called procedure is processed, the flow of control continues right after the point where the call was made. A procedure also can call a sub-procedure and in any case, calling procedure and the called procedure are allowed to exchange data in some way. This form of programming has been in existence the longest, and is still in use today by many programmers.

Thursday, January 26, 2012

A brief overview of programming techniques


A brief overview of programming techniques


In the early stages of computing, people neither have powerful computers nor intricate problems to solve as in today using computers. Both the programmers and the users were mostly computer professionals. Yet, programs were written but, in an unstructured way using a handful of programming languages.

An unstructured program consists of one main program module containing the sequence of statements. The data being used in the program are globally visible. i.e. common to the whole program. The suitability of unstructured programming is mostly limited to beginners who write simple programs or small utilities.

However, with the rising demand for IT applications, the things got changed. Today we have multifarious problems to solve in business, science, industry and everyday life. The most of the computer users are not computer professionals. So we need more sophisticated and user-friendly programs to outfit the current trend in Information Technology. The ability of programmers to organize well-structured solutions to problems is of major importance. In an effort to produce well organized, reliable, easily maintained and efficient programs, a number of guidelines and methodologies were developed.

Wednesday, January 18, 2012

Getting Closer to Natural Languages


Getting Closer to Natural Languages


Human thoughts originate in its natural form. Natural languages (English, French, Germen, etc.) play the major role in expressing human ideas. Therefore the development of computer languages those closely resemble natural languages was essential to program computers. Such languages are commonly known as High-level languages. Some examples of high-level languages are PL/I, COBOL, FORTRAN, BASIC and Pascal

Today there are more than two thousand high-level languages available for programming computers. Each language has its own objective and structure. For example the BASIC (Beginner’s All purpose Symbolic Instruction Code) and Pascal languages are originally intended to teach computer programming; while COBOL (Common Business Oriented Language) is intended to create business applications such as Payrolls, Stock Control Systems and so on. Some of the primitive high-level languages are being used extensively even today. This is due to the fact that they had been continuously updated to suite the trends in Information Technology. For example the BASIC language was developed in 1965. Since then it has been subjected to many developments and today, its newest version, Microsoft Visual Basic, is used in Rapid Application Development (RAD). In contrast to high-languages, machine language and assembly language are known as Low-level languages.

However, C language is unique among most of the high-level languages. It is neither high-level nor low level. It is rather considered mid-level as it can replace assembly language and still perform high-level operations Once again, a disadvantage of high-level or mid-level languages is the necessity of a translator to translate the program code (source code) into machine code (object code). There are two types of translators used for this purpose; namely an interpreter and a compiler. An interpreter translates one line of code at a time and executes it immediately. An example of a popular interpreter is Microsoft GW-BASIC. Interpreters are more suitable for novice programmers who write small programs and they can run each statement of the code, observing errors and correcting them. Interpreters are not so suitable for large programs where time matters.

A compiler on the other hand reads the whole source code form the beginning to the end and translates it into an object code. Therefore compilers detect errors in advance. An error that encounters in compilation process is known as a compile time error. Such an error has to be corrected and recompiled before the execution. However, after the compilation the object code is available for execution at any time. The advantage of compilation is that, the compiled code is very compact and runs fast. The disadvantage is that, each time an error is corrected it has to be recompiled.

Thursday, January 12, 2012

Machine Oriented Languages


Machine Oriented Languages

Programming a computer in machine language is an extremely difficult process. Machine language is
tedious, because so much of program code is needed to accomplish even simple tasks. One should
know the internal mechanism of the PU thoroughly to work with it. Machine language also differs from
PU to PU and is difficult to read and modify.

To make the programmer’s job little easier, another type of programming language called Assembly
Language was developed. An instruction in assembly language is in an ‘easy to remember’ form called
a mnemonic.

For example instructions to add, subtract, multiply and divide in machine language and assembly
language might look like as follows

M/C Instruction                            Assembly Instruction (mnemonic)
0000000111011000                                ADD
0010100111011000                                SUB
1111011111100011                                MUL
1111011111110011                                DIV

The main problem with assembly language when compared to machine language is that an assembly
language program cannot be directly executed by a computer. It needs another program to read
assembly code and translate it into machine language. A program that performs this task is called an
assembler.

Development of the assembly language and assemblers placed the programming task in the correct
track, but the programmers did not get much relief as they were still forced to think in terms of bits and
bytes.

Saturday, January 7, 2012

Early Stages in Programming


Early Stages in Programming

The earliest computers were not programmed in the same way as today’s computers, instead the programs were hard-wired into the machine and the physical wiring was done by hardware experts. In order to modify such a program, the programmer had to rearrange the wiring.

It was not long before John Von Neumann exposed the concept of sharing the same memory by both programs and data. In this case the programs were entered into the memory through a switch panel as a stream of bits.


Sunday, January 1, 2012

What is Programming?


What is Programming?

The roots of man-machine relationship runs back to thousands of years. Today, we manipulate various
kinds of machines. Out of myriads of machines available for the human, the computer has become the
foremost, due to the fact that it is programmable and versatile.

Like all other machines, computers are not wise. But it is made to obey and work according to a set of instructions given by the human. These instructions are stored in the computer’s memory and the computer is allowed to follow them in the given sequence. Thus computers provide a close association with human in the context of solving real world tasks. This has paved the way to, what is called “Computer Programming”.


Programming
The core activity in the process of instructing a computer in solving problems is known as programming.


Program
An ordered set of instructions given to a computer to accomplish a given task is known as a program.
[ Programming is the art of designing, coding, modifying and testing programs.]


Man-Machine Communication
Conveying human thoughts to a computer in solving problems is not easy. Human beings are intelligent. They use natural languages, signals, symbols etc. in exchanging ideas among them. Computers on the other hand are dumb. They can only understand their native language called machine language, which comprises of streams of bits and bytes. So one choice of programming a computer is to use machine language, in its native form.