Friday 8 March 2013

const modifier in c:


const modifier in c:

In c all variables are by default not constant. Hence, you can modify the value of variable by program. You can convert any variable as a constant variable by using modifier const which is keyword of c language.
Properties of constant variable:

1. You can assign the value to the constant variables only at the time of declaration. For example:

const int i=10;
float const f=0.0f;
unsigned const long double ld=3.14L;

2. Uninitialized constant variable is not cause of any compilation error. But you cannot assign any value after the declaration. For example:

const int i;

If you have declared the uninitialized variable globally then default initial value will be zero in case of integral data type and null in case of non-integral data type. If you have declared the uninitialized const variable locally then default initial value will be garbage.

3. Constant variables executes faster than non constant variables.

4. You can modify constant variable with the help of pointers. For example:

#include<stdio.h>
int main(){
    const int i=10;
    int *ptr=&i;
    *ptr=(int *)20;
    printf("%d",i);
    return 0;
}

Output: 20 

Constants



Constants: A constant is a value that does not change during the program execution. As its name implies it is a constant or fixed value. Constants are declared with the ‘const’ keyword. Constants in every language remain same. In some languages, constants are also known as literals. The constants can be classified as integer constant, floating constant, character constant and string constant. For example: const data_type var; 

Integer Constant: An integer is a whole number without decimal point. An integer may be either 0-9 digits or the combination of 0-9. Integer can be further divided into three different number systems: decimal (base 10), octal (base 8) and hexadecimal (base 16).
Octal: 1) It consists of numeric range 0-7 or combination of 0-7 numbers.
2) The first digit must be 0 in order to identify the constant as an octal.
3) For example: 00, 010, and 0200.
Decimal: 1) It consists of any combination of 0-9 digits. It is the most commonly used number system.
2) It is normal counting number of mathematics. The first digit needs not to be zero.
3) For example: 0, 8, 156, 25378 etc.
Hexadecimal: It consists of 0-9 digits and alphabets ‘a’ to ‘f’ or ‘A’ to ‘F’. Here ‘a’ to ‘f’ represents the decimal values 10 to 15. ‘A’ or ‘a’ is 10, ‘B’ or ‘b’ is 11 and so on.
2) A hexadecimal number must begin with 0x or OX.
3) For example: 0x0, 0x10, 0x265 etc.
Rules for integer constants: 1) it may be either positive or negative.
2) It must not have any decimal point.
3) No commas or blank spaces are allowed in an integer.
4) It must have at least one digit.


Floating Constant: A floating point constant has a real value. It is a numeric value with decimal point. It may be either of single precision or of double precision type. It may be written in two forms called the fraction form and exponent form.
Fraction form: In the fraction form, the value is represented as a whole number followed by a decimal point. For example: 130.35, -0.67
Rules for fraction form: 1) a decimal point should be present.
2) No commas or spaces are allowed.
3) It may be +ve or -ve but default is +ve.
Exponential form: In the exponential form a floating point constant has a mantissa part and exponent. The mantissa part and exponent part should be separated by e or E. For example: a number 234.56 can be written as 2.3456e2 or 2.3456e+2 i.e. 2.3456*10^2 Here 2.3456 represents mantissa part and the part after 'e' is exponent part, which has a base 10.
Rules: 1) the mantissa part can be written in positive or negative.
2) Spaces and commas are not allowed.
3) Letter e can be written in uppercase or lowercase.


Character constant: A character constant is a single alphabet, single digit or single symbol which is enclosed in single quotes (' '). Every character constant has a unique ASCII value. For example ASCII value of 'A' is 65. The maximum length of a character constant is only one character. For example: 'a', '&', '2' etc.
A character can be any ASCII character, printable or not printable from values -128 to 127. (But only 0 to 127 are used.) Control characters i.e. non printable characters are put into programs by using a backslash \ and a special character or number. The characters and their meanings are:
\b
backspace BS 
\f
form feed FF (also clear screen) 
\n
new line NL (like pressing return) 
\r
carriage return CR (cursor to start of line) 
\t
horizontal tab HT 
\v
vertical tab (not all versions) 
\"
double quotes (not all versions) 
\'
single quote character ' 
\\
backslash character \ 

These are some certain character constants that start with backslash (\). Such characters are known as escape sequence character. There are predefined in compile and used with output statements. These characters are non printable and have some specific tasks.
String constant: A string constant is a group of characters, which is enclosed in double quotes. So it is also called double quotes character constant. The characters enclosed in double quotes may be alphabet, digits, special symbols, escape sequence and spaces. For example: "This is my pen", "hi...\ this is Vijraj Bhargav", "My mobile number is 9872871471".

