Data Types and Variables in C language

Similar documents
Basic Elements of C. Staff Incharge: S.Sasirekha

DEPARTMENT OF MATHS, MJ COLLEGE

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

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

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

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

Presented By : Gaurav Juneja

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

ANSI C Programming Simple Programs

Programming and Data Structures

C Language, Token, Keywords, Constant, variable

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

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

VARIABLES AND CONSTANTS

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

C: How to Program. Week /Mar/05

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

Fundamental of Programming (C)

INTRODUCTION 1 AND REVIEW

Chapter 2 - Introduction to C Programming

Fundamentals of Programming

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

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

6.096 Introduction to C++ January (IAP) 2009

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

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

Fundamental of C programming. - Ompal Singh

Tokens, Expressions and Control Structures

Fundamentals of C Programming

ME240 Computation for Mechanical Engineering. Lecture 4. C++ Data Types

C - Basic Introduction

!"#$% &'($) *+!$ 0!'" 0+'&"$.&0-2$ 10.+3&2),&/3+, %&&/3+, C,-"!.&/+"*0.&('1 :2 %*10% *%7)/ 30'&. 0% /4%./

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program

BLM2031 Structured Programming. Zeyneb KURT

Java Notes. 10th ICSE. Saravanan Ganesh

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

A Fast Review of C Essentials Part I

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information

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

Syntax and Variables

Fundamentals of Programming Session 4

Chapter 2 THE STRUCTURE OF C LANGUAGE

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

Chapter 2: Overview of C. Problem Solving & Program Design in C

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

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

Chapter 1 & 2 Introduction to C Language

Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. C Data Types

Differentiate Between Keywords and Identifiers

BASIC ELEMENTS OF A COMPUTER PROGRAM

CSc Introduction to Computing

Chapter 2. Lexical Elements & Operators

UNIT- 3 Introduction to C++

Variables in C. CMSC 104, Spring 2014 Christopher S. Marron. (thanks to John Park for slides) Tuesday, February 18, 14

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

ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1

THE FUNDAMENTAL DATA TYPES

Preview from Notesale.co.uk Page 6 of 52

Programming. C++ Basics

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

Basic Types and Formatted I/O

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

ET156 Introduction to C Programming

Programming for Engineers Introduction to C

ME 172. Lecture 2. Data Types and Modifier 3/7/2011. variables scanf() printf() Basic data types are. Modifiers. char int float double

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

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

Basics of Programming

Introduction to C# Applications

Lecture 2 Tao Wang 1

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

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

Fundamentals of Programming. Lecture 3: Introduction to C Programming

Data types, variables, constants

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

Introduction to Computing Lecture 01: Introduction to C

Standard 11. Lesson 9. Introduction to C++( Up to Operators) 2. List any two benefits of learning C++?(Any two points)

UEE1302 (1102) F10: Introduction to Computers and Programming

SEQUENTIAL STRUCTURE. Erkut ERDEM Hacettepe University October 2010

EEE145 Computer Programming

Work relative to other classes

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

LEXICAL 2 CONVENTIONS

BITG 1233: Introduction to C++

CS149: Elements of Computer Science. Fundamental C++ objects

Recap. ANSI C Reserved Words C++ Multimedia Programming Lecture 2. Erwin M. Bakker Joachim Rijsdam

PROGRAMMAZIONE I A.A. 2018/2019

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

Creating a C++ Program

DETAILED SYLLABUS INTRODUCTION TO C LANGUAGE

CMSC 104 -Lecture 5 John Y. Park, adapted by C Grasso

Have the same meaning as variables in algebra Single alphabetic character Each variable needs an identifier that distinguishes it from the others a =

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead.

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

1.1 Introduction to C Language. Department of CSE

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

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

IV Unit Second Part STRUCTURES

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

Transcription:

Data Types and Variables in C language

Basic structure of C programming To write a C program, we first create functions and then put them together. A C program may contain one or more sections. They are illustrated below. Documentation section Link section Definition section Global declaration section main () Function section { Declaration part Executable part } Subprogram section Function 1 Function 2.... Function n (User defined functions)

Programming Rules Each instruction should be written in separate statement. A complete C program consists of set of instructions. The statements in program must be written in sequencial order to get desired output. Unless any logic problem can arises. All statement should written in small case letters. C has no particular rules for position at which statement is to be typed. In C program every statement must end with ; (semicolon). It act as a terminator.

Rules for Comment Comment in the program should be enclosed within /*.. */.Look example below the first line is comment. For ex. /*This my first program*/ #include<stdio.h> main() { } Statement; Though comments are not necessary, but it good practice to begin program with comment indicatingpurposeof program so that other person can get idea of program. You can write any number comment at any place in program mentioning the purpose of the statement. Use few Comment instead of too many. A comment cannot be nested. For ex., /* The/* first/*program*/*/*/. A comment can split over more than one line. For ex. /*THE First Program*/

