UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Similar documents
Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Data Types and Variables in C language

C: How to Program. Week /Mar/05

ANSI C Programming Simple Programs

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Chapter 2 - Introduction to C Programming

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

DECLARATIONS. Character Set, Keywords, Identifiers, Constants, Variables. Designed by Parul Khurana, LIECA.

C - Basic Introduction

2/29/2016. Definition: Computer Program. A simple model of the computer. Example: Computer Program. Data types, variables, constants

Data types, variables, constants

Basic Elements of C. Staff Incharge: S.Sasirekha

UNIT IV 2 MARKS. ( Word to PDF Converter - Unregistered ) FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING

Basics of Programming

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Programming in C and Data Structures [15PCD13/23] 1. PROGRAMMING IN C AND DATA STRUCTURES [As per Choice Based Credit System (CBCS) scheme]

Full file at C How to Program, 6/e Multiple Choice Test Bank

Presented By : Gaurav Juneja

Programming and Data Structures

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

LESSON 4. The DATA TYPE char

Fundamentals of Programming Session 4

Chapter 1 & 2 Introduction to C Language

Programming Fundamentals (CS 302 ) Dr. Ihsan Ullah. Lecturer Department of Computer Science & IT University of Balochistan

INTRODUCTION 1 AND REVIEW

UNIT- 3 Introduction to C++

Chapter 2. Lexical Elements & Operators

VARIABLES AND CONSTANTS

Lecture 2 Tao Wang 1

Programming for Engineers Introduction to C

Computers Programming Course 5. Iulian Năstac

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

DEPARTMENT OF MATHS, MJ COLLEGE

Number Systems, Scalar Types, and Input and Output

Operators and Expressions:

Differentiate Between Keywords and Identifiers

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

Introduction to C Language

Programming. C++ Basics

UNIT 3 OPERATORS. [Marks- 12]

CHAPTER-6 GETTING STARTED WITH C++

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

PART I. Part II Answer to all the questions 1. What is meant by a token? Name the token available in C++.

CSc Introduction to Computing


CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

A Fast Review of C Essentials Part I

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

.. Cal Poly CPE 101: Fundamentals of Computer Science I Alexander Dekhtyar..

The C++ Language. Arizona State University 1

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

COMPUTER SCIENCE HIGHER SECONDARY FIRST YEAR. VOLUME II - CHAPTER 10 PROBLEM SOLVING TECHNIQUES AND C PROGRAMMING 1,2,3 & 5 MARKS

C Language, Token, Keywords, Constant, variable

Unit 1: Introduction to C Language. Saurabh Khatri Lecturer Department of Computer Technology VIT, Pune

These are reserved words of the C language. For example int, float, if, else, for, while etc.

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Work relative to other classes

PES INSTITUTE OF TECHNOLOGY (BSC) I MCA, First IA Test, November 2015 Programming Using C (13MCA11) Solution Set Faculty: Jeny Jijo

Fundamental of Programming (C)

SEQUENTIAL STRUCTURE. Erkut ERDEM Hacettepe University October 2010

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Course Outline Introduction to C-Programming

6.096 Introduction to C++ January (IAP) 2009

Guide for The C Programming Language Chapter 1. Q1. Explain the structure of a C program Answer: Structure of the C program is shown below:

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

BITG 1233: Introduction to C++

Introduction to C# Applications

Unit 4. Input/Output Functions

Intro to Computer Programming (ICP) Rab Nawaz Jadoon

Programming in C++ 4. The lexical basis of C++

Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur

THE FUNDAMENTAL DATA TYPES

2 nd Week Lecture Notes

Reserved Words and Identifiers

>B<82. 2Soft ware. C Language manual. Copyright COSMIC Software 1999, 2001 All rights reserved.

BLM2031 Structured Programming. Zeyneb KURT

P.E.S. INSTITUTE OF TECHNOLOGY BANGALORE SOUTH CAMPUS 1 ST INTERNAL ASSESMENT TEST (SCEME AND SOLUTIONS)

