Unit 1
Unit 1
I CSE C
SEMESTER II
CS3251 Programming in C
UNIT 1
BASICS OF C PROGRAMMING
SYLLABUS
Definition Section
define such symbolic constants that we have to use in the entire
program, here the value once defined is never changed during
the entire program. These symbolic constants are also called
macro.
Eg #define PI=3.14
Global Declaration Section
There are some variables that are used in more than one function.
Such variables are called global variables and are declared in the
global declaration section that is outside of all the functions. This
section also declares all the user-defined functions.
Eg: int b=30;
void add(int r, int k);
For example
void main() // In some compiler, “void” is optional
{
Statement 1
….
Statement i
}
# include< stdio.h>
# define PI
_ 4_BY_ 3 4. 1887902048
b. Octal
Octal Integer Constant can contain digits from 0 to 7. Octal numbers
always start with 0 in C.
Examples of valid Octal Integer Constants:
0123 06663
Integer Constant
c.Hexadecimal
Hexadecimal Integer Constant can contain digits from 0 to 9 and
alphabets from A to F. where
A = 10
B = 11
C = 12
D = 13
E = 14
F = 15
Hexadecimal numbers always start with 0X in C.
Examples of valid Hexadecimal Integer Constants:
0X123 0X6663
Integer constants
An integer constant can be a decimal integer or octal integer
or hexadecimal integer.
• Embedded spaces, commas and non-digit characters are not permitted between
digits.
b. Exponent Form
Exponent form of floating point constant is also called scientific
notation.
In this form, a floating point number is represented in terms of
power of 10.
The power of 10 is represented by E or e where E represents
exponent.
Example
23000000 can be represented as 2.3e7
Character Constant
Character Constants are those constants which can contain any
symbol which can include alphabets, digits, special symbols as well
as blank spaces. Character constant can be categorized into two
types:
Single Character Constant
String Constant
Escape Sequence
printf("%d ",i);
}
}
Program2:
enum day {sunday = 1, monday, tuesday = 5,wednesday, thursday = 10, friday,
saturday};
int main()
{
printf("%d %d %d %d %d %d %d", sunday, monday, tuesday,
wednesday, thursday, friday, saturday);
return 0;
}
Language Elements in C
The C-Character Set
• The C language alphabet:
• Uppercase letters ‘A’ to ‘Z’
• Lowercase letters ‘a’ to ‘z’
• Digits ‘0’ to ‘9’
• C special characters:
, < > . _
( ) ; $ :
% [ ] # ?
' & { } "
^ ! * / |
- \ ~ +
C language recognizes total 256 ASCII codes; other 128 ASCII codes are for extended
characters’ symbols
Keywords in C
• Keywords
• Keywords are those words whose meaning is already defined by Compiler; also
called “reserved words” and cannot be used in identifier declaration
• There are 32 keywords in C
auto double int struct
break else long switch
case enum register typedef
char extern return union C is a case-sensitive
const float short unsigned programming
continue for signed void language!
default goto sizeof volatile
do if static while
Identifiers in C
Rules for Identifiers in C –
* First character: The first character of the identifier should necessarily begin
with either an alphabet or an underscore. It cannot begin with a digit.
* No special characters: C does not support the use of special characters
while naming an identifier. For instance, special characters like comma or
punctuation marks can’t be used.
* Nokeywords: The use of keywords as identifiers is strictly prohibited, as
they are reserved words which we have already discussed.
* No white space: White spaces include blank spaces, newline, carriage
return, and horizontal tab, which can’t be used.
* Word limit: Theidentifier name can have an arbitrarily long sequence that
should not exceed 31 characters, otherwise, it would be insignificant.
* Case sensitive: Uppercase and lowercase characters are treated differently.
Variables
• It is a data name that can be used to store a data value.
Example: x = 39, here x being a variable presently stored 39 in it
int a, b, c;
char x;
a = 3;
b = 50; c = a-b;
x = ‘d’;
b = 20; a = a+1;
x = ‘G’;
Declarations of Variables
• There are two purposes:
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.
• General syntax:
data-type variable-list;
• Examples:
int velocity, distance;
int a, b, c, d;
float temp;
char flag, option;
Declarations of Variables
• According to C-language, in an expression
• A variable say x, refers to the contents of the memory location.
• &x refers to the address of the memory location.
• Examples:
scanf (“%f %f”, &x, &y);
printf (“%f %f %f”, x, y, x + y);
Declarations of Variables
Operators in C-Language
Operators in C
Operators
Increment Bit-wise
Operators Operators
Arithmetic Operators
x = 13; y = 5;
• Addition: +
• Subtraction: -
• Multiplication: *
• Division: /
• Modulus: %
Example:
distance = rate * time ;
netIncome = income - tax ;
speed = distance / time ;
area = PI * radius * radius;
y = a * x * x + b*x + c;
quotient = dividend / divisor;
remain = dividend % divisor;
int a = 21; int b = 10; int c ;
c = a + b;
printf("Line 1 - Value of c is %d\n", c );
c = a - b;
printf("Line 2 - Value of c is %d\n", c );
c = a * b;
printf("Line 3 - Value of c is %d\n", c );
c = a / b;
printf("Line 4 - Value of c is %d\n", c );
c = a % b;
printf("Line 5 - Value of c is %d\n", c );
c = a++;
printf("Line 6 - Value of c is %d\n", c );
c = a--;
printf("Line 7 - Value of c is %d\n", c );
Operation Result Example
x = 5 (0101), y = 12 (1100)
Operator Meaning Usage Example
& Bitwise AND z=x&y z = 0100 (4)
| Bitwise OR z=x|y z = 1101 (13)
^ Bitwise exclusive OR z= x^y z = 1001 (9)
<< Left shift z = x << u z = 0100 (4)
>> Right shift z = x >> u z = 0001(1)
~ One’s complement z = ~x z = 1010 (10)
u is an unsigned integer
See illustrations for left-shift and right-shift operations in the next slide
*Bit wise left shift and right shift : In left shift operation “x
<< 1 “, 1 means that the bits will be left shifted by one
place. If we use it as “x << 2 “, then, it means that the bits
will be left shifted by 2 places.
EXAMPLE
212 = 11010100 (In binary)
212>>2 = 00110101(In binary) [Right shift by two bits]
212>>7 = 00000001 (In binary)
212>>8 = 00000000
212>>0 = 11010100 (No Shift)
x = 00101000
*x << 1 = 01010000 (binary) = 80 (decimal)
*x >> 1 = 00010100 (binary) = 20 (decimal)
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;
c = a & b; /* 12 = 0000 1100 */
printf("Line 1 - Value of c is %d\n", c );
c = a | b; /* 61 = 0011 1101 */
printf("Line 2 - Value of c is %d\n", c );
c = a ^ b; /* 49 = 0011 0001 */
printf("Line 3 - Value of c is %d\n", c );
c = ~a; /*-61 = 1100 0011 */
printf("Line 4 - Value of c is %d\n", c );
c = a << 2; /* 240 = 1111 0000 */
printf("Line 5 - Value of c is %d\n", c );
c = a >> 2; /* 15 = 0000 1111 */
printf("Line 6 - Value of c is %d\n", c );
Relational Operators
When arithmetic expressions are used on either side of a relational operator, the
arithmetic expressions will be evaluated first and then the results compared.
Example:
a + b > c – d is the same as (a+b) > (c-d)
Relational Operators
• Example:
if (x > y)
printf (“%d is larger\n”, x);
else
printf (“%d is larger\n”, y);
Logical Operators
• logical operators in C (also called logical connectives).
&&---------- Logical AND
|| ------- Logical OR
! -------- Logical NOT
Logical Operators
• Logical AND
• Result is true if both the operands are true.
• Logical OR
• Result is true if at least one of the operands are true.
Assignment in C-Language
It is used to assign a value or expression etc to a variable.
Compound operator
It is also used to assign a value to a variable.
Eg: x + = y means x = x + y
Nested operator
It is used for multiple assignment. Eg: i = j = k = 0;
Statement with simple Statement with
assignment operator shorthand operator
var_name op= expression;
a=a+1 a += 1
a=a–1 a -= 1
a = a * (n+1) a *= (n+1)
a = a / (n+1) a /= (n+1)
a=a%b a %= b
Assignment in C
• Used to assign values to variables, using the assignment operator (=).
• General syntax:
variable_name = expression;
Examples:
velocity = 20;
b = 15; temp = 12.5;
A = A + 10;
v = u + f * t;
s = u * t + 0.5 * f * t * t;
Example:
a + b * c – d / e a + (b * c) – (d / e)
a * – b + d % e – f a * (– b) + (d % e) – f
a – b + c + d (((a – b) + c) + d)
x * y * z ((x * y) * z)
a + b + c * d * e (a + b) + ((c * d) * e)
Integer arithmetic
• Operators applicable
• All arithmetic operators
• All logical operators
• All relational operators
• All increment and decrement operators
• All bit-wise operators
Real Arithmetic
• When one of the operands is integer and the other is real, the expression is called a
mixed-mode arithmetic expression.
• If either operand is of the real type, then only real arithmetic is performed, and the
result is a real number.
25 / 10 2
25 / 10.0 2.5
x = l / i + i * f - d
long double
double
int double
Type Casting
• C language allows to force a type conversion, which is different than the
automatic type conversion
• The syntax for such a type casting is
(type_name) expression;
Example
int a = 4, b = 5; float x; double y;
x = (float) a / b; // division is done in floating point mode, x = 0.8
a = (int) x / b; // Result is converted to integer by truncation, a = 0
y = (char) b / a; // It may report wrong type conversion
The Standard Input Output File
*Character Input / Output
*getchar, getc
*putchar, putc
*Formatted Input / Output
*printf
*scanf
*Whole Lines of Input and Output
*gets
*puts
C uses two functions for formatted input and output.
#include <stdio.h>
main()
{
char line[256]; /* large to store a line of input */
while(gets(line) != NULL) /* Read line */
{
puts(line); /* Print line */
printf("\n"); /* Print blank line */
}
}
◾ Expresses some action to be carried out
◾ Program is a sequence of one or
more statements.
void main()
{
int a;
a=10;
printf(“%d”,a);
}
◾ Decision making (Branching) Statement is used
to specify the order in which statements are to
be executed.
◾ The statements are
If
If…else
Nested if
If….else if….else
Switch…case
if ( condition)
statement;
Or
if (condition)
{
Statements;
}
if ( a>b)
c=a;
Or
if (a>b)
{
c=a;
printf(“a is big”);
}
int main() Output:
{ Please Enter Ur Pin
int pin; 1234
printf(“Please Enter ur Pin”); Proceed
scanf(“%d”,&pin); Home
if(pin==1234) Test Case2:
printf(“Proceed”); Please Enter Ur Pin
printf(“Home”); 11111
Home
}
Case:
• Ask a user to enter a number
• If it is negative, then display “Wrong”
• Other wise display “Correct”
int main()
{ Test Case1:
Enter any Num
int num;
-45
printf(“Enter any Num”); Wrong
scanf(“%d”, &num );
if( num<0)
printf(“Wrong”); Test Case2:
else Enter any Num
123
printf(“Correct”); Correct
}
Nested IF
if ( condition) Case:
statement 1; • Ask a user to enter his
else if(condition) age
statement 2; • If it is more than 50, then
else “OLD”
statement 3; • If it is more than 35 ,
then “MIDDLE”
• Otherwise, “YOUNG”
int main()
{ Test Case1:
Enter Ur Age
int age; 45
printf(“Enter Ur Age”); MIDDLE
scanf(“ %d ”, &age ); Test Case2:
if( age >= 50 ) Enter Ur Age
printf (“OLD”); 12
YOUNG
else if(age >= 35 && age<50 )
printf (“MIDDLE”); Test Case3:
Enter Ur Age
else 66
printf (“YOUNG”); OLD
}
switch ( expr)
{ Note:
case constant: • expr value :
stmt; integer / char
break;
• case constant must be
case constant:
stmt; • Int
break; • char
default: case 1:
stmt; case ‘a’:
}
int main()
Test Case1:
{
Enter the choice
int choice; 2
printf(“Enter the choice”); Monday
switch( choice )
{ Test Case2:
Enter the choice
case 1: 9
printf(“Monday”); Pls enter between 1 to 7
break;
Test Case3:
default: Enter the choice
printf(“Pls enter between 1 to 7); 7
} saturday
}
◾ Iteration Statement is used to execute set of
statements repeatedly until condition holds
true
◾ Types
for
while
do … while
for ( initialization ; condition; increment/decrement)
statement;
Case:
• Print Values from 1 to 50
int main()
{ Numbers from 1 to 50
1
int i; 2
printf(“Numbers from 1 to 50”); 3
.
for( i=1;i<=50;i++) .
{ .
printf (“%d”,i); .
} 50
printf(“Over”); Over
}
Initialization;
while( condition)
{
statements;
Increment/decrement;
}
How while loop works?
•The while loop evaluates the test expression inside the
parenthesis ().
•If the test expression is true, statements inside the body
of while loop are executed. Then, the test expression is
evaluated again.
•The process goes on until the test expression is evaluated to
false.
•If the test expression is false, the loop terminates (ends).
•The do..while loop is similar to the while loop with one
important difference.
•The body of do...while loop is executed at least once. Only
then, the test expression is evaluated.
How do...while loop works?
•The body of do...while loop is executed once. Only then,
the test expression is evaluated.
•If the test expression is true, the body of the loop is
executed again and the test expression is evaluated.
•This process goes on until the test expression becomesfalse.
•If the test expression is false, the loop ends.
Example: (while) Example: (for)
int x = 2; int x;
while(x < 100) for(x=2;x<100;x*=2)
{ printf("%d\n", x);
printf("%d\n", x);
x = x * 2;
}
Example: (do-while)
do{
printf("Enter 1 for yes, 0 for no :");
scanf("%d", &input_value);
} while (input_value == 1);
Output
#include<stdio.h>
#include<conio.h>
Enter the Number:3
void main() The value of 3! is: 6
{
int i=1,fact=1,n;
printf("\nEnter the Number:"); for(i=1;i<=n;i++)
scanf("%d",&n); {
while(i<=n) fact =fact *i;
{
fact =fact *i; }
i++; // i=i+1
}
printf("\n The value of %d! is:%d",n,fact);
getch();
}
unconditional control statements/Jump Statements
O/P:
Current time: 19:54:39
Compilation process
The compilation is a process of converting the source code
into object code. It is done with the help of the compiler.
The compiler checks the source code for the syntactical or
structural errors, and if the source code is error-free, then it
generates the object code
Compilation process
The c compilation process converts the source code taken
as input into the object code or machine code.
The compilation process can be divided into four steps,
i.e., Pre-processing, Compiling, Assembling, and Linking.
The preprocessor takes the source code as an input, and it
removes all the comments from the source code.
The preprocessor takes the preprocessor directive and
interprets it.
For example, if <stdio.h>, the directive is available in the
program, then the preprocessor interprets the directive and
replace this directive with the content of the 'stdio.h' file.
The following are the phases through which our
program passes before being transformed into an
executable form:
Preprocessor
Compiler
Assembler
Linker
Preprocessor
The source code is the code which is written in a text editor and the source code
file is given an extension ".c". This source code is first passed to the
preprocessor, and then the preprocessor expands this code. After expanding the
code, the expanded code is passed to the compiler.
Compiler
The code which is expanded by the preprocessor is passed to the compiler. The
compiler converts this code into assembly code. Or we can say that the C
compiler converts the pre-processed code into assembly code.
Assembler
The assembly code is converted into object code by using an assembler. The
name of the object file generated by the assembler is the same as the source file.
The extension of the object file in DOS is '.obj,' and in UNIX, the extension is'o'. If
the name of the source file is 'hello.c', then the name of the object file would
be 'hello.obj'.
Linker
linker is to link the object code of our program with the object code of the
library files and other files. The output of the linker is the executable file. The
name of the executable file is the same as the source file but differs only in their
extensions. In DOS, the extension of the executable file is '.exe', and in UNIX, the
executable file can be named as 'a.out'.
*First,the input file, i.e., hello.c, is passed to the preprocessor,
and the preprocessor converts the source code into expanded
source code. The extension of the expanded source code would
be hello.i.
*The expanded source code is passed to the compiler, and the
compiler converts this expanded source code into assembly code.
The extension of the assembly code would be hello.s.
*This assembly code is then sent to the assembler, which converts
the assembly code into object code.
*After the creation of an object code, the linker creates the
executable file. The loader will then load the executable file for
the execution.