Basics of C Programming UNITI Basic Terminologies Computers

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 1. First, divide the number by two. 2. If the remainder of the division is zero, the number is even; 3. 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 (FORmula TRANslation) 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 1. Write Source Program using Text Editor • The program that is to be compiled is first typed into a file on 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 program because 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 bugs from 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, Code. Warrior and Xcode are 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 that code 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) o Object-oriented which groups instructions together with the part of the state they operate on. o 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. – Logic in 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 objectoriented 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 My. SQL 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. 14 4. 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. . 1n. . . 2n. . 3n");

#include<stdio. h> #include<conio. h> void main() { int sum; clrscr(); sum = 50 + 25; printf ("The sum of 50 and 25 is %in", 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 Keywords Constants Strings operators Eg: main, avg Eg: int, for Eg: 17, 15. 5 Eg: “ab” Eg: + - sp. I 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 int xval; void sum_of_num( )

The rules 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 before it 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 selfexplanatory.

List of valid variable names Sum sum piece. Flag i J 5 x 7 Number_of_moves _sysflag List of not valid variable names with reason sum$value $ is not a valid character. piece flag Embedded spaces are not permitted. 3 Spencer Variable cannot start with a number int is a reserved word/name.

Keywords auto double int struct break else long switch case enum static register typedef char extern return union const float short unsigned while continue for signed void default goto sizeof do if

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. 5 e 9. We can specify our constants in octal or hexadecimal, or force them to be treated as long integers.

Constants Numeric Constants Integer Constant Real Constant Character Constants 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 0 x - 0 x 1 ae. • Long constants are written with a trailing L - 890 L.

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 '