Variables


Variables: A variable is a symbolic name of a location in the computer's memory. In this variable, a value can be stored and this can be used in the program. The value of a variable may change during the program execution. Only one value can be stored at a time in it. In a variable you can store integer value or float value, character value or string names according to the requirement. As we know that a variable is an identifier of certain data. Every variable must have a name and a data type. A data type is the type of data which is to be stored in a variable. It can be an integer, floating, character or string name values. These values can be assigned to the variable using assignment operator: = (equal to)
Example of variable: sum=5+10; Here sum is a variable and 5 & 10 are two integer constant values. + And = are two operators. Semicolon (;) is used in the end of every C statement. This tells that it is end of statement.

Rules for naming variables: 1) a variable must be unique in a program’s block.
2) A variable name can contain only alphabets, digits and underscore. No any other symbol can be used.
3) The variable name must begin with a letter or an underscore.
4) A variable name must not start with a digit.
5) C language is a case sensitive language. It means upper case and lower case letters are different variable.
6) A variable name must not contain any white space. The white space includes tab, spacebar and new line.
7) It can’t be a C language keyword or reserve word. As we know that C is a case sensitive language and we can use different case of keywords as variable name.
8) A variable name cannot use a symbol in naming.
9) Some valid examples are: a, box, tab10, roll_no, Roll_no, _abc, For.
10) Some invalid examples are: 10tab, for, ab$c, roll no.
11) The length of variable name should be of 31 characters. If it is more than 31 characters then compiler will not generate any error but it will recognize only first 31 characters.


Where to declare Variables: There are two kinds of place in which declarations can be made.

  1. One place is outside all of the functions. That is, in the space between function definitions. (After the #include lines, for example.) Variables declared here are called global variables. They are also called static and external variables in special cases.)
#include <stdio.h>

int globalinteger;              /* Here! outside {} */

float global_floating_point;

main ()

{
}
2.      The other place where declarations can be made is following the opening brace, {}, of a block. Variables of this kind only work inside their braces {} and are often called local variables. Another name for them is automatic variables.
main ()

 { int a;
   float x,y,z;

 /* statements */

 }

Identifiers


Identifiers: A name or identifier in C can be anything from a single letter to a word. Identifiers are the names given to program elements such as variables, function names, array names and structure names. Once a type or value is assigned to an identifier, it cannot be changed during the execution of the program. For example: if an integer variable named as 'x' then 'x' will always remain an integer variable which can hold only integer or numeric value.

Rules of identifier: 1) an identifier must be unique in a program.
2) An identifier can contain only alphabets, digits and underscore. No any other symbol can be used.
3) The identifier must begin with a letter or an underscore.
4) An identifier must not start with a digit.
5) C language is a case sensitive language. It means upper case and lower case letters are different identifier.
6) An identifier must not contain any white space. The white space includes tab, spacebar and new line.
7) It can’t be a C language keyword or reserve word. As we know that C is a case sensitive language and we can use different case of keywords as identifier.
8) An identifier cannot use a symbol in naming.
9) Some valid examples are: a, box, tab10, roll_no, Roll_no, _abc, For.
10) Some invalid examples are: 10tab, for, ab$c, roll no.

Wednesday 6 March 2013

Keywords


Keywords: Some words in C programming are reserved for some special tasks. Such words are known as keywords. Their meaning is predefined in the compiler and compiler knows what to do with these keywords. Keywords are also known as the reserved words because these are reserved for C compiler. The programmer cannot use these words as variable or identifier in program. As we know that C is a case sensitive language and we can use different case of the keywords as identifier. The color of the keywords in C language is white. C language has total 40 keywords. 32 keywords are used in routine programming but remaining 8 characters are used in low level programming and rarely used. These 32 keywords are:
auto                else                  long                 switch
break               enum               register                        typedef
case                 extern              return               union
char                 float                 short                unsigned
const                for                   signed              void
continue          goto                 sizeof               volatile
default             if                      static                while
do                    int
               struct               double 

Character set and C-Tokens


