100% found this document useful (1 vote)
119 views

Session 01 PDF

C is a general-purpose programming language developed in the early 1970s. It was developed by Dennis Ritchie at Bell Labs to be used for system programming on the Unix operating system. Some key features of C include that it is compiled, supports structured programming, and is a mid-level language. The document then provides details on C program structure, data types, variables, constants, and keywords.

Uploaded by

LIVE WIRE
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
119 views

Session 01 PDF

C is a general-purpose programming language developed in the early 1970s. It was developed by Dennis Ritchie at Bell Labs to be used for system programming on the Unix operating system. Some key features of C include that it is compiled, supports structured programming, and is a mid-level language. The document then provides details on C program structure, data types, variables, constants, and keywords.

Uploaded by

LIVE WIRE
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

C Programming

Agenda of This Session

• Introduction to C:
• Introduction, Environment setup, Basic I/O
• Variables &Data types, Constants and Literals
• Storage classes , Type casting, operators
• Conditional Branching control statements: If-Else, switch-case,
A Brief History
• Developed in 1972 (traditional C – K&R C)
• By Dennis Ritchie
• AT At&T bell laboritories
• Influenced by Languages ALGOL, CPL, BCPL, B.
• Developed to make Unix more portable.
• 1989 –Standardised by ANSI (American National Standards Institute) – c89
• ISO (International Organization for standardization) adopted C89 with changes
in 1990 – c90
• Later on updated in 1995, 1999, 2011 -C95, C99, c11
About C
• Mother language
• System programming language
• Procedure-oriented programming language
• Structured programming language
• Mid level programming language
Features of C Language
Compiler
• Program that converts Source code to Executable machine language Programs.

• C is a compiled Language.

• Executable machine language program are self contained and runs very quickly.

• Programs written once and run Multiple times, without carrying the source code
or compiler around.
The C Compilation Model
RUNNING A C PROGRAM
• Compiler
Eg: gcc, cc, tcc etc

• Integrated Development Environment- IDE (editor, compiler, Debugger)


Eg: visual studio, code blocks, Clion etc

• Online compilers
Eg: codechef.com, jdoodle.com etc
C Program Structure
• Documentations
• Pre-processor Statements
• Global Declarations
• The main() Function
• Local Declarations
• Program Statements And expressions
• User Defined Functions
Program Example
Example:
/* description: writes the words "hello world" on the screen */

#include<stdio.h>

int main()
{
/* first c program */
printf("hello, world!\n");
return 0;
}
Explanation
• /*……*/ - comments
• #include<stdio.h> - pre-processor directive.
• int/void – return value
• main() – main function
• {….} – block
• printf – function to print text to screen
• return 0 – returns value 0 at the end of the main function.
Note

• C requires a semicolon at the end of every statement.


• Printf() is a standard C function
• \n signifies newline.
Data Types

• Fundamental Datatypes • User Defined


• Integer (int) • TypeDef
• Character (char) • Stucture
• Floating Point (float, double) • Union
• Enumerated Datatype
Data types Cont’d
Character
Integer  equivalent to ‘letters’ in English
language
 used to declare numeric program  Numeric digits: 0 - 9
variables of integer type  Lowercase/uppercase letters: a - z
 whole numbers, positive and and A - Z
negative  Space (blank)
 keyword: int  Special characters: , . ; ? “ / ( ) [ ] { } *
 Example: & % ^ < > etc
int number;  single character
number = 12;
 keyword: char
 Example:
char my_letter;
my_letter = 'U';
Data types Cont’d
Double
Float
 used to declare floating point
 fractional parts, positive and negative variable of higher precision or higher
 keyword: float range of numbers
 Example:  exponential numbers, positive and
float height; negative
height = 1.72;  keyword: double
 Example:
double valuebig;
valuebig = 12E-3;
Type Modifiers

