You are on page 1of 58

BEGINNING WITH

THE The Stack
Overflow

C
Dennis M. Ritchie

INTRODUCTION

• 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

PROGRAM STRUCTURE

A sample C Program

#include<stdio.h>
int main()
{
--other statements
}

HEADER FILES

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 .h
C Source file is given an extension .c

MAIN FUNCTION

This is the entry point of a program
When a file is executed, the start point is
the main function
From main function the flow goes as per the
programmers choice.
There may or may not be other functions
written by user in a program
Main function is compulsory for any C
program

RUNNING A ‘C’ PROGRAM Type a program Save it Compile 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.

the basic element recognized by the compiler is the "token. In a C source program. ." A token is source- program text that the compiler does not break down into component elements. C LANGUAGE TOKENS What are actually tokens? The smallest individual units in a C program are known as tokens.

1. ] ] 6.g.g. }.g. “SMIT”. -25.g.Operators [e. .Identifiers [e. *] C programs are written using these tokens and the general syntax. {. -. [.g. +.Strings [e.6.Keywords [e. amount] 3.Constants [e. “year”] 5.Special Symbols [e.g. TOKEN TYPES IN ‘C’  C has 6 different types of tokens viz. float. while] 2. 100] 4. main. int.

 All keywords are written in only lowercase. . THE KEYWORDS  "Keywords" are words that have special meaning to the C compiler.  Serve as basic building blocks for program statements.  Their meaning cannot be changed at any instance.

KEYWORDS IN ANSI C auto double register switch break else return typedef case enum short union char etern signed unsigned const float sizeof void continue for static volatile default goto struct while do if int long .

functions. numeric. etc. followed by alpha.and lower-case characters are important (case- sensitive)  Must consist of only letters. digits or underscore ( _ ). THE IDENTIFIERS  They are programmer-chosen names to represent parts of the program: variables.  Only first 31 characters are significant.  Cannot use C keywords as identifiers  Must begin with alpha character or _. . or _  Upper.  Must NOT contain spaces ( ).

VALIDITY OF IDENTIFIERS (EXAMPLES) .

ABOUT CONSTANTS  Constants in C are the fixed values that do not change during the execution of a program. CONSTANTS Numeric Character constants constants Real Single String Integer Constant Character Constant Constants s Constants s .

0X2 etc.  String Constants  A string constant is a sequence of characters enclosed in double quotes [ “ ” ]. +67. “Stack Overflow” etc. For example.0083. 56579u. For example.  Some of the examples are 112.78.89 etc. ‘i’ etc. ‘a’ . CONSTANTS EXAMPLES  Integer Constants  Refers to sequence of digits such as decimal integer. ‘8’. octal integer and hexadecimal integer. 0551.  Single Character Constants  A single char const contains a single character enclosed within pair of single quotes [ ‘ ’ ]. . -0.  Real Constants  The floating point constants such as 0. “0211”.

 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 compiler: 1. DECLARATIONS  Constants and variables must be declared before they can be used. Associates the name of the constant or . Reserves a memory location in which to store the value of the constant or variable. 2. the name and the value of the constant.  A constant declaration specifies the type. the name and possibly the initial value of the variable.  When you declare a constant or a variable.

 Variables are used to store values that can be changed during the program execution.5)  Remember that variables in algebra are represented by a single alphabetic character. or variable.  Variables in C have the same meaning as variables in algebra. value. . they represent some unknown. x=a+b z + 2 = 3(y . WHAT ARE VARIABLES IN C?  A Variable is a data name that is used to store any data value. That is.

digits.  No other special characters are allowed including space. Variable names in C  May only consist of letters. numbers or underscore. . NAMING VARIABLES Variables in C may be given representations containing multiple characters. But there are rules for these representations. 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. and underscores  May be as long as you like.

 Examples:  #define PI 3.14159  #define AGE 52 .  Examples: surfaceArea surface_Area surface_area  Be consistent while naming the variables!  Use all uppercase for symbolic constants (used in #define preprocessor directives). 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.

such as a variable name. CASE SENSITIVITY C is a case sensitive language.  It matters whether an identifier. is uppercase or lowercase.  Example: area Area AREA ArEa are all seen as different variables by the compiler. .

. you must give the compiler some information about the variable.  float area . The declaration statement includes the data type of the variable. DECLARING VARIABLES Before using a variable..e. Examples of variable declarations:  int length . you must declare it. i.

)  Variables are not automatically initialized. DECLARATION (CONTD.  Once a value has been placed in a variable it stays there until the program alters it. it is good practice to initialize variables when they are declared. the value of the variable sum can be anything (garbage).  Thus. For example. . after declaration int sum.

DATA TYPES IN ‘ANSI C’  There are three classes of data types here::  Primitive data types  int. 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. float. . double.

483.647 unsigned long 32 bits Binary 0 4.648 2.175495e-38 3.147.4028235e+38 long double 32 bits IEEE 32-bit 1. signed short 16 bits 2's complement -32768 32767 unsigned short 16 bits Binary 0 65535 int.175495e-38 3.4028235e+38 double 32 bits IEEE 32-bit 1.967.147.4028235e+38 . DATA TYPES. signed int 16 bits 2's complement -32768 32767 unsigned int 16 bits Binary 0 65535 long.295 float 32 bits IEEE 32-bit 1.294.DIFFERENT ATTRIBUTES Type Size Representation Minimum range Maximum range char.175495e-38 3. signed char 8 bits ASCII -128 127 unsigned char bool 8 bits ASCII 0 255 short. signed long 32 bits 2's complement -2.483.

INTEGER An integer type is a number without a fractional part.DATA TYPES : 1. and long int Size of short int  size of int  size of long int . Designed to hold whole numbers Can be signed or unsigned:  12 -6 +3 Available in different sizes (number of bytes): short int. Represents a signed integer of typically 4 or 8 bytes (32 or 64 bits). int. Precise size is machine-dependent.

On separate lines: int length.On the same line: int length. unsigned int area. width.DECLARATION OF INTEGER VARIABLES Declarations tell the compiler what variable names will be used and what type of data each can handle (store). . . unsigned int area. Variables of integer type can be defined . int width.

67 .  ASCII character set used in ANSI C  Numeric value of character is stored in memory: MEMORY: CODE: letter char letter..  Used to hold characters like ‘d’ or ‘x’ etc.CHARACTER  Represents a single byte (8 bits) of storage.  Can be signed or unsigned  Internally char is just a number  Numerical value is associated with character via a character set. DATA TYPE: 2. letter = 'C'.

On separate lines: char x. . y.DECLARATION OF CHARACTER VARIABLES Variables of character type can be defined: . .On the same line: char x.

or when changing the value of a variable of char type. .  When initializing a constant or a variable of char type. CHARACTER DATA  A variable or a constant of char type can hold an ASCII character. char letter. one = '1'. the value is enclosed in single quotation marks. Examples: const char star = '*'.

Designed to hold real numbers 12.8 All numbers are signed. Available in different sizes (number of bytes): float.FLOATING-POINT A floating-point type is a number with a fractional part Represent typically 32 bit real numbers. and long double Size of float  size of double  size of long double . DATA TYPES: 3. double.45 -3.

long double z. long double z . . float y .DECLARATION OF FLOATING POINT VARIABLES Variables of floating point type can be defined: .On separate lines: double x.On the same line: double x. e. r. y. float y. .

. ch). QUICK RESPONSE!  Question: char ch= ‘A’. 2. printf(“%d”. ch). what is the difference between: 1. printf(“%c”.

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 2011 .

i < j. a = (a < b). • Expressions are formed by combining variables with operators and ALWAYS return a single value in C. i = 5. C supports a rich set of operators that allow the programmer to manipulate variables . ABOUT Operators and expressions • They decide the semantics of expression • Meaning of operator given in language system.

<=. . Operators. %) • Relational Operators (<. ==. ||.Types • Arithmetic Operators (+. !=) • Logical Operators (&&. • Special operators. >=. *. • Conditional Operators. -. |) • Assignment Operators (=) • Increment/Decrement Operators. /. >. !) • Bitwise Operators (&.

e.. b and c • Do not use: a + b + c / 3 • Use: (a + b + c ) / 3 . 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. multiplication before addition) • Use parenthesis when needed • Example: Find the average of three variables a.

) • Arithmetic Operators:: .Arithmetic Operators (Contd.

*. If there are several pairs of parentheses “on the same level” (i. not nested). If the parentheses are nested.) • RULES OF OPERATOR PRECEDENCE:: Operator(s) Operation(s) Order of evaluation (precedence) () Parentheses Evaluated first. they are Subtraction evaluated left to right. If there are several. If there are several. Addition Evaluated last.e.. they are evaluated left to right. /. Modulus evaluated left to right. they are sion. . or % Multiplication. + or .Divi Evaluated second. the expression in the innermost pair is evaluated first. Arithmetic Operators (Contd.

/ “divided by” c = a/b 5. b = 2.b 3. What are the values of c in each case above if 1. int a = 10. b = 2.“minus”  c = a . . 3. * “times”  c = a * b 4. 2. % “modulus” c = a % b Q. + “plus”  c = a + b 2. float b = 2. Arithmetic (summary) • Five simple binary arithmetic operators 1. int a = 10. ?? . float a = 10.

< “less than” 3. >= “greater than or equal to” 4. <= “less than or equal to” 5. > “greater than” 2. float • Relational operators return Boolean values: • 0 if relation is FALSE • 1 if relation is TRUE . int. Relational Operators  Six basic operators for comparison of values in C. == “is equal to” 6. != “is NOT equal to” • A relational operator compares two values of C built in data types such as char. These are typically called relational operators: 1.

) .Relational (contd.

Returns 0 (x >= y) // true. Relational (contd... Returns 1 (x != y) // true . (x == y) // false..) • Example: int x=44.. int y=12.. Returns 1 ..

 > is compliment of <=  < is compliment of >=  == is compliment of != . each one is the compliment of another operator such as.Relational Operator Compliments • Among the six relational operators.

! “logical NOT” is used to define a compliment of any given expression or value or variable Logical operators. are typically used in conditional expressions 1. && “logical AND”  A compound expression formed with && evaluates to true if all of its components are true 3. || “logical OR”  A compound expression formed with || evaluates to 1 (true) if any one of its components is true 2. if ( (a == 1) && (b < 3) || (c == 1) ) etc. • However. like relational operators. LOGICAL OPERATORS • Logical Operators are used to create compound expressions • There are three logical operators in C 1. these can also be used in regular expressions .

if( age> 55 && salary < 1000) 2.Truth Table Operand-1 Operand-2 Op1 && Op2 Op1 | | Op2 (Op1) (Op2) (Logical AND) (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.Logical operator.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 are used to assign the result of an expression to a variable. 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. C provides the facility of shorthand assignment operators of the form:: variable op= expression • Some examples are:: x= x+y can be written as x+=y a=a*(n+1) can be written as a *= n+1 z= z%d can be written as z%=d .

. subtracts 1 from the operand • Both the operators are unary and take the following form:: ++x. OR y--. --y.INCREMENT/DECREMENT OPERATORS • In C. OR x++. we have 2 very useful operators called the increment & decrement operators: • Increment : ++ adds 1 to the operand • Decrement : -.

they require variable as their operands. • When prefix ++ (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. the variable’s value is accordingly incremented or decremented and then the expression is evaluated using the new value of the variable.Rules for ++ and – – operators • ++ and – – are unary operators. . • The precedence and associativity if ++ & – – are same as that of unary + and unary –. • When postfix ++ (or – –) is used with a variable in an exp.. firstly.

• Conditional expression :: • Format: <Expression 1> ? <Expression 2> : <Expression 3> • Example: x ? y : z Test True False Condition expression expression . CONDITIONAL OPERATORS • The operators ? and : are called conditional operators as they are used to test the conditions in the conditional expressions.

b= 95. else Both the statements are resulting the same values. if(a>b) z= (a>b) ? a : b. This is an example of usage of conditional expressions .Use of Conditional Operators  Now consider Consider the these following statements: statements: a= 80. b=95. z=b. z=a. a=80.

• AND & • OR | x : 1 0 1 0 (binary) • XOR (exclusive OR) ^ y : 1 1 0 0 (binary) • NOT ~ x & y : 1 0 0 0 (binary) (1’s complement) x | y : 1 1 1 0 (binary) • Shifts are bitwise operators x ^ y : 0 1 1 0 (binary) • SHIFT LEFT << ~x : 0 1 0 1 (binary) • SHIFT RIGHT >> x << y shift x y-places to the left (add zeros) x >> y shift x y-places to the right (sign extend) . BITWISE OPERATORS • Perform bitwise logical operations across individual bits of a value.

b=z. • FOR loop for(i=0. c!= ‘20’) • Interchanging values z=a. ) 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. j=1. THE COMMA ( . i++. i<=10 . . Say. y=5. then y is assigned as 5 and then 15 (10+5) is being assigned to the val • This operator is used in for loops. j++). val = ( x=10. x+y) x is firstly assigned the value as 10. a=b. while loops etc. • WHILE loop while(c =getchar().

THE SIZEOF OPERATOR • The sizeof operator is used with an operand to return the number of bytes the operand occupies. a constant or a data type qualifier. j= sizeof(long int). . The operand may be a variable. • Mainly used to find the length of arrays and structs when their sizes are unknown. • It’s a compile time operator. • Also used to allocate memory spaces dynamically to different variables while any program execution. w= sizeof(32767). • For example:: k= sizeof (sum).

. • Associativity rule decides the order in which multiple occurrences of the same operator are applied.Rules of Precedence & Associativity • Precedence rule decides the order in which different operators are applied.

* & (type) sizeof right to left * / % left to right + . + . left to right ! ~ ++ -. left to right << >> Bitwise left to right < <= > >= Relational left to right == != Relational left to right & Bitwise left to right Bitwise ^ left to right Bitwise | left to right && Logical left to right Logical || left to right ?: right to left = += -= *= /= %= &= ^= |= <<= >>= right to left .OPERATOR PRECEDENCE/ASSOCIATIVITY OPERATORS (precedence from HIGHER to LOWER) ASSOCIATIVITY ( ) [ ] -> . left to right .