Main Method main() is a collection of the set of statements. Statements that belongs to main() are always written within pairs of {} (opening and closing braces). For ex. void main() { 1st statement; 2nd statement; } Technically main() is a function because every function has the pair of parentheses ( ) associated with it. The function in c have their return type. Similarly, if we want that main() function should not return any value of particular type precede it with void. In case of returning a integer use int.

Declaration Any variable used in the program must be declared before using it. For ex, int a,b,c; float a,b,c; a=a+b; /*declaration*/ /*declaration*/ /*usage*/

Variable types Datatype number Declaration format string Integer 1,+5,-5 int a; "%d", a Float 11.363,+1.14,-12.11 float a; "%f", a Double +1.123123,-1.234345 double a; "%l", a Character 'A','B' char a; "%c",a String "Dev.com" char a[20]; "%c",a

Variable types a) While declaration you can also initialize it as int a=1, b=24;, float a=1.5, b=1.98+3.8*2.7; b) The order of declaration sometimes matter in initialization. For ex. int i = 1, j=24; is same as int j=24, i=1; float a=1.8, b= 3.1+a; This statement is alright but float b=3.1+a, a=1.8; is not the way, we have to initialize a before. c) Lets see another statements: int x,y,z; x=y=z=10; int x=y=z=10; work perfectly does not work we are trying to use y (assign to y) before defining it.

Character Set Character set are the set of alphabets, letters and some special characters that are valid in C language. Alphabets: Uppercase: A B C... X Y Z Lowercase: a b c... x y z Digits: 0 1 2 3 4 5 6 8 9 Special Characters in C language, <>. _ () ; $ : % [] #? & {} ^! * / - \ ~ White space Characters: blank space, new line, horizontal tab, carriage return and form feed

Tri-graph Characters Many non-english keyboards do not support all the characters. ANSI C introduces the concept of Trigraph sequences to provide a way to enter certain characters that are not available on some keyboards.

Tokens in C Keywords Identifiers Constants String Constants Operators Punctuators

Tokens in C

Keywords Keywords are C tokens that have a strict meaning. They are explicitly reserved and cannot be redefined. ANSII C has 32 key words auto do goto signed unsigned break double if sizeof void case else int static volatile char enum long struct while const extern register switch continue float return typedef default for short union

Identifiers In C programming, identifiers are names given to C entities, such as variables, functions, structures etc. Identifier are created to give unique name to C entities to identify it during the execution of program. For example: int money; int mango_tree; Here, money is a identifier which denotes a variable of type integer. Similarly, mango_tree is another identifier, which denotes another variable of type integer.

Rules for Identifiers First letter must be alphabet (or Underscore) An identifier can be composed of letters (both uppercase and lowercase letters), digits and underscore '_' only. The first 31 characters of an identifier are significant Cannot use Keyword as identifiers Must not contain white space

Constants Constants in C refers to fixed values that do not change during the execution of program. C supports several types of constants

Integer Constants An integer constant refers to a sequence of digits, There are three types integers, namely, decimal, octal, and hexa decimal. Decimal Constant Eg: 123,-321 etc., Note: Embedded spaces, commas and non-digit characters are not permitted between digits. Eg: 15 750, $1000 Octal Constant An octal integer constant consists of any combination of digits from the set 0 through 7, with a leading 0. Eg: 1) 037 2) 0435 Hexadecimal Constant A sequence of digits preceded by 0x or 0X is considered as hexadecimal integer. They may also include alphabets A through F or a through f. Eg: 1) 0X2 2) 0x9F 3) 0Xbcd

Integer Constants Program for representation of integer constants on a 16-bit computer. /*Integer numbers on a 16-bit machine*/ main() { printf( Integer values\n ); printf( %d%d%d\n,32767,32767+1,32767+10); printf( \n ); printf( Long integer values\n ); printf( %ld%ld%ld\n,32767l,32767l+1l,32767l+10l); } OUTPUT Integer values 32767-32768 -32759 Long integer values 32767 32768 32777

Real Constants Certain quantities that vary continuously, such as distances, heights etc., are represented by numbers containing functional parts like 17.548. Such numbers are called real (or floating point) constants. Eg: 0.0083, -0.75 etc. A real number may also be expressed in exponential or scientific notation. Eg:215.65 may be written as 2.1565e2 The generic form is mantissa e exponent 2.1565 is called as mantissa and 2 is the exponent Embedded white spaces are not allowed.

Single Character Constants A single character constants contains a single character enclosed within a pair of single quote marks. Eg: 7, X, ;, ' ' Note that character '7' is not same as number 7. Character constants have integer values known as ASCII values For ex. printf( %d, 'A'); will print 65, the ASCII value of 'A' Similarly, printf( %c, 65); will print letter 'A'

String Constants A string constant is a sequence of characters enclosed in double quotes. The characters may be letters, numbers, special characters and blank space. Eg: Hello!, 1987?.!

