Sunteți pe pagina 1din 60

Session 01

Introduction to C
Session Speaker

Tharani Anandan

M.S.Ramaiah School of Advanced Studies

Session Objectives
To learn about the basics of programming language. To learn about procedural oriented programming language. To learn the basic elements of C language. To learn about algorithm, flowcharts and data types and in C Language.

M.S.Ramaiah School of Advanced Studies

Session Topics
Introduction to C Characteristics of C Usage of C Why learn C? C program Structure General Structure of a C program General programming Rules Algorithms & flowcharts Constants, Variables & Data types

M.S.Ramaiah School of Advanced Studies

Introduction to C
C is a general purpose computing programming language.

It was invented and was first implemented by Dennis Ritchie with the Unix Operating System in 1972.
C is often called a middle level computer language. C is a Structured Language. Strengths of C its flexible & portable, it can produce fast, compact code, international standard, ANSI C .
M.S.Ramaiah School of Advanced Studies

Dennis Ritchie

Characteristics of C
Portability : C programs can be written in such a way that the

programs can be easily transferred from one C compiler to another.


Structured programming language : It make use of

subroutines by making us of temporary variables.


Availability : Its available on more machines then any other programming language.

M.S.Ramaiah School of Advanced Studies

Contd..
Efficiency : It could mean in any of the following, ability to produce programs which run quickly production of small executable programs being able to write a given algorithm in fewer program statements

Size of Executable File : The calling mechanism that C uses for functions produces smaller and less complex machine code than the Pascal or Fortran system does. Many C operators translate to single machine instructions. C programs are often smaller than Pascal or Fortran equivalents.
M.S.Ramaiah School of Advanced Studies

Contd..
Various application : Wide usage in all upcoming fields. Speed : C programs were faster than equivalent Fortran programs. Size of Source Code : C has many tricks & short-cuts which allow the programmer to write in a couple of lines something that would require 10 or more lines of Pascal.

M.S.Ramaiah School of Advanced Studies

C & Operating System


The first C compiler was written for the Unix operating system. All versions of Unix since the development of C have been written in C. Most versions of MS-DOS have been written in C. Numerous other operating systems and environments have been developed in C, even if parts are later converted to assembler.

M.S.Ramaiah School of Advanced Studies

Contd..
Programmers writing systems programs in C have the entire computer under their control. There is not even one part of the computer memory they cannot access. All the bit manipulation routines are available.

M.S.Ramaiah School of Advanced Studies

Usage of C
C's primary use is for system programming, including implementing operating systems and embedded system applications. C has also been widely used to implement end-user applications, although as applications became larger much of that development shifted to other, higher-level languages. One consequence of C's wide acceptance and efficiency is that the compilers, libraries, and interpreters of other higherlevel languages are often implemented in C. You will be able to read and write code for a large number of platforms even microcontrollers.
M.S.Ramaiah School of Advanced Studies

Why Learn C?
Compact, fast, and powerful Mid-levelLanguage Standard for program development (wide acceptance) It is everywhere! (portable) Supports modular programming style Useful for allapplications C is the native language of UNIX Easy to interface with system devices/assembly routines
M.S.Ramaiah School of Advanced Studies

C Program Structure
The following program is written in the C programming language
#include <stdio.h> main() { /* My first program */ printf("Hello World! \n"); }

C is case sensitive. All commands in C must be lowercase. C has a free-form line structure. End of each statement must be marked with a semicolon.
M.S.Ramaiah School of Advanced Studies

Contd..
Multiple statements can be on the same line. White spaceis ignored. Statements can continue over many lines.
#include <stdio.h> main() { /* My first program */ printf("Hello World! \n"); }

The C program starting point is identified by the word main().

This informs the computer as to where the program actually starts. The parentheses that follow the keyword main indicate that there are no arguments supplied to this program (this will be examined later on).
M.S.Ramaiah School of Advanced Studies

Contd..
The two braces, { and }, signify the begin and end segments of the program. In general, braces are used throughout C to enclose a block of statements to be treated as a unit. COMMON ERROR: unbalanced number of open and close curly brackets!
#include <stdio.h> main() { /* My first program */ printf("Hello World! \n"); }

