C Language Notes
February 11, 2017 | Author: momghost | Category: N/A
Short Description
Download C Language Notes...
Description
Index Introduction of Programming Directory Structure of C Language Integrated Development Environment Data Types. printf , scanf Functions ,getch function. Constants , Variables , Keywords , Operators, Escape Sequence, Format Specifier. Decision Making In C Using if statement & switch case default. Loop. User Defined Functions. Preprocessor Directives. Pointer.
1
Introduction to Programming Languages Programming languages are classified into two different types. Procedural and Non-Procedural Procedural languages specify how something is accomplished. Non Procedural languages specify what is accomplished without going into detail of how. The difference b/w Procedural and Non-Procedural language is illustrated in following example: Procedural language : Like I am sit on a Taxi and give directives to Taxi Driver….The directions might go as : Drive 600 yards forward, Turn right then Drive 300 yards forward then Stop. Non-Procedural language: You would simply tell the Driver what you want. “Take me to Tariq Road”
Topic 2
Introduction to C - Language
C is a programming language developed at AT & T’s Bell laboratories of USA in 1972. It was designed and written by a man named Dennis Ritchie. C is so popular b/c it is reliable, simple and easy to use.
Where C Stands C is often classified a middle-level language. C is b/w these two categories i.e High level language and Low level language.
Learning Language Communication with a computer involves speaking the language the computer understand. Learning any Computer language is like the same as we learn other spoken languages. If we want to learn English we first learn alphabets or characters used in the language, then word and then form a sentence and sentence are combined to form a paragraph. Learning C is similar. Steps in learning English: Alphabets
Words
Sentence
Paragraph
Constant Variables Keywords
Instructions
Program
Steps in learning C: Alphabets Digits Special Symbols
C Character Set Alphabets
A,B,………….Y,Z A,b,…………..y,z Digits 0,1,2,3,4,5,6,7,8,9 Special Symbols ~ ! @ # % ^ ` & * ( ) _ - + = | \ [ ] { } : ; “ ‘ < > ? /
2
Directory Structure of C C :\TC
BIN ( Bin Folder contains TC.exe file to execute IDE) INCLUDE ( Header Files is like text files …….extension .h) LIB ( Routines for performing specific task…extension .lib)
Don’t change the name of the sub-directories.
Executable Files Executable files are stored in the sub directory BIN. The most important exe. File is TC.exe.
Library Files If a programmer uses a function such as printf() to display text on the screen, the code to create the display is contained in a library file. A library file has unique characteristics: only those parts that are necessary will be linked to a program, not the whole file.
Concepts of Header Files Header Files : The sub directory called INCLUDE contains header files. These files also called “Include files” are text files like the one you generate with word processor. Header files can be combined with your program before it is compiled, in a same way that a typist can insert a standard heading in a business letter. Each Header file has a .h file extension. Header files serve several purposes. You can place statements in your program listing that are not program code but instead message to the compiler. These messages called compiler directives, can tell the compiler such things as the definition of words and phrases used in your program. Some useful compiler directives have been grouped together in header files, which can be included in your source code of your program before it goes to the compiler.
IDE (Integrated Development Environment) & Command line Development Turbo C features an IDE, which provides a platform to C programmers. There is another completely different way to develop C programs in Turbo C. This is a traditional command – line system, in which editing, compiling, linking, debugging and executing are performed in Dos environment. Two different language translators Programs are used to translate High level languages : 1. Compilers 2. Interpreters 3. Assembler Compiler: A compiler translates a whole program, called the source code, into machine language all at one time before the program is executed. Once converted, the program is stored in machine readable form called the object code. Like:
ABC SOURCE CODE
COMPILING COMPILER
The Object code can be immediately executed anytime thereafter. 3
100101000010 OBJECT CODE
Interpreter: A Interpreter translates a program into a machine language one line at a time, executing each line of the program after it is translated. With most Interpreters, the machine readable form is not stored in main memory or on a secondary storage medium. Therefore, the program must be interpreted each time it is executed.
Making an EXE. File After you’ve written the source file for your program, you need to turn it into an executable file. Compiling: The program you typed is understandable to human being (at least if they know C). However, it is not understandable to the microprocessor in your computer. There must be two versions of the program. The one you type which is Source file and the machine language version, which is called the exe file (also called binary file). The Compiler which is a part of the IDE, translates this source code into machine language.
Linking The text editor produces .c source file, which go to the compiler, which produces .obj files, which go to the linker, which produces .exe executable files.
Stdio.h
Myprog.c
MyProg.obj
Myprog.exe
Compiler
Linker Cs.lib
4
IDE (Integrated Development Environment) & Command line Development Turbo C features an IDE, which provides a platform to C programmers. There is another completely different way to develop C programs in Turbo C. This is a traditional command – line system, in which editing, compiling, linking, debugging and executing are performed in Dos environment. IDE : It’s also referred to as the Programmer’s Platform. It is a screen display with windows and Pull-down menus. IDE provides all necessary operations for the development of your C Program, including editing, compiling, linking, and Program execution. You can even debug your program within the IDE.
Basic Structure of C Program Learning C, as it true with any language, is a largely a matter of practice. Void main(void) { Printf(“Sadequain”); } Function Definition: All C Programs are divided into units called “Functions”. No matter how many functions there are in C program, main( ) is the one to which the control is passed from the operating System, when the program is run, it is the first function to execute. The word “void” preceding “main” specifies that the function main( ) will not return a value. The second “void”, in parentheses ------ ( ), specifies that the function takes no argument.
Conclusion: C program consists of functions. The main( ) function is the one to which control is passed when the program is executed. Function Define: Our program begins the way all C functions do with a name followed by parentheses. This signals the compiler that a function is being defined. Delimiter (Draws a boundary)…{ }……”{“ The Opening Brace indicates that the opening the block of code and ending Brace “}” terminates the block of code. Statement Terminator: A statement in C is terminated with a semicolon ( ; ). Semicolon terminates the line. Each instruction in a C is written as a separate statement.
Structure of a C Program Function Name
one statement
void main(void)
Opening Brace to delimit body of function
{ printf(“ Sadequain “);
semicolon to terminate
}
each program statement
closing brace to 5
delimit body of function
This entire program consists Of a function called main( )
Function Basics: Function is always in small case. No space b/w function name and parenthesis…..like printf ( ) is wrong. If you are using INPUT and OUTPUT function you have to INCLUDE header file….#include and #include . Function always return a value.
Exploring the printf( ) function The general form of printf( ) statement is …..printf(“ “ , list of variables); The printf( ) is a very powerful and versatile function. printf( ) is a output function. Printing Numbers in printf( ) function: The printf( ) function using a unique format for printing constants and variables. Like:
format specifier printf(“ This is a number two : %d”, 2);
Output:
This is a number two : 2
Why was the digit 2 printed, and what effect does the %d have. String on the left……..and value on the right. The two arguments are separated by a comma. Format Specifier: The format specifiers tells printf( ) where to put a value in a string and what format to use in printing the value. %d tells printf( ) to print the value 2 as decimal integar. Other specifier could be used for the number 2. Like %f could cause the 2 to be printed as a floating point number. Printing Strings: Using the format specifier we can print constants as well as numbers….like: Printf(“ I am %s and I am %d years old”,”Any Name”,25); left side
Right side
Scanf( ) Function: scanf ( ) is an input function. The scanf( ) function can accept input to several variable at once. The scanf( ) function use ampersand ( & ) preceding the variable names used as arguments. 6
“Fundamentals of C Program” Constant: A constant is the quantity/value that doesn’t change. This value can be stored at a location in the memory of the computer.
int num=1;
Variable: Variable may be the most fundamental aspect of any computer language. A variable is a space in the computer’s memory set aside for a certain kind of data and given a name for easy reference. Variable are used so that the same space in memory can hold different values at different times.
Rules for Variable Names A Variable name is any combination of 1 to 8 alphabets, digits or underscore. The first character in the variable name must be an alphabet. No commas and space are allowed within a variable name & No special symbol other than underscore can be used in variable name.
Variable Definition:
int num; is an example of variable definition. In a C program all variables must be defined. If you have more than one variable of same type, you can define them all with one type name, separating the variables name with commas. Any variable used in a program must be declared before using it in any statement. When you define variable, the compiler sets aside an appropriate amount of memory to store that variable.
Defining and Declaring Variable: Variable definition specify the name and type of variable, and also set aside memory space for the variable. A variable declaration in contrast specifies the variable’s name and data type, but doesn’t set aside any memory for the variable. In most cases the word “Declaration” is used for both meanings. Initializing Variable: It’s possible to combine a variable definition with an assignment operator so that a variable is given a value at the same time it’s defined……like int num = 5; float num1 = 10.5;
Keywords: Keywords are the words whose meaning has already been explained to the C compiler (to the Computer). The Keywords cannot be used as variable names b/c if we do so we are trying to assign a new meaning to the keyword. It’s safer not to mix up the variable name and the keywords. There are only 32 keywords available in C some of them are ……. void, if, else, switch, case, default do, for, while, float, int, short, long, signed, unsigned….etc etc.
Operators: Operators are words or symbols that cause a program to do something to variable. There are many kinds of operators we’ll mention the most common one. Arithmetic and Relational operators and Increment and Decrement operators. 1. Arithmetic Operators........ ( +, - , * , / , % ) 2. Relational Operators…( , =, ==, !=) which is (less than, greater than, less than equal to, not equal to) 3. Logical Operators………...( &&, ||, !) which is (AND, OR, !) 7
Arithmetic Operator: Precedence 1st 2nd 3rd
Operator * / % +=
Description Multiplication, division, remainder Addition, subtraction Assignment
Note : The fact that (*) and (/) have a higher precedence than (+) and (-). Remainder operator is used to find the remainder when one number is divided by another.
Escape Sequences: The symbol ( \ ) backslash is considered an escape character. The tab and new line are the most often used escape sequence. \n Newline \t Tab \b Backspace \’ Single quote \” Double quote \\ Backslash
( for new line) ( moves next 8 space wide field ) ( moves the cursor one space left ) ( print single quote) ( print double quote) ( print backslash )
Format Specifiers: we use format specifier ( such as %d or %c ) is used to control what format will be used by printf( ) function to print out a particular variable. %c %s %d %u %f %l (% L)
To print single character To print String To print signed decimal integer To print unsigned decimal integer To print floating point Prefix used with %d %u to specify long integer ….like ( %ld, %lu)
Data Type Numeric Data 500 Hole Number
500.00 Decimal Number
8
5002 Scientific
Data Type:
Note short integer are the same as integer.
Data Type
Range
Byte
Format
Signed char unsigned char short signed int short unsigned int long signed int long unsigned int float double
-128 to 127 0 to 255 -32768 to +32768 0 to 65535 -2147483648 to +2147483647 0 to 4294967295 10-38 to 1038 10-138 to 10 138
1 1 2 2 4 4 4 8
%c %c %d %u %ld %lu %f %lf
More on Data Types Integer, long and short: Integers always occupies 2 Bytes in memory with a range of (32767 to -32768). Remember that out of the 2 Bytes use to store an integer, the highest bit ( 16th bit) is used to store the sign of the integer. This bit is ( 1) if the number is negative (-ve) and 0 when the number is positive (+ve). C offers a variation in integer data type that is called long integer value. The long integer occupy 4 Byte in memory and use long prior to integer in declaration like: long int num; long int num=10; The range of value that we can hold in long integer will expand tremendously. In fact short is nothing but our ordinary integer, which we are using all the time without knowing that it was a short integer.
Integer, signed and unsigned: If we know in advance that a value stored in a given integer will always be positive, so we can use: unsigned int; With such a declaration the range of integer value will shift from the range 32767 9
32768 65535 Unsigned almost double the size of the value that it can hold and reserve the same 2 Bytes. Unsigned integer is nothing but a short unsigned integer.
Chars, signed and unsigned: The way there is a signed and unsigned integer similarly there are signed and unsigned chars. A signed char is same as our ordinary char and has a range from (-128 to 127) where as an unsigned char has a range from 0 to 255. 128 127 255 Floats and Double: Float occupies 4 Bytes in memory and can range from 10-38 to 1038 whereas double data type occupies 8 Bytes in memory and has a range from 10308 to 10-308 .A variable of double can be declared as: double num;
Decision Making in C: Up to now we have used sequenced control structure in which the various steps are executed sequencly i.e in the same order in which they appear in the program. Computer languages can perform different sets of actions depending on the circumstances. C has 3 major decisionmaking structure. 1. if statement 2. if-else statement and 3. switch statements
How to use if statement: C uses the keyword “ if ” for basic decision making statement. The if statement is similar to the while . Without any operator, we cannot apply more than one condition. If you use only one statement after condition, then braces{ } sign is optional. if( This Condition is True) execute this statement; If the condition is true, then the statement is executed otherwise not. Relational Operators (= =, ! =, , =) allow us to compare two values. Note that (=) is used for assignment, whereas (= =) is used for comparison of two quantities.
Relational Operator
Conditional expression
if (char= = ‘y’) printf(“You type y”);
Terminating semicolon Structure of if statement
Keyword
Body of if statement
10
In the while statement, if the condition is true, the statement in the body of the loop will be executed over and over until the condition becomes false: In “if “ statement they will be executed only once. The && and || operators allow two or more conditions to be combined in an if statement.
The if-else statement When the test expression is true, the statement will execute in the body of if statement. It does nothing when it’s false. We can execute a group of statement if and only if the test expression is not true. This is a purpose of the else statement. Condition expression
Body of if statement
keyword
if (char= = ‘y’) printf(“You type y”); else printf(“\nYou did not type y.”);
keyword
Body of else statement
Logical Operators: ( && , || , ! ). They are composed of double symbols ( || ), ( &&). Logical Operators have a lower precedence than the relational operators….such as ( = = ). The relational operators are evaluated first then the logical operators. Logical Operators are always evaluated from left to right………. if( a
View more...
Comments