Multiple Choice Questions ( 1 mark)

C-LANGUAGE CURRICULAM

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

CSC 1107: Structured Programming

COMPONENTS OF A COMPUTER

JAVA Programming Fundamentals

C Fundamentals & Formatted Input/Output. adopted from KNK C Programming : A Modern Approach

Introduction to C programming. By Avani M. Sakhapara Asst Professor, IT Dept, KJSCE

Unit 3. Operators. School of Science and Technology INTRODUCTION

Unit-II Programming and Problem Solving (BE1/4 CSE-2)

1. History of C. 2. Characteristics of C. 3. Basic structure of C programs INTRODUCTION TO C

ME 172. Sourav Saha. Md. Mahamudul Hossain Kazi Fazle Rabbi Saddam Hossain Joy Kamruzzaman Lecturer,Dept. of ME,BUET

Basics of Java Programming

Lecture 02 C FUNDAMENTALS

Computer Programming : C++

Department of Computer Applications

IECD Institute for Entrepreneurship and Career Development Bharathidasan University, Tiruchirappalli 23.


The component base of C language. Nguyễn Dũng Faculty of IT Hue College of Science

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

Variables in C. Variables in C. What Are Variables in C? CMSC 104, Fall 2012 John Y. Park

Fundamentals of Programming

Transcription:

UNIT - I Introduction to C Programming

Introduction to C C was originally developed in the year 1970s by Dennis Ritchie at Bell Laboratories, Inc. C is a general-purpose programming language. It has been closely associated with the UNIX operating system where it was developed, since both the system and most of the programs that run on it are written in C.

Introduction to C It is a language with features economy of expression, modern flow control and data structures, and a rich set of operators. The language, however, is not tied to any one operating system or machine; and although it has been called a ``system programming language'' because it is useful for writing compilers and operating systems.

Introduction to C C provides the fundamental control-flow constructions required for well-structured programs: statement grouping, decision making (if-else), selecting one of a set of possible values (switch), looping with the termination test at the top (while, for) or at the bottom (do), and early loop exit (break).

Simple structure of a C program Inclusion of header files Inclusion of main( ) function Declaration Part i.e. Declaration of variables with corresponding Data types. Set of instructions using C syntax. End of Program statement

Simple Program /* Comment statements */ /* The Hello World program */ Preprocessor directives main() { Program statements; } # include <stdio.h> main() { printf( Hello World\n ); }

Sample C program # include<stdio.h> main( ) { int a, b, c, sum; a = 1; b = 2; c = 3; sum = a + b + c; printf("sum is %d", sum); }

Formal Structure of C Documentation section Link section Definition section Global declaration Main( ) Function section { Declaration Part, Executable Part } Subprogram section Function 1 Function 2 (User defined Function) Function n

The documentation section consists of a set of comment lines giving the name of the program, the author and other details. The link section provides instruction to the compiler to link function from the system library. The definition section defines all symbolic constants. There are some variables that are used in more than one function. Such variables are called global variables. Main() function two parts, declaration and executable part. The Declaration part declares all the variables used in executable part.

The program execution begins at the opening brace and ends at the closing braces. The closing braces of the main() function section is the logical end of the program. The subprogram section contains all the userdefined functions that are called in the main() function. User-defined functions are generally placed immediately after the main() function.

Executing a C program 1. Creating the program. 2. Compiling the program. 3. Linking the program with function that are needed from the C library. 4. Executing the program.

Points to remember 1. Every C program requires a main() function (use of more than one main() is illegal). 2. The execution of a function begins at the opening brace of the function and ends at the corresponding close brace. 3. C programs are written in lowercase letters. However, uppercase letters are used for symbolic names and output strings. 4. Al the programming words must be separated by at least one space. 5. Every program statement in a C program must end with a Semicolon(;)