Character Set: C is a powerful programming language. Not only C, every language follows some rules. These rules are required for writing a program. In order to write a program some alphabets, digits and special symbols are used. All this is known as Character set. Character set is used to write program blocks, variables and identifiers etc. Character set consists of the upper and lower case alphabets, digits, special characters and white space.
Alphabets: It consists of both upper and lower case alphabets. It can be ‘A’ to ‘Z’ or ‘a’ to ‘z’ or combination of the alphabets. These are used for naming purpose. C language is a case sensitive language. It means that lower and upper case alphabets are different. For example: 'A' is different from 'a'. Both can be used in the program and both can contain different values. But one thing should be noted that same variable or name cannot be used for two purposes. If we do so then it will create a big confusion.
Digits: Digits represent to the numeric values. These are used by the programmer for assigning the values to the variables. Digits are same as the mathematical digits i.e. 0 to 9 or combination of the digits. It consists both of positive and negative numbers. Also it includes decimal point values. The programmer can assign any numeric value depending on the data type. For example: a=5, b=109, c=-69, d=48.56
Special Symbols: On the keyboard all keys are special symbols except alphabets, digits and function keys or hot keys. Such as: &, $, @. All these symbols are used for special purposes.
Tokens: Tokens are various C program elements. Tokens are identified by the compiler during compilation. Tokens are useful for compiler to detect errors. When tokens are not arranged in a particular sequence then compiler generates an error message. These tokens are: Keywords, Identifiers, Variables, Constants and Delimiters or separators

Types of Errors


Types of error: An error is considered as a speed breaker in the process of program developing. This error may be of any type. There are four types of errors.
1) Syntax error, 2) Linking error, 3) Run Time error, 4) Logical error
Syntax error: This error occurs when the rule or syntax of the language is broken. Such errors may be of missing semi colon, missing of any punctuation, misuse of any term etc. For example: c = (a+b/2; Here in example, closing bracket is missing after b.
All syntax errors must be found and corrected before a program is made to run. Almost all the language compilers and interpreters are designed to detect syntax errors. The language processors print error messages on the screen that indicates the number of the statement with errors and gives hints of nature of the error.
Linking error: As we know that each language comes with built in libraries and basic functions. To execute a program we use these basic functions along with the libraries. It is the responsibility of the linker to link the function with the library. If the linker does not find the library then an error is generated. This error is known as linking error. For example: if main() method's library is not defined i.e. stdio.h
Runtime error: It is not sure that after successfully compiling and linking a program, it will display the desired result. The result may be wrong due to errors in logic such as division by zero, square root of a negative number. Runtime errors are harder to find and to correct them. It is because compiler does not tell us about the error. Compiler does not tell the number of line in which the occurred and also not the nature of the error.
Logic Errors: Logic errors are those that appear once the application is in use. They are most often unwanted or unexpected results in response to user actions. In this case the language processor successfully translates the source code into machine code. Also a computer actually does not know that an error has occurred. It follows the instructions and produces the results, but this output may be wrong. For example, a mistyped key or other outside influence might cause your application to stop working. Logic errors are generally the hardest type to fix, since it is not always clear where they originate.

Assembler, Compiler, Interpreter, Linker, Loader


Assembler: A computer will not understand any program written in a language, other than its machine language. The programs written in other languages must be translated into the machine language. Such translation is performed with the help of software. A program which translates an assembly language program into a machine language program is called an assembler. If an assembler which runs on a computer and produces the machine codes for the same computer then it is called self assembler or resident assembler. If an assembler that runs on a computer and produces the machine codes for other computer then it is called Cross Assembler.
Assemblers are further divided into two types: One Pass Assembler and Two Pass Assembler. One pass assembler is the assembler which assigns the memory addresses to the variables and translates the source code into machine code in the first pass simultaneously. A Two Pass Assembler is the assembler which reads the source code twice. In the first pass, it reads all the variables and assigns them memory addresses. In the second pass, it reads the source code and translates the code into object code.
Compiler: It is a program which translates a high level language program into a machine language program. A compiler is more intelligent than an assembler. It checks all kinds of limits, ranges, errors etc. But its program run time is more and occupies a larger part of the memory. It has slow speed. Because a compiler goes through the entire program and then translates the entire program into machine codes. If a compiler runs on a computer and produces the machine codes for the same computer then it is known as a self compiler or resident compiler. On the other hand, if a compiler runs on a computer and produces the machine codes for other computer then it is known as a cross compiler.
Interpreter: An interpreter is a program which translates statements of a program into machine code. It translates only one statement of the program at a time. It reads only one statement of program, translates it and executes it. Then it reads the next statement of the program again translates it and executes it. In this way it proceeds further till all the statements are translated and executed. On the other hand, a compiler goes through the entire program and then translates the entire program into machine codes. A compiler is 5 to 25 times faster than an interpreter.
By the compiler, the machine codes are saved permanently for future reference. On the other hand, the machine codes produced by interpreter are not saved. An interpreter is a small program as compared to compiler. It occupies less memory space, so it can be used in a smaller system which has limited memory space.
Linker: In high level languages, some built in header files or libraries are stored. These libraries are predefined and these contain basic functions which are essential for executing the program. These functions are linked to the libraries by a program called Linker. If linker does not find a library of a function then it informs to compiler and then compiler generates an error. The compiler automatically invokes the linker as the last step in compiling a program.
Not built in libraries, it also links the user defined functions to the user defined libraries. Usually a longer program is divided into smaller subprograms called modules. And these modules must be combined to execute the program. The process of combining the modules is done by the linker.


Loader: Loader is a program that loads machine codes of a program into the system memory. In Computing, a loader is the part of an Operating System that is responsible for loading programs. It is one of the essential stages in the process of starting a program. Because it places programs into memory and prepares them for execution. Loading a program involves reading the contents of executable file into memory.  Once loading is complete, the operating system starts the program by passing control to the loaded program code. All operating systems that support program loading have loaders. In many operating systems the loader is permanently resident in memory. 

Programming language


Programming Language: An artificial language used to write programs that can be translated into machine language and then executed by a computer. As we know that computer understands only machine language. It does not understand the English language or any other what we normally use. So to perform tasks from computer we use programming language to write programs. These programs tell the computer what to do? Each natural language has a method of using symbols of that language. In English, the method is given by the rules of the grammar. These rules tell us which word to use when and how to use it. Similarly, the rules of a programming language must also be used. These rules are known as “Syntax Rules”. In case of natural language people can use poor and incorrect language, but in case of programming language we can’t use. Each language has strict syntax rules and these rules cannot be ignored. Each program has its own syntax and this is further converted to machine language. Now after the conversion, machine is able to understand the task. This conversion is done by compiler or interpreted. A compiler or interpreter is tool that converts the program into machine language. Each programming has its own compiler or interpreter. Programming language can be classified into three broad categories: 1) Machine Language 2) Assembly Language and 3) High Level Language.
Machine Language: It is the language of the computer machine itself. A machine can understand this language directly without any translator. It is also known as Binary language. It is only two digits language i.e. 0s and 1s. It is first generation of the programming languages. Machine language was used when the computer was of a huge size; approximately it covered one room.
                        Only the developers could work with the computer. Because it was not easy as it is today. Input was firstly converted into the Binary language of zeros and ones. Then fed to computer, computer processed it and output is generated. This output is also in the form of machine language. Again it was converted to human understandable language English. Thus it was a headache giver task.
                        Machine language is the fundamental language of the machines. Each machine we see today works on the machine language. We give input in English and machine works on the machine code.  Some interfaces are there that converts our language into machine language. The circuitry of a machine is wired in such a way that it immediately recognizes the machine language and operates the machine.
                        Machine language is not very easy language to learn. It is difficult to read and understand. The most important advantage of machine language is that programs written in machine language are executed very fast by the computer. This is mainly because machine language is directly understood by the CPU and no translation of the program is required. However writing a program in machine language has several disadvantages; Machine Dependent, Difficult to program and Difficult to modify. Machine dependent means the machine code of one machine will not work for other machine.
                        Machine Language is the toughest language of all the generations. Only developers of this language and experienced scientists can use this language. New learner or normal users can’t even understand it because of its complexity.