Backslash Character Constants C supports special backslash character constants that are used in output functions. These character combinations are known as escape sequences.

Variables A variable is a data name that may be used to store a data value. It may take different values at different times of execution and may be chosen by the programmer in a meaningful way. Variable name may consist of letters, digits and underscore character. Eg: 1) Average, 2) Counter_1 3) Fan1

Rules for Variable Names They must begin with a letter. Some systems permit underscore as the first character. ANSI standard recognizes a length of 31 characters. However, the length should not be normally more than eight characters. Uppercase and lowercase are significant. The variable name should not be a keyword. White space is not allowed.

Rules for Variable Names Valid Variables Names: John Value T_raise Delhi x1 ph_value mark sum1 distance Invalid Variable Names: 123 (area) % 25th

Data Types Storage representation and machine instructions to handle such data differs from machine to machine. Variety of data type is available in C to select from. A data type is used to Identify the type of a variable when the variable is declared Identify the type of the return value of a function Identify the type of a parameter expected by a function

Data Types ANSI C supports four classes of data types. 1. Primary or Fundamental data types. 2. User-defined data types. 3. Derived data types. 4. Empty data set.

Primary Data Types

Data Types - Integer Size and Range Of Data types on 16 bit machine

Data Types - Floating Point

Declaration of Variables Declarations does two things: It tells the compiler what the variable name it It specifies what type of data the variable will hold Primary Type Declaration The syntax is Data-type v1,v2..vn; Eg: int count; double ratio, total;

User-defined type declaration C allows user to define an identifier that would represent an existing data type. The general form is typedef type identifier; Eg: typedef int units; typedef float marks; Another user defined data types is enumerated data type which can be used to declare variables that can have one of the values enclosed within the braces. enum identifier {value1,value2, valuen}; Ex. enum day {Monday, Tuesday, Wednesday, Thursday, Friday} enum day week_st, week_end; week_st = Monday;

Declaration of Storage Class Variables in C can have not only data type but also storage class that provides information about their locality and visibility. /*Example of storage class*/ int m; main() { int i; float bal; function1(); } function1() { int i; float sum; } Here the variable m is called the global variable. It can be used in all the functions in the program. The variables bal, sum and i are called local variables. Local variables are visible and meaningful only inside the function in which they are declared. There are four storage class specifies, namely, auto, static, register and extern

Declaration of Storage Class

Assigning Values to Variables The syntax is Variable_name=constant Eg: int a=20; bal=75.84; yes= x ; C permits multiple assignments in one line. Example: initial_value=0;final_value=100;

Reading Data from Keyboard Another way of giving values to variables is to input data through keyboard using the scanf function. The C library function int scanf(const char *format,...) reads formatted input from stdin. The general format of scanf is as follows. scanf( control string, &variable1, &variable2,.); The ampersand symbol & before each variable name is an operator that specifies the variable name s address. Eg: scanf( %d, &number); Note: printf() and scanf() functions are declared in stdio.h header file in C library.

Symbolic Constants Many times unique constants are required in the program which are used repeatedly. For Ex. 3.142, representing value of pi It is advisable to use named constant or symbolic names rather than the value like Area = PI * r *r; rather than Area = 3.142 * r *r; It also increases understandability of the program Ex. # define PI 3.14159 Ex. # define PASS_MARKS 40 Symbolic names are constants and not variables. They do not appear in declaration.

Symbolic Constants - Rules Symbolic names have same form as variable names No space between # and define keyword # must be first character in the line Blank space between #define and symbolic name and the constant No semicolon to end the statement After definition, no value can be assigned to symbolic constant in the program No data types #define statement may appear anywhere in the program but before its usage. However usual practice is to place them in the beginning of the program.

Symbolic Constants Valid symbolic constant definition #define Students 70 #define COURSE BTECH Invalid symbolic constant definition #define Students = 70 # define COURSE BTECH #define COUNT 70; #define A 10, B20 #Define Total 100 #define amount$ 1000

Variable as Constant Certain variables may be required to remain constant throughout the program execution. Can be declared as constant Ex. const int class_size=40; This tells the compiler that the value of the int variable class_size must not be modified by the program.

Variable as Volatile By declaring a variable as volatile, its value may be changed at any time by some external source. Eg: volatile int date; The value of a volatile variable may be changed by some external factors even if it does not appear on the LHS of an assignment statement. The value of a volatile variable can be modified by by its own program as well. If the value should not be modified by the program while it can be altered by external process, declare as both const and volatile Ex. volatile const int location = 100;

Overflow and Underflow of Data Problem of data overflow occurs when value of a variable is either too big or too small for data type to hold Floating point values are rounded to the number of significant digits allowed Integers are always exact within the limit of the range of the integral data type C does not provide any warning or indication of integer overflow Exercise greater care in defining the variable with correct data type