The C character Set C uses uppercase letters A to Z, the lowercase letters a to z, the digits 0 to 9, and certain special characters as building blocks to form basic program. The special characters are listed below. + - * / = % & #!? ^ ~ \ < > ( ) [ ] { } : ;., _ $

The C character Set C uses certain combinations of these characters, such as \b, \n, and \t, to represent special conditions such as backspace, newline, and horizontal tab, respectively. These character combinations are known as escape sequences.

Identifiers and Keywords Identifiers are names that are given to various program elements, such as variables, functions and arrays. Identifiers consists of letters and digits, in any order, except that the first character must be a letter. Both upper and lower case letters are permitted. The underscore character ( _) can also be included, and is considered to be a letter.

Valid identifiers X y12 sum_1 _temperature Name area tax_rate TABLE Invalid Identifiers 4 th the first character must be a letter x Illegal character ( ) Order-no Illegal character (-) Error flag Illegal character (blank space)

Keywords There are certain reserved words, called keywords, that have standard, predefined meaning in C. The keyword can be used only for their intended purpose. E.g. auto extern sizeof break static case for struct char goto switch if int double union Void do while else return

Data types C language is rich in its data types. The variety of data types available allow the programmer to select the type appropriate to the needs of the applications as well as the machine The fundamental data types, namely integer (int), character (char), floating point (float), and doubleprecision floating point (double)

Data types Type Size (bits) Range Char 8-128 to 127 Integer 16-32, 768 to 32, 767 Float 32 3.4E-38 to 3.4E+38 Double 64 1.7E-308 to 1.7E+308 Declaration of variables int count; Int number, total; Char s;

User-Defined data types C supports a feature known as type definition that allows users to define an identifier that would represent an existing data type. Format : typedef type identifier; Where type refers to an existing data type and identifier refers to the new name given to the data type.

typedef int units; typedef float marks; Here, units symbolizes int and marks symbolizes float. units batch1, batch2; marks name1[50], name2[50]; batch1 and batch2 are declared as int variable and name1[50] and name2[50] are declared as 50 element floating point array variables.

Constants Constants in C refers to fixed value that do not change during the execution of a program. Integer consist of a set of digits, 0 to 9, preceded by an optional or + sign. Valid constants are. 123-321 0 65432 +78

Invalid constants 15 750 20,000 $1000 Real constants These constants are represented by number containing fractional parts like 17.548 e.g. 0.083-0.75 435.45 +247.0

Character Constant A single character constant contains a single character enclosed within a pair of single quote marks. E.g. 5 X Note that the character constant 5 is not same as number 5. the last constant is blank space. Character constant have integer values known as ASCII values printf( %d, a ); ---------- > will print the number 97 printf( %c, 97 ); --------- > will print the letter a

String Constant A string constant is a sequence of characters enclosed in double quotes. The character may be letters, number, special characters and blank space. E.g. Hello 1987 X Remember that a character constant X is not equivalent to the single character constant X.

Backslash Character Constant constant Meaning \a Audible alert \b Back space \n New line \t Horizontal tab \v Vertical tab \0 Null \\ Backslash \ Single quote \ Double quote

VARIABLES A variable is a data name that may be used to store a data value. A variable may take different values at different times during execution. A variable name can be chosen by the programmer in a meaningful way. Valid: john Value T_raise sum1 mark Invalid: 123 (area)

First_tag char Price$ group one average_number int_type Variable Declaration Syntax: datatype v1,v2,.., vn; Variables are separated by commas, and declaration statement must end with a semicolon. E.g. int count; int number, total;

ARRAYS A array is a kind of variable that is used extensively in C. An array is an identifier that refers to a collection of data items that all have the same name. The data items must all be of the same type (e.g. all integers, all characters). The individual data item are represented by their corresponding array element. E.g. int a[10]; a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]

ARRAYS E.g. int a[5]; The values of array element can be assigned as follows. a[0]=35; a[1]=40; a[2]=20; a[3]=57; a[4]=19; This would cause the array a to store values as shown below. a[0] a[1] a[2] a[3] a[4] 35 40 20 57 19

