1.48k likes | 1.72k Views
Basics of C Programming. UNIT-I. Basic Terminologies. Computers -really dumb machines because they do only what we are told to do. A computer program - is just a collection of the instructions necessary to solve a specific problem.
E N D
Basics of C Programming UNIT-I
Basic Terminologies • Computers-really dumb machines because they do only what we are told to do. • A computer program - is just a collection of the instructions necessary to solve a specific problem. • Algorithm-The approach or method that is used to solve the problem.
Continue.. For example: Develop a program that tests if a number is odd or even. • First express the solution to the problem in terms of an algorithm • Then develop a program that implements that algorithm. Algorithm for above problem • First, divide the number by two. • If the remainder of the division is zero, the number is even; • Otherwise, the number is odd.
1. Machine Level Language - Binary numbers that corresponded directly to specific machine instructions and locations in the computer’s memory. 2. Low-Level Language (Assembly language) - permits the programmer to use symbolic names to perform various operations and to refer to specific memory locations. Assembler - A special program that translates the assembly language program from its symbolic format into the specific machine instructions of the computer system
Disadvantage of Assembly language • Machine dependent -Different processor types have different instruction sets. Assembly language program will not run on a different processor type without being rewritten. • Not Portable - Programmer learn the instruction set of the particular computer system to write a program in assembly language.
3. Higher-level languages (HLL)-came to overcome the machine dependent issue of low-level language. • FORTRAN(FORmulaTRANslation) was the first higher-level language. • Merits: Machine independent - A program could be written in any language is to be run on any machine that supported the language with few or no changes.
Compiler • To support HLL, a special computer program is used to translates the statements of the HLL into particular instructions of the computer. • First, Analyzes a program which written in a particular computer language (HLL) • Then translates it into a form that is suitable for execution on particular computer system.
Operating system- A program that controls the entire operation of a computer system. • All I/O operations that are performed on a computer system are channelled through the operating system. • Also manage the computer system’s resources. • Handle the execution of programs. • Most popular operating systems today is the Unix, Microsoft Windows XP.
Compilation Process • Write Source Program using Text Editor • The program that is to be compiled is first typed into a fileon the computer system. • A text editor is usually used to enter the C program into a file. • C programs can typically be given any name provided the last two characters are “.c”. • For example, vi is a popular text editor used on Unix systems. The program that is entered into the file is known as the source programbecause it represents the original form of the program expressed in the C language.
2. Debugging Phase: Compiler checks each program statement in source program to conforms the syntax and semantics of the language. *unbalanced parentheses (syntactic error) * variable that is not “declared” (semantic error) • If any mistakes are discovered then it reported to the user and the compilation process ends right there. • So errors have to be corrected in the source program (with the use of an editor), and the compilation process must be restarted.
Creation of Object code file • Once all syntactic and semantic errors have been removed from the program, the compiler then proceeds to take each statement of the program and translate it into a “lower” form. (translated into the equivalent statements in assembly language) • Next the assembler takes each assembly language statement and converts it into a binary format known as object code, which is then written into another file on the system. • This file typically has the same name as the source file with the last letter an “o” (in unix) or “obj” (in windows) instead of a “c”.
3. Linking Process (Creation of executable object code) • Now object code is ready to be linked. If the program uses other programs that were previously processed by the compiler, then those programs are linked together. • Programs that are used from the system’s program library are also searched and linked together with the object program during this phase. • The process of compiling and linking a program is often called building. • The final linked file is an executable object code which is ready to be run or executed. It is stored in another file on the system, (In Unix, this file is called “a.out”, In Windows, same name as the source file, with “exe” extension).
4. Loading & Execution • To run the program, an executable object code file must be loaded into the computer’s memory and initiating its execution. • When the program is executed, each of the statements of the program is sequentially executed in turn. • If the program requests any data from the user, known as input, the program temporarily suspends its execution so that the input can be entered. Or, the program might simply wait for an event, such as a mouse being clicked, to occur. • Results that are displayed by the program, known as output, appear in a window called the console. Or, the output might be directly written to a file on the system.
If all goes well, the program performs its intended functions. • If the program does not produce the desired results, it is necessary to go back and reanalyze the program’s logic. This is known as the debugging phase, during which an attempt is made to remove all the known bugsfrom the program. • To do this, make changes to the original source program. So the entire process of compiling, linking, and executing the program must be repeated until the desired results are obtained.
Compiler Vs Language Interpreters • Another method used for analyzing and executing programs developed in a higher-level language. • Source Programs are not compiled but are interpreted. • An interpreter analyzes and executes the statements of a program at the same time. This method usually allows programs to be more easily debugged. • It is slower than compilation because statements are not converted into their lowest-level form in advance of their execution. Example • BASIC and Java are two programming languages in which programs are often interpreted and not compiled. • Other examples include the Unix system’s shell and Python. • Some vendors also offer interpreters for the C programming language.
Integrated Development Environment • The process of editing, compiling, running, and debugging programs is managed by a single integrated application known as an IDE. • An IDE is a windows-based program that allows you to easily manage large software programs, edit files in windows, and compile, link, run, and debug your programs. • Most IDEs also support program development in several different programming languages in addition to C, such as C# and C++. Example • In Mac OS X, CodeWarrior and Xcodeare two IDEs used. • In Windows, Microsoft Visual Studio is a popular IDE. • Kylix is a popular IDE for developing applications under Linux.
Programming paradigms • Way to classify programming languages based on their features. • Languages can be classified into multiple paradigms. • Some paradigms are concerned mainly with implications for the execution model of the language, • Other paradigms are concerned mainly with the way thatcode is organized. • Yet others are concerned mainly with the style of syntax and grammar.
Execution model& Side effects • Execution model specifies how work takes place. • Every programming language has an execution model cover What is an indivisible unit of work? & What are the constraints on the order in which those units of work take place? • This order may be chosen ahead of time, or it can be dynamically determined as the execution proceeds. • The implementation of an execution model can be via compiler/ interpreter, and includes a runtime system. • Side effects -way that a program interacts with the outside world (people, file systems, other computers on networks). But the degree to which side effects are used depends on the programming paradigm.
Example: C programming language has a concept called a statement. Statements are indivisible units of work and that they proceed in the same order as their syntactic appearance in the code (except when a control statement such as IF or WHILE modifies the order). The C language actually has an additional level to its execution model, which is the order of precedence. It states the rules for the order of operations within a single statement.
Common programming paradigms • Imperative which allows side effects. (in which the programmer instructs the machine how to change its state) • Object-oriented which groups instructions together with the part of the state they operate on. • Procedural which groups instructions into procedures. • Declarative in which the programmer merely declares properties of the desired result, but not how to compute it. • Functional in which the desired result is declared as the value of a series of function applications. • Logicin which the desired result is declared as the answer to a question about a system of facts and rules. • Mathematical in which the desired result is declared as the solution of an optimization problem
Imperative paradigm has two main features: they state the order in which operations occur and they allow side effects. Most object-oriented languages are also imperative languages. • Declarative paradigm does not state the order in which to execute operations. Instead, they supply a number of operations that are available in the system, along with the conditions under which each is allowed to execute. The execution model tracks which operations are free to execute and chooses the order on its own.
Languages support single/multiple paradigms • Languages are designed to support one paradigm (Smalltalk supports object-oriented programming, Haskell supports functional programming). • Multi paradigm supported languages can be purely procedural, purely object-oriented, or can contain elements of both or other paradigms. • Example: Object Pascal, C++, Java, C#, Scala, Visual Basic, Lisp, Scheme, Perl, PHP, Python, Ruby, Oz, and F# • Software designers and programmers decide how to use those paradigm elements.
Introduction to C • C is a high-level structured oriented programming language used in general purpose programming, developed by Dennis Ritchie at AT&T Bell labs, USA between 1969 and 1973. • Some Facts about C Programming Language • In 1988, the American National Standards Institute (ANSI) has formalized the C language. • C was invented to write UNIX operating system. • C is a successor of ‘Basic Combined Programming Language’ (BCPL) called B language. • Linux OS, PHP and MySQL is written in C. • C has been written in assembly language.
Uses of C Programming Language • In the beginning C was used for developing system applications e.g. : Database Systems, Language Interpreters, Compilers and Assemblers, Operating Systems, Network Drivers, Word Processors C has Become Very Popular for Various Reasons • One of the early programming languages. • Still the best programming language to learn quickly. • C language is reliable, simple and easy to use. • C language is a structured language. • Modern programming concepts are based on C. • It can be compiled on a variety of computer platforms. • Universities preferred to add C programming in their courseware.
Features of C Programming Language • C is a robust language with rich set of built-in functions and operators. • Programs written in C are efficient and fast. • C is highly portable, programs once written in C can be run on another machines with minor or no modification. • C is basically a collection of C library functions; we can also create our own function and add it to the C library. • C is easily extensible.
Advantages of C • C is the building block for many other programming languages. • Programs written in C are highly portable. • Several standard functions are there (like in-built) that can be used to develop programs. • C programs are basically collections of C library functions, and it’s also easy to add own functions in to the C library. • The modular structure makes code debugging, maintenance and testing easier. Disadvantages of C • C does not provide Object Oriented Programming (OOP) concepts. • There is no concept of Namespace in C. • C does not provide binding or wrapping up of data in a single unit. • C does not provide Constructor and Destructor.
1. Documentation Section - This is a comment block, which is ignored by the compiler. Comment can used anywhere in program to add info about program or code block, which will be helpful for developers to easily understand the existing code in the future. e.g. /* */, //2. Link Section -This Section is the core part of the program in which compiler links the inbuilt function from the system library. e.g. # include < >3. Definition Section -In this part, we define a symbolic constant. e.g. define PI = 3.144. Global Declaration -When programmer wants to use some variables that are used in more than one function. The global declaration section is used to define those variables that are used globally within the entire program and is used in more than one function.
5. Main( ) -The main() is the main function where program execution begins. Every C program must contain only one main function. This section contains two parts. -These two parts are declared within the opening and closing curly braces of the main(). The execution of program begins at the opening brace ‘{‘ and ends with the closing brace ‘}’. -Also it has to be noted that all the statements of these two parts needs to be terminated with semi-colon. Declaration parts in which all variables and user defined functions are declared. Execution part in which program logic and other process is done.Two curly brackets “{…}” are used to group all statements together Or shows how much the main() function has its scope. 6. Subprogram Section -The sub-program section deals with all user defined functions that are called from the main(). These user defined functions are declared and defined usually after the main() function.
Compile & Run the first C program #include <stdio.h> void main () { printf ("Programming is fun.\n"); } Note: to display multi line output printf ("Testing...\n..1\n...2\n....3\n");
#include<stdio.h> #include<conio.h> void main() { int sum; clrscr(); sum = 50 + 25; printf ("The sum of 50 and 25 is %i\n", sum); getch(); }
C Tokens • The smallest element in the C language is the token. • It may be a single character or a sequence of characters. C Tokens Identifiers Eg:main, avg Keywords Eg: int, for Constants Eg:17, 15.5 Strings Eg: “ab” operators Eg: + - spI symbol Eg: # $ %
Identifiers • Identifiers are names given to various program elements such as variables, functions and arrays etc,. • Eg: #define N 10 #define a 15 intxval; void sum_of_num( )
The rules for forming identifier • First character must be alphabetic or underscore. • Must consist only of alphabetic characters, digits, or underscores. • Only the first 31 characters of an identifier are significant and are recognized by the compiler. • Cannot use a keywords or reserved word (e.g. main, include, printf & scanf etc.). • No space are allowed between the identifiers etc,. • C is case sensitive, e.g. My_name my_name.
Working with Variables • Assign symbolic names for storing program computations and results in memory known as variable names. • A variable name can be chosen by you. • The C language allows storing different types of data into the variables & proper declaration for the variable is made beforeit is used in the program. • Variables can be used to store floating-point numbers, characters, and even pointers to memory locations.
Suggestions on choosing variable name • Pick names that reflect the intended use of the variable (i.e. type of value or purpose). The reasons are obvious. • Just as with the comment statement, meaningful variable names can dramatically increase the readability of a program and pay off in the debug and documentation phases. • In fact, the documentation task is greatly reduced because the program is more self-explanatory.
Keywords auto register continue double typedef for int char signed struct extern void break return default else union goto long const sizeof switch float do case short if enum unsigned static while
Constants • Any number, single character, or character string is known as a constant. • For example, the number 58 represents a constant integer value. • The character string "Programming in C" is an example of a constant character string. • C constant is just the written version of a number. For example 1, 0, 5.73, 12.5e9. We can specify our constants in octal or hexadecimal, or force them to be treated as long integers.
Constants Constants Numeric Constants Character Constants Integer Constant Real Constant Single Character Constant String Constant
Numeric constants Integer constants • It is formed using a sequence of digits. • Decimal - 0 to 9, • Octal - 0 to 7. • Hexa - 0 to 9, A to F Real constants • It is formed using a sequence of digits but it contain decimal point. • length, height, price distance measured in real number Eg: 2.5, 5.11, etc.
Rules for defining Integer Constant • It must have atleast one digit. • Decimal point are not allowed. • No blank space or commas are allowed. • It can be either positive or negative. • Octal constants are written with a leading zero - 015. • Hexadecimal constants are written with a leading 0x - 0x1ae. • Long constants are written with a trailing L - 890L.
Character constants Single character constant • A character constant is a single character they also represented with single digit or a single special symbol which is enclosed in single quotes. • Eg: ‘a’, ‘8’,’_’etc. String constants • String constant are sequence of characters enclosed with in double quote. • Eg: “Hello” ,”444”,”a” etc,.
Character constants are written with in single quotes 'a', 'b', 'c'. • String constants are written with in double quotes “hello” • Character constants are rarely used, since string constants are more convenient. • A string constant is surrounded by double quotes e.g. "Brian and Dennis". The string is actually stored as an array of characters. The null character '\0' is automatically placed at the end of such a string to act as a string terminator. • Constant is a special types of variable which cannot be changed at the time of execution. Syntax: const int a=20;
Data Type • The C programming language provides five basic data types: int, float, double, char, and _Bool. • A variable declared to be of type int can be used to contain integral values only—that is, values that do not contain decimal places. • A variable declared to be of type float can be used for storing floating-point numbers (values containing decimal places). • The double type is the same as type float, only with roughly twice the precision. • The char data type can be used to store a single character, such as the letter a, the digit character 6, or a semicolon etc. • Finally, the _Bool data type can be used to store just the values 0 or 1. Variables of this type are used for indicating an on/off, yes/no, or true/false situation.
Variable Storage Sizes and Ranges • The amount of storage that is allocated to store a particular type of data. • It is not defined in the language. It is machine-dependent. • You should never write programs that make any assumptions about the size of your data types. • Guaranteed that a minimum amount of storage will be set aside for each basic data type.
Octal & Hexadecimal notation • To express the octal constant 0177 represents the decimal value 127 (1 × 64 + 7 × 8 + 7) leading 0 used. • An integer can be displayed in octal notation by using format characters %o, the value is displayed in octal without a leading zero. • The format characters %#o does cause a leading zero to be displayed before an octal value. • Hexa representation Eg: intrgbColor = 0xFFEF0D; • The format characters %x display a value in hexadecimal format without the leading 0x, and using lowercase letters a–f for hexadecimal digits. • To display the value with the leading 0x, you use the format characters %#x
The Floating Number Type float • Floating-point constants can also be expressed in scientific notation. The value 1.7e4 is represents the value 1.7 × 104. • The value before the letter e is known as the mantissa, whereas the value that follows is called the exponent. Letter e can be written in either lowercase or uppercase. • In the constant 2.25e–3, the 2.25 is the value of the mantissa and –3 is the value of the exponent. • This constant represents the value 2.25 × 10–3, or 0.00225.