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