The purpose of the statement #include <stdio.h>is to allow the use of the printf statement to provide program output. For each function built into the language, an associated header file must be included.
M.S.Ramaiah School of Advanced Studies

Contd..
Text to be displayed by printf()must be enclosed in double quotes. The program only has the one only has the one printf() statement. printf() is actually a function (procedure) in C that is used for printing variables values and text. Where text appears in double quotes "", it is printed without modification. There are some exceptions however. This has to do with the \ and % characters. These characters are modifiers, and in this code the \ followed by the n character represents a new line character
M.S.Ramaiah School of Advanced Studies

Contd..
Compilation using gcc
1. 2. Use the command mkdir to create a new directory. Use the text editor vi followed by the name of the file. Ex: vi sample.c Use the insert mode to type the text. Use the Insert key or I. Save the file using :wq. The file is now saved. Compile using gcc followed by the name of the file. Ex: gcc sample.c View the output using a.out file. Type ./a.out.
M.S.Ramaiah School of Advanced Studies

3.
4. 5. 6.

Contd..
First Program Output & Comments
Thus the program prints Hello World! And the cursor is set to the beginning of the next line. As we shall see later on, the letter that follows the \ character will determine what special printing action is taken (i.e., a tab, backspace, clear line, etc.) /* My first program */ Comments can be inserted into C programs by bracketing text with the /* and */ delimiters. As will be discussed later, comments are useful for a variety of reasons. Primarily they serve as internal documentation for program structure and functionality.
M.S.Ramaiah School of Advanced Studies

Contd..
Header Files
Header files contain declarations of functions and variables which can be incorporated into any C program by using the pre-processor #include statement. Standard header files are provided with each compiler, and cover a range of areas: string handling, mathematics, data conversion, printing and reading of variables, etc. To use any of the standard functions, the appropriate header file should be included. This is done at the beginning of the C source file. For example, to use the function printf() in a program. #include <stdio.h>
M.S.Ramaiah School of Advanced Studies

Contd..
the line should be at the beginning of the source file, because the declaration for printf()is found in the file stdio.h. All header files have the extension .hand generally reside in the /usr/include subdirectory. Some examples: #include <string.h> #include <math.h> #include "mylib.h The use of angle brackets <>informs the compiler to search the compilers include directories for the specified file. The use of the double quotes""around the filename informs the compiler to start the search in the current directory for the specified file.
M.S.Ramaiah School of Advanced Studies

Contd..
The use of angle brackets <> informs the compiler to search the compilers include directories for the specified file. The use of the double quotes""around the filename informs the compiler to start the search in the current directory for the specified file. Comments The addition of comments inside programs is desirable. These maybe added to C programs by enclosing them as follows, /* Computational Kernel: In this section of code we implement the TSP algorithm for the numerical solution of the differential Einstein Equations. */

M.S.Ramaiah School of Advanced Studies

Contd..
Note that the /*opens the comment field and the */closes the comment field. Comments may span multiple lines. Comments may not be nested one inside the another.

/* this is a comment. /* this comment is inside */ wrong */


In the above example, the first occurrence of */closes the comment statement for the entire line, meaning that the text wrong is interpreted as a C statement or variable, and in this example, generates an error.
M.S.Ramaiah School of Advanced Studies

General Structure of a C Program


Opening comment block Should always contain authors name, name of the file, and purpose of the program Preprocessor directives include all header files for needed libraries define any useful constants Function prototypes Must be declared before the function is called Main function Program execution begins at the start of main() and ends when it reaches the end of main() Any additional functions called main are ignored. Other function definitions
M.S.Ramaiah School of Advanced Studies

Internal Structure of a C Program


A C source program is a collection of one or more directives, declarations, and statements contained in one or more source files. Statements: Specify the action to be performed. Directives: Instruct the preprocessor to act on the text of the program. Declarations: Establish names and define linkage characteristics such as scope, data type, and linkage. Definitions: Are declarations that allocate storage for data objects or define a body for functions. An object definition allocates storage and may optionally initialize the object.
M.S.Ramaiah School of Advanced Studies

A Typical C Program Development Environment


Phases of C Programs:
Editor Preprocessor Compiler Linker