• Size qualifiers
• long
• Short
• Sign qualifiers
• Signed
• Unsigned
Size & Range
Type Size (bytes) Range Format Specifier
Char 1 -127 to +127 %c
Signed char
Unsigned char 1 0 to 255 %c
Short 2 −32,767 to +32,767 %hi
Short int
Signed short
Signed short int
Int 2 −32,767 to +32,767 %i or %d
signed
Signed int
unsigned short 2 0 to 65536 %hu
unsigned short int
unsigned 2 0 to 65536 %u
unsigned int
Size & Range cont’d

long 4 −2,147,483,647 to %li


long int +2,147,483,647
signed long
signed long int
unsigned long 4 0 to 4,294,967,295 %lu
unsigned long int
long long (since c99) 8 −9,223,372,036,854,775 %lli
long long int ,807 to
signed long long +9,223,372,036,854,775
signed long long int ,807
unsigned long long (since 8 0 to %llu
c99) 184467440737095516
unsigned long long int 15
Size & Range cont’d
float 4 3.4E - 38 to 3.4E + 38 %f (promoted
automatically to double
for printf())
double 8 1.7E - 308 to 1.7E + 308 %f (%F)
%g %G
%e %E (for scientific
notation)
long double 10 3.4E _ 4932 to 1.1E + %Lf %LF
4932 %Lg %LG
%Le %LE
_Bool (since c99) 1 0 (false) or 1(true)
Example Program
#include <stdio.h>
int main()
{
int a = 4000; // positive integer data type
float b = 5.2324; // float data type
char c = 'Z'; // char data type
long d = 41657; // long positive integer data type
long e = -21556; // long -ve integer data type
int f = -185; // -ve integer data type
short g = 130; // short +ve integer data type
short h = -130; // short -ve integer data type
double i = 4.1234567890; // double float data type
float j = -3.55; // float data type
}
Variables
• Variables are Names (identifiers) Associated with locations in memory for storing
Variable data.
• Every variable has
• Name
• Type
• Size
• Value
Rules for naming identifiers
Rules Example
Can contain a mix of characters and numbers. However it cannot start with a number. H2O
First character must be a letter or underscore Temp1; _nummix
Can be of mixed cases including underscore character Circle_Area;
TrigCalc
Cannot contain any arithmetic operators A/2; S*
Or any other punctuation marks Num#123;
power^2;
Cannot be a C keyword/reserved word If, printf, while,
struct
Cannot contain a space Decimal Numbers
Identifiers are case sensitive Temp != temp
Reserved Words
C89 has 32 reserved words, also known as keywords, which are the words that
cannot be used for any purposes other than those for which they are predefined:

Auto Double Int Struct


Break Else Long Switch
Case Enum Register Typedef
Char Extern Return Union
Const Float Short Unsigned
Continue For Signed Void
Default Goto Sizeof Volatile
Do If Static While
Reserved Words Cont’d
C99 reserved five more words:

_Bool _Imaginary Restrict _Complex Inline

C11 reserved seven more words:

_Alignas _Atomic _Noreturn _Thread_local


_Alignof _Generic _Static_assert
Constants and Literals

• Four basic types of constants in C


• Integer constants
• Floating-point constants
• Character constants
• String constants
Integer Constants
Integer constants of 3 different bases: Example:
Decimal (Base 10), Hexadecimal (Base
16) or Octal (base 8)
• 123 /* decimal constant*/
• 0x9b /* hexadecimal constant*/
• For decimal literals, no prefix is used.
• 0X9c /* hexadecimal constant*/
• Prefix used for hexadecimal: 0x / 0X
• 0456 /* octal constant*/
• Prefix used for octal: 0
Floating Point Constants
Floating point constant has a integer Example:
part, a decimal point, a fractional part 1234.5432 /* Decimal Form */
and may contain an exponential part.
-100.001 /* signed Decimal Form */
2.37E-3 /* Exponential
• Decimal point format or Form */
• Exponent format 3.14159 /* Legal */
314159E-5L /* With long
suffix */
Character Constant
Character constants hold a single  Example:
character enclosed in single quotes. 'a'
Different characters have associated
integer values (like 'A' is 65, 'a' is 97 'b'
etc.) 1
• Character constants can hold escape 2
sequences too
'\n'
'\0'
Escape Sequence
Description Escape Sequence Carriage Return \r
Bell \a Quotation mark \”
Backspace \b
Apostrophe/single quotes \’
Horizontal tab \t
Question mark \?
Vertical tab \v
Backslash \\
Newline \n
Form feed \f Null \0
String Constants
set of characters enclosed between a Example
pair of double quotes "" /* Null String. */
• A string literal may contain any "A" /* String literal having
number of characters including single characters. */
alphanumeric characters, escape
characters, graphical characters etc. "ABc12.iyu" /* String literal with
multiple characters. */
"ABd jjuh\n" /* String with spaces and
escape characters. */
Declaration of Constants in C
2 Ways:

• Using const keyword in variable declaration.


• Using #define preprocessor directives.
Declaration of Constants in C Cont’d

Const #define

• Syntax • Syntax
const data_type variable_name = Constant; #define Constant_Identifier Value
• Example • Example:
const float PI = 3.141; #define PI 3.141
Storage Classes
• Every variable has a storage class and a scope
• For variables storage class determines
• Part of memory
• Scope
• Visibility
• Lifetime
• 4 storage classes
• Automatic variables
• External variables
• Static variables
• Register variables
Automatic Storage Class
• Keyword: auto
• Scope: local
• Visibility: function or block
• Lifetime: function or block
• Any variable declared within a function or block with or without the ‘auto’
Keyword is by default a variable of the automatic storage class.
• auto is the default storage class for local variables.
• Example:
{
int Count;
auto int Month;
}
External Variable
• Keyword: Extern • Example:
• Scope: Global #include <stdio.h>
• Visibility: Entire duration of program extern int x;
execution int main()
• Lifetime: Entire duration of program {
execution
printf("x: %d\n", x);
• extern defines a global variable that is
visable to ALL object modules. }
• The extern keyword is used before a int x = 10;
variable to inform the compiler that
this variable is declared somewhere
else.
• The extern declaration does not
allocate storage for variables.
Static Variables
• Keyword: static void test(); //Function declaration
• Scope: global main()
• Visibility: function or block {
• Lifetime: Entire duration of program test();
execution test();
• A static variable tells the compiler to persist test();
the variable until the end of program.
• Static variables have default initial value zero }
and initialized only once in their lifetime. void test()
{
static int a = 0; //Static variable
a = a+1;
printf("%d\t",a);
}
output :
1 2 3
Register Variable
• Keyword: register
• Scope: local
• Visibility: function or block
• Lifetime: function or block
• Memory location: CPU registers
• Register should only be used for variables that require quick access - such as
counters.
Example:
{
register int Miles;
}
Type Casting
• Process of converting an entity of one data type to another.
• 2 Types:
• Implicit Type casting
• Explicit Type casting
Implicit Type casting
• automatic type conversion by the
compiler
• data of one or more subtypes can be
converted to a supertype as needed at
runtime
• The compiler converts all operands
into the data type of the largest
operand
• Example:
int i=20;
double p;
p=i; // implicit conversion
Explicit type conversion
• 2 types #include <stdio.h>
• Upcasting- lower to upper datatype int main()
• Downcasting- upper to lower datatype
{
• Upcast – no data loss
int value1 = 10, value2 = 3;
• Downcast – data loss
float result;
• Example:
• float to int causes truncation, i.e., removal
of the fractional part. result = (float)value1 / value2;
• double to float causes rounding of digit.
printf("Result with type casting: %f",
• long long to int causes dropping of
excess higher order bits. result);
• Syntax: return 0;
(data_type)expression; }
Operators
• Special characters used to perform particular operations in C
• Used to manipulate data and variables
• They are:
• Arithmetic Operators
• Increment and Decrement Operators
• Assignment Operators
• Relational Operators
• Logical Operators
• Conditional Operators
• Bitwise Operators
• Special Operators
Operators Cont’d

Arithmetic Operators Relational Operators

Operator Meaning of Operator Operator Description


+ Addition == Is equal to
- Subtraction != Is not equal to
* Multiplication > Greater than
/ Division < Less than
% Remainder >= Greater than or equal to
<= Less than or equal to
Operators Cont’d