Assembly Language: In machine language we write the programs in binary code i.e. 0s and 1s. That is headache giver task. But this headache is reduced by the Assembly Language. In Assembly Language, programs can be easily written in alphanumeric symbols instead of 0s and 1s. For good and effective programming, meaningful and easily remember able symbols are selected. For example: ADD for addition, SUB for subtraction, CMP for comparison etc. Such symbols are known as Mnemonics. A language which uses these mnemonics symbols is known as Assembly Language. A program written in assembly language is known as assembly language program.
The advantage of assembly language is that the execution time of an assembly language program is less. An assembly language program runs faster to produce results.
The most disadvantage of assembly language is that programming in this language is difficult and time consuming. Assembly language is machine dependent. The programmer must have detailed knowledge of the structure of the computer. He must have the knowledge of registry of the computer. The program written in assembly language for one computer cannot be used in any other computer. It means that the assembly language program is not portable. Each processor has its own instruction sets and hence its own assemble language.
High Level Language: A language, in which instructions are written, is called High Level Language. The instructions written in a high level language are called statements. These statements are closer to English and mathematics as compared to mnemonics in assembly languages. Example of high level languages are BASIC, PASCAL, FORTRAN, COBOL, ADA, C, C++, C# and JAVA etc.
High level languages are independent of computer architecture. A programmer does not need knowledge of architecture of the computer. The programming is easier. The same program can run on any other computer which has a compiler of that language. The compiler is machine dependent but not the language. Thus language is machine independent.
High level languages are very similar to English like language. These are easy to learn and use. The programmer needs not to learn anything about the computer. He need not to worry about how to store the code in the computer, where to store them, what to do with them etc. All this was in the previous languages.
Writing programs in high level languages requires less time and effort. Programs written in high level languages are easier to maintain than assembly language or machine language programs. This is because these are easier to understand, easier to correct and modify. Insertion or removal of instructions from a program is also possible.
Disadvantage of high level language is that it takes more time to run and requires more computers’ main memory.