Disk
Disk Disk Disk Primary Memory

1. Program is created in the editor and stored on disk 2. Preprocessor program processes the code 3. Compiler creates object code and stores it on disk. 4. Linker links the object code with the libraries

Edit

Preprocess
Compile Link Load Execute

Loader

5. Loader puts program in memory.

Disk Primary Memory CPU

6. CPU takes each instruction and executes it, possibly storing new data values as the program executes

M.S.Ramaiah School of Advanced Studies

4 Steps to Develop an C Program

M.S.Ramaiah School of Advanced Studies

4 Steps to Develop an C Program


Word processor: (Editor) Used to type in program and corrections Source file Format : Text

Compiler: Accepts to translate program into machine code Unsuccessful Error message Other Object file Format : Binary

Successful

Object file Format : Binary

Linker: Restores cross-references among object files Executable file (Load module) Format : Binary

Input data

Results

Loader: Copies executable file into memory; initiate execution of instructions

M.S.Ramaiah School of Advanced Studies

Terms and Terminologies


Source code: The text of a program that a user can read, commonly thought of as the program. Object code: Translation of the source code of a program into machine code , while the computer can read and execute directly. Linker: A program that links separately compiled modules into one program. The output of the linker is an executable program.

M.S.Ramaiah School of Advanced Studies

Contd..
Library : The file containing the standard functions that your program can use. These functions include all I/O operations as well as other useful routines. Compile time: The time during which the program is being compiled Run time : The time during which the program is executing

M.S.Ramaiah School of Advanced Studies

General Programming Rules


All C Statements are free-form

Can begin and end on any line and in any column


C statements are always terminated with a semicolon ;. Blank lines are ignored White space (blanks, tabs and new lines) must separate keywords from other things

M.S.Ramaiah School of Advanced Studies

Contd..
Comments
All text enclosed within /* ----- */ Text on the same line following //

Examples:
// This is a comment /* So is this. */
M.S.Ramaiah School of Advanced Studies

ALGORITHM & FLOWCHARTS


A sequence of activities to be processed for getting desired

output from a given input.


Then we can say that: Getting specified output is essential after algorithm is

executed.
One will get output only if algorithm stops after finite time. Activities in an algorithm to be clearly defined in other words for it to be unambiguous.

M.S.Ramaiah School of Advanced Studies

Contd..

Symbols used while writing an algorithm : + for Addition - for Subtraction * for Multiplication / for Division and for assignment. For example A value of X*3.

X*3 means A will have a

M.S.Ramaiah School of Advanced Studies

Contd..
Example : Write an algorithm to determine a students final grade and indicate whether it is pass or fail. The final grade is calculated as the average of four marks. Input a set of 4 marks Calculate their average by summing and dividing by 4 if average is below 50 Print FAIL else Print PASS

M.S.Ramaiah School of Advanced Studies

Contd..
Detailed Algorithm : Step 1: Input M1,M2,M3,M4 Step 2: GRADE (M1+M2+M3+M4)/4 Step 3: if (GRADE < 50) then Print FAIL else Print PASS Step 4: Stop

M.S.Ramaiah School of Advanced Studies

Contd..
Properties of algorithm : Finiteness: An algorithm must always terminate after a finite number of steps. Definiteness: Each step of an algorithm must be precisely defined. Input: Any operation you perform need some beginning value/quantities associated with different activities in the operation. Output: One always expects output/result in terms of output from an algorithm. Effectiveness: Algorithms to be developed/written using basic operations.
M.S.Ramaiah School of Advanced Studies

Contd..
FLOWCHART : The flowchart is a diagram which visually presents the flow of data through processing systems. This means by seeing a flow chart one can know the operations performed and the sequence of these operations in a system. A flowchart is a diagrammatic representation of algorithm. Flowcharts are used as a link of communication between programmers and clients for whom the program to be developed

M.S.Ramaiah School of Advanced Studies

Contd..
Name Symbol Use in Flowchart

Oval

Denotes the beginning or end of the program

Parallelogram

Denotes an input operation

Rectangle

Denotes a process to be carried out e.g. addition, subtraction, division etc.

Diamond

