Chapter One Basic Concepts in Refrigeration Basic Concepts in Refrigration1.
C the basic concepts
-
Upload
abhinav-vatsa -
Category
Education
-
view
11.932 -
download
1
description
Transcript of C the basic concepts
The Stack Overflow
BEGINNING WITH BEGINNING WITH THETHE
CC
Dennis M. Ritchie
• C programming language– Structured and disciplined approach to program design.
C is developed by Dennis Ritchie C is a structured programming language C supports functions that enables easy maintainability of code,
by breaking large file into smaller modules Comments in C provides easy readability C is a powerful language. C programs built from
Variable and type declarations Functions Statements Expressions
INTRODUCTION
A sample C Program
#include<stdio.h>int main(){
--other statements}
PROGRAM STRUCTURE
The files that are specified in the include section is called as header file
These are precompiled files that has some functions defined in them
We can call those functions in our program by supplying parameters
Header file is given an extension .hC Source file is given an extension .c
HEADER FILES
This is the entry point of a programWhen a file is executed, the start point is
the main functionFrom main function the flow goes as per the
programmers choice.There may or may not be other functions
written by user in a programMain function is compulsory for any C
program
MAIN FUNCTION
Type a programSave itCompile the program – This will generate an exe
file (executable)Run the program (Actually the exe created out of
compilation will run and not the .c file)In different compiler we have different option for
compiling and running. We give only the concepts.
RUNNING A ‘C’ PROGRAM
What are actually tokens?
The smallest individual units in a C program are known as tokens. In a C source program, the basic element recognized by the compiler is the "token." A token is source-program text that the compiler does not break down into component elements.
C LANGUAGE TOKENS
C has 6 different types of tokens viz.1.Keywords [e.g. float, int, while]2.Identifiers [e.g. main, amount]3.Constants [e.g. -25.6, 100]4.Strings [e.g. “SMIT”, “year”]5.Special Symbols [e.g. {, }, [, ] ]6.Operators [e.g. +, -, *]
C programs are written using these tokens and the general syntax.
TOKEN TYPES IN ‘C’
"Keywords" are words that have special meaning to the C compiler.
Their meaning cannot be changed at any instance.Serve as basic building blocks for program statements.All keywords are written in only lowercase.
THE KEYWORDS
KEYWORDS IN ANSI C
switchtypedefunionunsignedvoidvolatilewhile long
registerreturnshortsignedsizeofstaticstruct int
doubleelseenumeternfloatforgotoif
autobreakcasecharconstcontinuedefaultdo
They are programmer-chosen names to represent parts of the program: variables, functions, etc.
Cannot use C keywords as identifiersMust begin with alpha character or _, followed by alpha,
numeric, or _Upper- and lower-case characters are important (case-
sensitive)Must consist of only letters, digits or underscore ( _ ).Only first 31 characters are significant.Must NOT contain spaces ( ).
THE IDENTIFIERS
VALIDITY OF IDENTIFIERS (EXAMPLES)
Constants in C are the fixed values that do not change during the execution of a program.
ABOUT CONSTANTS
CONSTANTS
Numeric constants
Character constants
Integer Constants
Real Constant
s
Single CharacterConstants
String Constant
s
Integer ConstantsInteger Constants Refers to sequence of digits such as decimal integer, octal integer
and hexadecimal integer. Some of the examples are 112, 0551, 56579u, 0X2 etc.
Real ConstantsReal Constants The floating point constants such as 0.0083, -0.78, +67.89 etc.
Single Character ConstantsSingle Character Constants A single char const contains a single character enclosed within
pair of single quotes [ ‘ ’‘ ’ ]. For example, ‘8’, ‘a’ , ‘i’ etc.String ConstantsString Constants
A string constant is a sequence of characters enclosed in double quotes [ “ ” ]; For example, “0211”, “Stack Overflow” etc.
CONSTANTS EXAMPLES
DECLARATIONS Constants and variables must be declared before they can be used. A constant declaration specifies the type, the name and the value of the constant. any attempt to alter the value of a variable defined as constant results in an error message by the compiler A variable declaration specifies the type, the name and possibly the initial value of the variable. When you declare a constant or a variable, the compiler:
1. Reserves a memory location in which to store the value of the constant or variable.2. Associates the name of the constant or variable with the memory location.
A Variable is a data name that is used to store any data value.
Variables are used to store values that can be changed during the program execution.
Variables in C have the same meaning as variables in algebra. That is, they represent some unknown, or variable, value.
x = a + bz + 2 = 3(y - 5)
Remember that variables in algebra are represented by a single alphabetic character.
WHAT ARE VARIABLES IN C?
NAMING VARIABLES
Variables in C may be given representations containing multiple characters. But there are rules for these representations.
Variable names in C May only consist of letters, digits, and underscores May be as long as you like, but only the first 31
characters are significant May not begin with a number May not be a C reserved word (keyword) Should start with a letter or an underscore(_) Can contain letters, numbers or underscore. No other special characters are allowed including
space.
NAMING CONVENTIONS
C programmers generally agree on the following conventions for naming variables. Begin variable names with lowercase letters Use meaningful identifiers Separate “words” within identifiers with underscores or
mixed upper and lower case. Examples: surfaceArea surface_Area
surface_area Be consistent while naming the variables!
Use all uppercase for symbolic constants (used in #define preprocessor directives).
Examples:
#define PI 3.14159 #define AGE 52
CASE SENSITIVITY
C is a case sensitive language. It matters whether an identifier, such as a variable name, is uppercase or lowercase.
Example:areaAreaAREAArEa
are all seen as different variables by the compiler.
DECLARING VARIABLES
Before using a variable, you must give the compiler some information about the variable; i.e., you must declare it.
The declaration statement includes the data type of the variable.
Examples of variable declarations: int length ; float area ;
Variables are not automatically initialized. For example, after declaration
int sum;the value of the variable sum can be anything (garbage).
Thus, it is good practice to initialize variables when they are declared.
Once a value has been placed in a variable it stays there until the program alters it.
DECLARATION (CONTD.)
There are three classes of data types here::
Primitive data types int, float, double, char
Aggregate OR derived data types Arrays come under this category Arrays can contain collection of int or float or char or double data
User defined data types Structures and enum fall under this category.
DATA TYPES IN ‘ANSI C’
DATA TYPES- DIFFERENT ATTRIBUTES
Type Size Representation Minimum range Maximum range
char, signed char 8 bits ASCII -128 127
unsigned char bool 8 bits ASCII 0 255
short, signed short 16 bits 2's complement -32768 32767
unsigned short 16 bits Binary 0 65535
int, signed int 16 bits 2's complement -32768 32767
unsigned int 16 bits Binary 0 65535
long, signed long 32 bits 2's complement -2,147,483,648 2,147,483,647
unsigned long 32 bits Binary 0 4,294,967,295
float 32 bits IEEE 32-bit 1.175495e-38 3.4028235e+38
double 32 bits IEEE 32-bit 1.175495e-38 3.4028235e+38
long double 32 bits IEEE 32-bit 1.175495e-38 3.4028235e+38
DATA TYPES : 1- INTEGER
An integer type is a number without a fractional part.
Represents a signed integer of typically 4 or 8 bytes (32 or 64 bits).
Precise size is machine-dependent.Designed to hold whole numbersCan be signed or unsigned:
12 -6 +3Available in different sizes (number of bytes): short int, int, and long int
Size of short int size of int size of long int
DECLARATION OF INTEGER VARIABLES
Declarations tell the compiler what variable names will be used and what type of data each can handle (store).
Variables of integer type can be defined- On separate lines:int length;int width;unsigned int area;
- On the same line:int length, width;unsigned int area;
DATA TYPE: 2- CHARACTERRepresents a single byte (8 bits) of storage.Used to hold characters like ‘d’ or ‘x’ etc..Can be signed or unsigned Internally char is just a numberNumerical value is associated with character via a character
set.ASCII character set used in ANSI CNumeric value of character is stored in memory:
CODE:char letter;letter = 'C';
MEMORY:letter
67
DECLARATION OF CHARACTER VARIABLESVariables of character type can be defined:- On separate lines:char x;
- On the same line:char x, y;
CHARACTER DATAA variable or a constant of char type can hold an ASCII
character.
When initializing a constant or a variable of char type, or when changing the value of a variable of char type, the value is enclosed in single quotation marks.
Examples: const char star = '*'; char letter, one = '1';
DATA TYPES: 3- FLOATING-POINT
A floating-point type is a number with a fractional part
Represent typically 32 bit real numbers.Designed to hold real numbers
12.45 -3.8All numbers are signed.Available in different sizes (number of bytes): float, double, and long double
Size of float size of double size of long double
DECLARATION OF FLOATING POINT VARIABLES
Variables of floating point type can be defined:- On separate lines:double x; float y; long double z;- On the same line:double x, y;float y , e; long double z , r;
Question: char ch= ‘A’;
what is the difference between:1. printf(“%c”, ch);
2. printf(“%d”, ch);
QUICK RESPONSE!
Is void a kind of a data type?
Yes or No??
DATA TYPE: 6-VOID
The void data type has no values and no operations.
Operators & Expressions in C
Stack Overflow 2011Stack Overflow 2011
• They decide the semantics of expression
• Meaning of operator given in language system.• Expressions are formed by combining variables with
operators and ALWAYS return a single value in C.i = 5;i < j;a = (a < b);
ABOUT Operators and expressions
C supports a rich set of operators that allow the
programmer to manipulate variables
Operators- Types• Arithmetic Operators (+, -, *, /, %)• Relational Operators (<, >, <=, >=, ==, !=)• Logical Operators (&&, ||, !)• Bitwise Operators (&, |)• Assignment Operators (=)• Increment/Decrement Operators.• Conditional Operators.• Special operators.
ARITHMETIC OPERATORS
Used for performing numeric calculations• Arithmetic calculations
• Use * for multiplication and / for division• Integer division truncates remainder
• 7 / 5 evaluates to 1• Modulus operator(%) returns the remainder
• 7 % 5 evaluates to 2• Operator precedence
• Some arithmetic operators act before others (i.e., multiplication before addition)• Use parenthesis when needed
• Example: Find the average of three variables a, b and c• Do not use: a + b + c / 3 • Use: (a + b + c ) / 3
Arithmetic Operators (Contd.)
C operation
Arithmetic operator
Algebraic expression
C expression
Addition + f + 7 f + 7 Subtraction - p – c p - c Multiplication * bm b * m Division / x / y x / y Modulus % r mod s r % s
• Arithmetic Operators::
Arithmetic Operators (Contd.)
Operator(s) Operation(s) Order of evaluation (precedence) () Parentheses Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there are several pairs of parentheses “on the same level” (i.e., not nested), they are evaluated left to right.
*, /, or % Multiplication,Division, Modulus
Evaluated second. If there are several, they are evaluated left to right.
+ or - Addition Subtraction
Evaluated last. If there are several, they are evaluated left to right.
• RULES OF OPERATOR PRECEDENCE::RULES OF OPERATOR PRECEDENCE::
Arithmetic (summary)
• Five simple binary arithmetic operators1. + “plus” c = a + b2. - “minus” c = a - b3. * “times” c = a * b4. / “divided by” c = a/b5. % “modulus” c = a % b
Q. Q. What are the values of c in each case above if1. int a = 10, b = 2;2. float a = 10, b = 2;3. int a = 10; float b = 2; ??
Relational Operators
Six basic operators for comparison of values in C. These are typically called relational operators:
1. > “greater than”2. < “less than”3. >= “greater than or equal to”4. <= “less than or equal to” 5. == “is equal to”6. != “is NOT equal to”
• A relational operator compares two values of C built in data types such as char, int, float• Relational operators return Boolean values:
• 0 if relation is FALSE• 1 if relation is TRUE
Relational (contd.)Standard algebraic equality operator or relational operator
C equality or relational operator
Example of C condition (Syntax)
Meaning of C condition Taking 2 variables ‘x’ and ‘y’
Equality Operators = == x == y x is equal to y NOT = != x != y x is not equal to y Relational Operators > > x > y x is greater than y < < x < y x is less than y >= >= x >= y x is greater than or
equal to y <= <= x <= y x is less than or
equal to y
Relational (contd.)• Example:
int x=44; int y=12; (x == y) // false... Returns 0 (x >= y) // true... Returns 1 (x != y) // true ... Returns 1
Relational Operator Compliments
• Among the six relational operators, each one is the compliment of another operator such as, > is compliment of <= < is compliment of >= == is compliment of !=
LOGICAL OPERATORS
• Logical Operators are used to create compound expressions• There are three logical operators in C
1. || “logical OR” A compound expression formed with || evaluates to 1 (true) if
any one of its components is true2. && “logical AND”
A compound expression formed with && evaluates to true if all of its components are true
3. ! “logical NOT” is used to define a compliment of any given expression or value or variable
Logical operators, like relational operators, are typically used in conditional expressions
1. if ( (a == 1) && (b < 3) || (c == 1) ) etc.• However, these can also be used in regular expressions
Logical operator- Truth Table
Operand-1(Op1)
Operand-2(Op2)
Op1 && Op2(Logical AND)
Op1 | | Op2(Logical OR)
Non-zero value Non-zero value 1 1
Non-zero value 0 0 1
0 Non-zero value 0 1
0 0 0 0
Some examples of Logical operators can be::1.if( age> 55 && salary < 1000)2.If (number <0 || number >1000)
Relative Precedence
• The relative precedence of the relational as well as logical operators is as follows::
• HIGHEST !> >= < <=== !=&&
• LOWEST | |
ASSIGNMENT OPERATORS
• The operator symbol is the equal sign ( = )• The expression on the right-hand side is evaluated and assigned to
the left-hand variable.int x = 9;
• Assignment operators are used to assign the result of an expression to a variable. C provides the facility of shorthand assignment operators of the form::
• Some examples are::x= x+y can be written as x+=ya=a*(n+1) can be written as a *= n+1z= z%d can be written as z%=d
variable op= expression
INCREMENT/DECREMENT OPERATORS
• In C, we have 2 very useful operators called the increment & decrement operators:
• Increment : ++ adds 1 to the operand• Decrement : -- subtracts 1 from the operand
• Both the operators are unary and take the following form::
++x; OR x++;--y; OR y--;
Rules for ++ and – – operators
• ++ and – – are unary operators; they require variable as their operands.
• When postfix ++ (or – –) is used with a variable in an exp., the expression is evaluated first using the original value of the variable and then the variable’s value is accordingly incremented or decremented.
• When prefix ++ (or – –) is used with a variable in an exp., firstly, the variable’s value is accordingly incremented or decremented and then the expression is evaluated using the new value of the variable.
• The precedence and associativity if ++ & – – are same as that of unary + and unary –.
CONDITIONAL OPERATORS
• The operators ? and : are called conditional operators as they are used to test the conditions in the conditional expressions.
• Conditional expression ::• Format: <Expression 1> ? <Expression 2> : <Expression 3>• Example:
x ? y : zTrue expression
False expression
Test Condition
Use of Conditional Operators
Consider the following statements:a= 80;b= 95;if(a>b) z=a;else z=b;
Now consider these statements:a=80;b=95;z= (a>b) ? a : b;
Both the statements are resulting the same values. This is an example of usage of conditional expressions
BITWISE OPERATORS
• Perform bitwise logical operations across individual bits of a value.• AND &• OR |• XOR (exclusive OR) ^• NOT ~
(1’s complement)
• Shifts are bitwise operators• SHIFT LEFT <<• SHIFT RIGHT >>
x : 1 0 1 0 (binary) y : 1 1 0 0 (binary)
x & y : 1 0 0 0 (binary)
x | y : 1 1 1 0 (binary)
x ^ y : 0 1 1 0 (binary)
~x : 0 1 0 1 (binary)
x << y shift x y-places to the left (add zeros)
x >> y shift x y-places to the right (sign extend)
THE COMMA ( , ) OPERATOR
• This operator is used to link the related expressions together• A comma-linked expression is evaluated from left to right &
the value of the right most expression is the value of combined expression. Say,
val = ( x=10, y=5, x+y) x is firstly assigned the value as 10, then y is assigned as 5 and then 15 (10+5) is being assigned to the val
• This operator is used in for loops, while loops etc.• FOR loop
for(i=0, j=1; i<=10 ; i++, j++);• WHILE loop
while(c =getchar(), c!= ‘20’)• Interchanging values
z=a, a=b, b=z;
THE SIZEOF OPERATOR
• The sizeof operator is used with an operand to return the number of bytes the operand occupies. The operand may be a variable, a constant or a data type qualifier.
• It’s a compile time operator.• Mainly used to find the length of arrays and structs when their
sizes are unknown.• Also used to allocate memory spaces dynamically to different
variables while any program execution.• For example::
k= sizeof (sum);j= sizeof(long int);w= sizeof(32767);
Rules of Precedence & Associativity
• Precedence rule decides the order in which different operators are applied.
• Associativity rule decides the order in which multiple occurrences of the same operator are applied.
OPERATOR PRECEDENCE/ASSOCIATIVITYOPERATORS (precedence from HIGHER to LOWER) ASSOCIATIVITY( ) [ ] -> . left to right! ~ ++ -- + - * & (type) sizeof right to left* / % left to right+ - left to right<< >> left to right< <= > >= left to right== != left to right& left to right^ left to right| left to right&& left to right|| left to right?: right to left= += -= *= /= %= &= ^= |= <<= >>= right to left, left to right
BitwiseBitwiseBitwise
Bitwise
RelationalRelational
LogicalLogical