Assignment Operators

<<= Assignment by bitwise


Operator Description
left shift
= Simple Assignment
>>= Assignment by bitwise
+= Assignment by sum right shift
-= Assignment by difference &= Assignment by bitwise
*= Assignment by product AND
/= Assignment by quotient ^= Assignment by bitwise
XOR
%= Assignment by
remainder | Assignment by bitwise
OR
Operators Cont’d

Logical Operators
Bitwise Operators
Operator Description
Operator Description
&& Logical AND. True only
when all operands are true. << Binary Left Shift Operator
(performs logical
conjunction on 2
>> Binary Right Shift Operator
expressions)
|| Logical OR. True if either
one operand is true.( ~ Binary ones compliment
Performs a logical operator
disjunction on 2
expressions) & Binary AND operator

! Logical NOT. True when ^ Binary XOR operator


operand is 0. (Performs
| Binary OR operator
logical negation on an
expression)
Operators Cont’d

Increment and Decrement Operators Conditional (ternary) operator

Operator Description • Syntax :


++ Increment Operator Conditional Expression ? expression1 : expression2
-- Decrement Operator • If conditionalExpression is true, expression1 is evaluated.
• If conditionalExpression is false, expression2 is evaluated.
• Example :
(A > 100 ? 0 : 1);
Special Operators
• Comma Operator
• Link related expressions togather
• Eg: int a, c = 5, d;

• Sizeof Operator
• returns the size of data
• Eg:
int a,b;
b=sizeof(a);

• &- Address of Operator


Eg: &a;

• * - Pointer to a variable
Eg: * a
Control Statements
Control the flow of program
3 types:
• Conditional branching control statement
• Conditional looping control statement
• Unconditional control statement
Branching control statement
• 2 types
• Decision Control Statements
Checks for one or more conditions and if the condition is satisfied i.e. true one or
more statements are executed.
• IF statement
• IF- ELSE statement
• IF-ELSE-IF Statement
• Nested IF and IF-ELSE Statement
• Selection Control Statement
A switch statement decides which of several statements to execute.
• Switch-Case Statement
IF Statement
• Most simple form of the branching #include <stdio.h>
statements. int main()
• Syntax: {
if (expression) int x = 20;
statement; int y = 22;
if (x<y)
or {
printf("Variable x is less than y");
if (expression) }
{ return 0;
Block of statements; }
}
IF-ELSE Statement
• Executes some code if the test expression #include <stdio.h>
is true (nonzero) and some other code if int main()
the test expression is false (0).
{
• Syntax:
int num;
if (expression)
printf("Enter an integer: ");
{
scanf("%d",&num);
Block of statements;
// True if remainder is 0
}
if( number%2 == 0 )
else
printf("%d is an even integer.",num);
{
else
Block of statements;
printf("%d is an odd integer.",num);
}
return 0;
}
IF-ELSE-IF Statement
• if-else-if statement allows you to check for #include <stdio.h>
multiple test expressions and execute int main()
different codes for more than two conditions. {
• Syntax: int var1, var2;
if (expression) printf("Enter two integers: ");
{ scanf("%d %d", &var1, &var2);
Block of statements; if (var1 >var2)
} {
else if(expression) printf("var1 is greater than var2");
{ }
Block of statements; else if (var2 > var1)
} {
else printf("var2 is greater than var1");
{ }
Block of statements; else
} {
printf("var1 is equal to var2");
}
return 0;
}
Nested IF-ELSE Statement
#include <stdio.h>
• More than one conditions are int main()
checked one after another to execute {

a specific statement. int n1, n2, n3;


printf("Enter any three numbers :\n");
• Syntax: scanf("%d %d %d", &n1, &n2, &n3);
If(Expression) if(n1>n2)
{
{ if(n1>n3)
If(Expression 2) printf("n1 = %d is max.", n1);
{ else
Block of statement printf("n3 = %d is max.", n3);
}
}
else
else {
{ if(n2>n3)
Block of statement printf("n2 = %d is max.", n2);
} else
printf("n3 = %d is max.", n3);
}
}
return 0;
}

You might also like