Denotes a decision (or branch) to be made. The program should continue along one of two routes. (e.g. IF/THEN/ELSE)

Hybrid

Denotes an output operation

Flow line

Denotes the direction of logic flow in the program

M.S.Ramaiah School of Advanced Studies

Contd..
START Input M1,M2,M3,M4

GRADE(M1+M2+M3+M4)/4

Step 1: Input M1,M2,M3,M4 Step 2: GRADE (M1+M2+M3+M4)/4 Step 3: if (GRADE <50) then Print FAIL else Print PASS Step 4: Stop
Y

IS GRADE<50

Print Pass

Print Fail

STOP
M.S.Ramaiah School of Advanced Studies

Contd..
Limitations of using Flowcharts :

Complexity of Logic: If program logic is complex then flowchart of the program becomes complicated.
Alterations and Modifications in Logic: any alterations in the program logic may require redrawing of flowchart completely. Reuse is Not Possible: As the flowchart symbols cannot be typed, always reproduction of flowchart symbols are required.

M.S.Ramaiah School of Advanced Studies

Constants, Variables & Data types


Constants : Are fixed values. They does not change during the execution of a program. They are broadly classified as shown below.,
Constants

Numeric Constants

Character Constants

String Constants

Integer
Decimal Octal

Real
Hexadecimal
M.S.Ramaiah School of Advanced Studies

Contd..
Integer Constants : Its an whole number without any decimal point. No extra character are allowed other than + and sign.(they should be precede the number). Decimal (Ex: 10,140,-140 etc) Octal (Ex: 010,0140,-0140 etc) Hexadecimal (Ex: 0x8A,0XAB etc)

Integer Constants

Real Constants : Numeric quantities having fractional part are called real(Floating point)constants.
M.S.Ramaiah School of Advanced Studies

Contd..
Character Constants : A character enclosed within a single quotes(apostrophe denoted by ). It is associated with an unique value called ASCII(American Standard Code of Information Interchange) value. Examples 9 , a , $ , \n , \t Backslash constants : Also known as Escape sequence character. It begins with a backslash and is followed by one character. They are represented by single character even though they are combination of two character.

M.S.Ramaiah School of Advanced Studies

Contd..
Commonly used Escape Sequence Character
Character Bell Backspace Escape Sequence \a \b Meaning Beep sound Cursor moves towards left by one position

Horizontal tab
New line Form feed Carriage return Backslash Null

\t
\n \f \r \\ \0
M.S.Ramaiah School of Advanced Studies

Cursor moves towards right by 8 position


Cursor moves to the next line Cursor moves to the next page Cursor moves to the start of current line \ null character

Contd..
String Constants : Sequences of character(i.e., one or more characters) enclosed within double quotes. Strings always ends with an Null character (\0). Examples 9 , Raj , \n. Character Set(Alphabets of C) : It is a collection of symbols called alphabets. Using these alphabets meaningful members, expressions & statements can be framed.
M.S.Ramaiah School of Advanced Studies

Contd..
Characters in C language are shown below: Letters: Upper case letters from A to Z and lower case letters from a to z. Digits: from 0 to 9. White spaces: Characters such as space, tab(\t),new line(\n). Symbols: such as ~ , ^ , - , + , / , * , ; , : , # , ( , ) , { , } , < , > , % , = , etc

M.S.Ramaiah School of Advanced Studies

Contd..
C Tokens : Is a small or basic unit of any program.
There are several rules that you must follow when naming constants and variables: Names... CANNOT start with a number CAN contain a number elsewhere CANNOT contain any arithmetic operators... CANNOT contain any other punctuation marks... CAN contain or begin with an underscore CANNOT be a C keyword CANNOT contain a space CAN be of mixed cases
M.S.Ramaiah School of Advanced Studies

Example 2i h2o r*s+t #@x%!!a _height_ struct im stupid XSquared

Contd..
Keywords used in C :
Basic building block Lowercase Fixed meaning, cannot be changed

auto break

double else

int long

struct switch

case char const continue default do

enum extern float for goto if

register return short signed sizeof static

typedef union unsigned void volatile while

M.S.Ramaiah School of Advanced Studies

Contd..
Identifiers :