ARRAYS The following are the valid statements : A = a[0] + 10; A[4] = a[0] + a[2]; Value[6] = a[3] * 6; E.g. float height[50]; Which declares the height to be an array containing 50 real elements. The C language treats character strings simply as array of characters. The size in a character string represents the maximum number of characters that a string can hold.

ARRAYS E.g. char name[10]; Declares the name as a character array variable that can hold a maximum of 10 characters. Suppose WELL DONE is a string that is stored in the memory as follows: We must always allow one extra element space for the null terminator. W E L L D O N E \0

Two-Dimensional Arrays Organized in the form of rows and columns E.g. int a[5][5]; a[0] a[1] a[2] a[3] a[4] a[5] a[0] a[1] a[2] a[3] a[4] a[5]

for (i=1;i<=5;i++) { for(j=1;j<=5;j++) { Scanf( %d, &a[ i ] [ j ]); } }

Operators and Expressions C operators can be classified into a number of categories. They include: 1. Arithmetic operators. 2. Relational operators. 3. Logical operators. 4. Assignment operators 5. Increment and decrement operators 6. Conditional operators.

1. Arithmetic operators C provides all the basic arithmetic operators as given below: operator Meaning + Addition - Subtraction * Multiplication / Division % Modulo division E.g. a+b; a-b; a*b; a/b; a%b;

2. Relational operators The comparison can be done by relational operator. The expression (a < b or 1 < 20) containing a relational operator is termed as a relational expression. If the relation is true it is one or the relation is false it is zero. operator Meaning < is less than > is greater than <= is less than or equal to >= is greater than or equal to == is equal to!= is not equal to

3. Logical operators C has he following three logical operators. operator Meaning && logical AND logical OR! Logical NOT The logical operators && and are used when we want to test more than one condition and make decision. E.g. (a > b && x ==10)

4. Assignment operator Assignment operators are used to assign the result of an expression to a variable. E.g. C=a+b; In addition, C has a set of shorthand assignment operators of the form: Stmt. with simple Stmt. with assgn. Operator shorthand operator a=a+1 a+=1 a=a-1 a-=1 a=a*(n+1) a*=n+1 Note: 1) what appears on the left-side need not be repeated and therefore easier to write 2) the statement is more efficient.

5. Increment and decrement operators C has two very useful operators not generally found in other languages. These are increment ( + + )and decrement operators ( - - ). The operator + + adds 1, while - - subtracts1. E.g. + + m; and m + +; mean the same thing when they form statements independently. They behave differently when they are used in the expressions on the right-hand side of an assignment statement. Consider the following.

5. Increment and decrement operators M = 5; Y= + + m; In this case, the value of y and m would be 6. suppose if we rewrite the above statement as M = 5; Y= m + +; Then, the value of y would be 5 and m would be 6.

5. Increment and decrement operators The unusual feature of `+ +' and `- -' is that they can be used either before or after a variable. The value of + + k is the value of k after it has been incremented. The value of k + + is k before it is incremented. E.g. Suppose k is 5. Then x = + + k; Increments k to 6 and then sets x to the resulting value, i.e., to 6. But x = k++; first sets x to 5, and then increments k to 6. The incrementing effect of ++k and k++ is the same, but their values are respectively 5 and 6.

6. Conditional operator A ternary operator pair? : is available in C to construct conditional expressions of the form: exp1? exp2 : exp3; Where exp1, exp2, exp3 are expressions. First exp1 is evaluated, if it is non zero (true) then the exp2 is evaluated and becomes the value of the expression. If exp1 is false, exp3 is evaluated and its value becomes the value of the expression. e.g. A=10; b=15; x=(a>b)? a : b; If (a>b) X=a; Else X=b; is same as