Source and Object Language: The language in which a programmer writes programs is called source language. It may be high level language or an assembly language. The language in which the computer works is called object language or machine language. A program written in a source language is called a source program. When source program is converted into machine code by an assembler or compiler it is known as an object program. In other words, a machine code program ready for execution is called an object program.

Algorithm

Algorithm: It is a sequence of instructions (or set of instructions) to make a program more readable. It is a process used to answer a question. In simple words an algorithm is a step-by-step procedure for solving a problem. Algorithms can be expressed in any language, from natural languages like English to programming languages like C. We use algorithms every day. For example, a recipe for baking a cake is an algorithm. Most programs consist of algorithms. Making algorithm is one of the principal challenges in programming language. An algorithm must always terminate after a finite number of steps. Simple example of algorithm to add two numbers:
                        An algorithm must have one starting point and one or more ending point. Its starting point can be labeled as START and its ending point can be labeled as STOP. Here is example of one starting point and one ending point.
Example of adding two numbers:
Step 1: Start.
Step 2: Take three variables named num1, num2, num3.
Step 3: Input the values in two variables: num1 = 10, num2 = 5.
Step 4: Now add num1 & num2 and put its value to num3: num3 = num1 + num2. Here both operands num1 and num2 are added and its combined value is assigned to num3.
Step 5: Now print the value of num3. Your result is displayed on the screen.
Step 6: Stop.
Example of finding bigger number between two numbers with one START and two STOP:
Step 1: START.
Step 2: Take two variables named num1, num2.
Step 3: Read num1 and num2.
Step 4: if num1>num2 then
Step 5: print num1.
Step 6: STOP.
Step 7: else
Step 8: print num2.
Step 9: STOP.

Features of C language


Features: C language is known as a middle level language, because it contains the features of both low level language and high level language. Its features are as below:
1. Clarity: C language is quite close to English language. So its syntax is clearer and more understandable. Its variables, names etc are written in simple English.
2. Portability: C language is a portable and can be run on any machine. It is independent of the type of CPU and machine.
3. Built in: Various built in functions are available in C to perform required operations.
4. Modular: C language is a modular programming language which makes a “Divide and Conquer” approach. In this approach we can module the programs and they are now easy to manage and understand.
5. Quicker Compiler: The speed of executing the C programs is very fast.  A program in C, created on one computer can be compiled and run on any other machine that has a similar C compiler.
6. Simplicity: C language is easy to learn and easy to debug (Debug means to make a program error free). Because of its easiness it is widely used from micro computers to mainframe computers.
7. Detect ability: It is a User Friendly language. C compiler detects the errors easily and displays along with the program. It means C compiler tells us that where the errors are. It tells us the type and number of the line in which the error is present.
8. Location of Data: It supports to the Pointer concept which tells us that where variables are stored in the computer memory.
9. C language is case sensitive language. It means lower case and upper case letters are considered as different.

Tuesday 5 March 2013

Intro of C


Basic of C language
Introduction: C language was designed by Dennis Ritchie at Bell Laboratories between 1969 and 1972. There were many developments of C language between 1969 and 1972. And final language came into existence in 1972. Like other languages C language was undergone a number of versions. In every new version many new features were added to make it more powerful and more useful. It was not written as a teaching help, but as an implementation language. It was developed for developing operating systems, utility programs and compilers. C is a powerful structured and module programming. Like most high level languages, C is a modular programming language. In which each task can be developed as a module. It was written when computers were big and they capital equipments.
                        C language is mainly influenced by the language B, which was further influenced by the BCPL language. C language was also influenced by the languages such as CPL, Assembly, FORTRAN and ALGOL. This C language further influenced some languages such as C++, C--, C sharp, Java, JavaScript and Perl etc.
                        C language is known as middle level language because it consist the features of low level language and high level language. Low level features are used for low level programming and High level features are used for high level programming and mostly the high level programming is developed.
                        The first major use of C language was to write an operating system called UNIX. The success of UNIX operating system and its features brought the consequent popularity for the C language. It was standardized in 1989 by ANSI (American National Standards Institute) known as ANSI C.