An identifier is a series of characters consisting of letters, digits and underscores _ that does not begin with a digit
Can be any length but only the first 31 characters are required to be recognized by ANSI C compilers Keep identifiers 31 characters or less for portability and fewer problems

M.S.Ramaiah School of Advanced Studies

Contd..
How to Declare an Variables ?
A variable is a named memory location in which data of a certain type can be stored. The contents of a variable can change, thus the name. User defined variables must be declared before they can be used in a program. It is during the declaration phase that the actual memory for the variable is reserved, a process called static memory allocation. All variables in C must be declared before use. It is common to adopt the habit of declaring variables using lowercase characters.
M.S.Ramaiah School of Advanced Studies

Contd..
Remember that C is case sensitive, so even though the two variables listed below have the same name, they are considered different variables in C. sum Sum

The declaration of variables is done after the opening brace of main(). main() { int sum; It is possible to declare variables elsewhere in a program, but lets start simply and then get into variations later on.
M.S.Ramaiah School of Advanced Studies

Contd..
The basic format for declaring variables is data_type var, var, ; where data_typeis one of the four basic types, an integer, character, float or double type. Examples are int i,j,k; float length,height; char midinit;

M.S.Ramaiah School of Advanced Studies

Contd..
Data types : Type of the data that a variable can store is called data type.
C Data Types

Primitive/Basic data types Integer Characters Floating points Long floats

Derived Data types Array

User defined Data types

Function pointer

Structures unions

M.S.Ramaiah School of Advanced Studies

Contd..
Basic data type that are supported by C are:
Integer data types denoted by the keyword int Character data types denoted by the keyword char Real or floating point data types denoted by the keyword float Double precision floating point number denoted by the keyword double.
Type char or signed char unsigned char int or signed int unsigned int short int or signed short int unsigned short int long int or signed long int unsigned long int Size (bits) 8 8 16 16 8 8 32 32 Range -128 to 127 0 to 255 -32768 to 32767 0 to 65535 -128 to 127 0 to 255 -2147483648 to +2147483647 0 to 4294967295

float
double long double

32
64 80
M.S.Ramaiah School of Advanced Studies

3.4 E 38 to 3.4 E + 38
1.7 E 308 to 1.7 E + 308 3.4 E 4832 to 1.1 E +4932

Contd..
Basic Data Types: INTEGER These are whole numbers, both positive and negative. Unsigned integers(positive values only) are also supported. In addition, there are short and long integers. The keyword used to define integers is int An example of an integer value is 32. An example of declaring an integer variable called age is int age;
M.S.Ramaiah School of Advanced Studies

Contd..
Basic Data Types: FLOAT
These are positive and negative REAL numbers which contain fractional parts. They can be written in either floating point notation or scientific notation. The keyword used to define float variables is float Typical floating point values are 1.73 and 1.932e5. An example of declaring a float variable called x is float x;

M.S.Ramaiah School of Advanced Studies

Contd..
Basic Data Types: CHARACTER

These are variables that contain only one character.


The keyword used to define character variables is char Typical character values might be the letter A, the character 5,the symbol , etc. An example of declaring a character variable called letter is char letter;
M.S.Ramaiah School of Advanced Studies

Contd..
Basic Data Types: DOUBLE

These are floating point numbers, both positive and negative, which have a higher precision than float variables.
The keyword used to define double variables is double An example of declaring a double variable called voltage is double voltage;
M.S.Ramaiah School of Advanced Studies

Test your basic knowledge


Which is a valid Hello World program?
#include<stdio.c> int main(){ printf(Hello World); return 0; } #include<stdio.h> int main(){ print(Hello World); return 0; }

#include<stdio.h> int main() printf(Hello World); return 0; }

#include<stdio.h> int main(){ printf(Hello World); return 0; }

M.S.Ramaiah School of Advanced Studies

Session Summary
Introduction to procedural oriented programming languages and the advantages and capabilities of C language has been discussed. The significance of algorithms, flowcharts, variables, constants and data types are also been discussed.

M.S.Ramaiah School of Advanced Studies

Thank You!

M.S.Ramaiah School of Advanced Studies

S-ar putea să vă placă și