Arithmetic expressions An arithmetic expression is a combination of variables, constants, and operators arranged as per the syntax of the language. C language can handle complex mathematical expressions. algebraic expressions C expressions a x b c a * b c (m+n) (x+y) (m+n) * (x+y) ab c a * b / c 3x 2 + 2x + 1 3 * x * X + 2 * X + 1 x + c y x / y + c

Precedence of Arithmetic operator An arithmetic expression without parenthesis will be evaluated from left to right using the rules of precedence of operators. There are two distinct priority levels of arithmetic operators in C. High priority * / % Low priority + - During the first pass, the high priority operators are applied as they are encountered. During the second pass, the low priority operators are applied as they are encountered.

Library functions The C language is accompanied by a number library functions that carry out various commonly used operations or calculations. There are some library functions that carry out standard input / output operations (e.g. read and write characters, read and write numbers, open and close files, etc). Functions that perform operations on characters (e.g. convert from lower- to upper) functions that performs operations on strings (e.g. copy a string, compare a string, concatenate strings, etc). Library functions that are functionally similar are usually grouped together as (compiled) object program in separate library files. A typical set of library functions will include a fairly large number of functions that are common to most C compilers.

Library functions abs(i) - return the absolute value of i. ceil(d) - round up to the next integer value. cos(d) - return the cosine of d. log(d) - return the natural logarithm of d. printf(.) - send data items to the standard output device. scanf( ) - enter data items from the standard input device. tolower(c) - convert letter to lowercase. toupper(c) - convert letter to uppercase. getchar( ) - enter a character from a standard input device. putchar( ) - send a character to the standard output device. sqrt(d) - returns a square root of d.

Library functions A library function is accessed simply by writing the function name, followed by a list of arguments that represent information being passed to a function. The arguments must be enclosed in parentheses and separated by commas. The arguments can be constants, variable names, or more complex expressions

Data input and output SINGLE CHARACTER INPUT THE getchar( ) FUNCTION Single character can be entered into the computer using the C library function getchar( ). The getchar( ) function is a part of the standard C I/O library. It returns a single character from a standard input device (typically a keyboard). The function does not require any arguments, though a pair of empty parentheses must follow the word getchar( ). SYNTAX: character variable = getchar( ); E.g. char c; c = getchar( );

Data input and output SINGLE CHARACTER OUTPUT THE putchar( ) FUNCTION Single character can be displayed using C library function putchar(). It transmits a single character to a standard output device ( typically a monitor) It must be expressed as an argument to the function, enclosed in parentheses, following the word putchar( ). SYNTAX: putchar (character variable ); E.g. char c; putchar(c);

Entering input data The scanf Function Input data can be entered into the computer from a standard input device by means of the C library function scanf. This function can be used to enter any combination of numerical values, single characters and strings. The function returns the number of data items that have been entered successfully. syntax: scanf( control string, arg1, arg2,.... argn); Where control string refers to a string containing certain required formatting information, and arg1, arg2,... argn are arguments that represent the individual input data items. The control string consists of individual groups of characters with one character group for each input data item.

Entering input data The scanf Function Each character group must begin with a percent sign (%). Conversion character c d f h i o x s Data item is a single character Data item is a decimal integer Meaning Data item is a floating-point value Data item is a short integer Data item is a decimal, hexadecimal or octal integer Data item is an octal integer Data item is a hexadecimal integer Data item is a string (null \0 will automatically added at end)

Entering output data The printf function Output data can be written from the computer onto a standard output device using the C library function printf. This function can be used to output any numerical values, ingle character and strings. The printf function moves data from the computer s memory to the standard output device. syntax: printf( control string, arg1, arg2,.... argn);

Conversion character c d f i o x s Meaning Data item is displayed as single character Data item is displayed as decimal integer Data item is displayed as floating-point value Data item is displayed as signed decimal integer Data item is displayed as octal integer Data item is displayed as hexadecimal integer Data item is displayed as string

Assignment - 1 1. C datatypes 2. Variables and Arrays. Submission date: 04/10/2007

END OF UNIT - I