ESC Unit-2 - Introduction - To - C - Program
ESC Unit-2 - Introduction - To - C - Program
RV College of
Engineering
Unit -2
Introduction to C
1
Go, change the world
RV College of
Engineering
Contents
2
Go, change the world
RV College of
Engineering
Introduction
C Orientation
3
Go, change the world
RV College of
Engineering
4
Go, change the world
RV College of
Engineering
Later Languages
• 1979 C++ by Bjarn Stroustrup also at
Bell
• Object orientation
• 1991 Java by Sun
• Partial compile to java bytecode:
virtual machine code
• Write once, run anywhere
• Memory manager – garbage
collection
• Many JVMs written in C / C++
5
Go, change the world
RV College of
Engineering
First Program
#include <stdio.h>
int main() Output :
{
/* My first program */ Hello World!
printf("Hello World! \n");
return 0;
}
• C is case sensitive.
• End of each statement must be marked with a
semicolon (;).
• Multiple statements can be on the same line.
• White space (e.g. space, tab, enter, …) is ignored. 7
Go, change the world
RV College of
Engineering
First Program
#include <stdio.h>
int main() Output :
{
/* My first program */ Hello World!
printf("Hello World! \n");
return 0;
}
First Program
#include <stdio.h>
int main() Output :
{
/* My first program */ Hello World!
printf("Hello World! \n");
return 0;
}
■ #include <stdio.h>
■ Including a header file stdio.h
■ Allows the use of printf function
■ For each function built into the language, an associated header file must be included.
■ printf() is actually a function (procedure) in C that is used for printing variables and text
9
Go, change the world
RV College of
Engineering
First Program
#include <stdio.h>
int main() Output :
{
/* My first program */ Hello World!
printf("Hello World! \n");
return 0;
}
• Comments
• /* My first program */
• Comments are inserted between “/*” and “*/”
• Or, you can use “//”
• Primarily they serve as internal documentation for program
structure and function. 10
Go, change the world
RV College of
Engineering
First Program
• first.c. If you are a Windows user, then open the command prompt by clicking
Start→Run and typing “command” and clicking Ok. Using the command prompt,
change to the directory in which you saved your file and then type:
C:\>tc first.c
• In case you are working on UNIX/Linux operating system, then exit the text
editor and type
$cc first.c –ofirst
• If everything is right, then no error(s) will be reported and the compiler will
create an .exe file for your program. This .exe file can be directly run by typing
"first.exe" for Windows and "./first" for UNIX/Linux operating system
• When you run the .exe file, the output of the program will be displayed on
screen. That is,
Hello World! 11
Go, change the world
RV College of
Engineering
First Program
Using Comments
Comments are a way of explaining what a program does. C supports two types of
comments.
• // is used to comment a single statement.
• /* is used to comment multiple statements. A /* is ended with */ and all
statements that lie between these characters are commented.
Note that comment statements are not executed by the compiler. Rather, they are
ignored by the compiler as they are simply added in programs to make the code
understandable by programmers as well as other users.
12
Go, change the world
RV College of
Engineering
First Program
Standard Header Files
Standard header files include:
• string.h : for string handling functions
• stdlib.h : for some miscellaneous functions
• stdio.h : for standardized input and output functions
• math.h : for mathematical functions
• alloc.h : for dynamic memory allocation
• conio.h : for clearing the screen
All the header files are referenced at the start of the source code file that uses one
or more functions from these files.
13
Go, change the world
RV College of
Engineering
14
Go, change the world
RV College of
Engineering
Character Set in C
Just like we use a set of various words, numbers, statements, etc., in any
language for communication, the C programming language also consists of a
set of various different types of characters. These are known as the
characters in C. They include digits, alphabets, special symbols, etc. The C
language provides support for about 256 characters.
17
Go, change the world
RV College of
Engineering
Types of Characters in C
The C programming language provides support for the following types of
characters. In other words, these are the valid characters that we can use in
the C language:
Type of character Description
Digits 0 to 9
Alphabets Lowercase Alphabets a to z
Uppercase Alphabets A to Z
Main characters `~@!$#^*%&()[]{}<>+=_–|/
\;:‘“,.?
All of these serve a different set of purposes, and we use them in different
contexts in the C language.
18
Go, change the world
RV College of
Engineering
C Tokens
The words formed from the character set are building blocks of C and are
sometimes
•C Tokens known as tokens. These tokens represent the individual entity of
language.
•The wordsThe following
formed fromdifferent types of
the character settoken are usedblocks
are building in C of C and are
sometimes known as tokens. These tokens represent the individual entity of
1)language. The following different types of token are used in C
Keywords
2)• Identifiers , Variables
Character set in C
1) Constants
3)
Keywords
2) Strings
4)
3) Identifiers
4) Special
5) symbols
Basic Data Types
5) Operators
6) Variables
6) Constants
7) I/O statements
19
Go, change the world
RV College of
Engineering
Keywords
• C has a set of reserved words often known as keywords that cannot be
used as an identifier.
• All keywords are basically a sequence of characters that have a fixed
meaning. By convention, all keywords must be written in lower case
letters.
• There are 32 keywords in C program
Keywords in C language
20
Go, change the world
RV College of
Engineering
Identifiers
Identifiers are basically names given to program elements such as variables,
arrays, and functions. They are formed by using a sequence of letters (both uppercase and
lowercase), numerals, and underscores
• Identifiers cannot include any special characters or punctuation marks (like #, $, ^, ?, ., etc.)
except the underscore “_”.
• There cannot be two successive underscores.
• Keywords cannot be used as identifiers.
• The case of alphabetic characters that form the identifier name is significant. For example,
‘FIRST’ is different from ‘first’ and ‘First’.
• Identifiers must begin with a letter or an underscore. However, use of underscore as the first
character must be avoided because several complier-defined identifiers in the standard C
library have underscore as their first character. So, inadvertently duplicated names may
cause definition conflicts.
• Identifiers can be of any reasonable length. They should not contain more than 31 characters.
(They can actually be longer than 31, but the compiler looks at only the first 31 characters of
the name.) 21
Go, change the world
RV College of
Engineering
Variables
• A variable is nothing but a name given to a storage area that our programs can
manipulate. Each variable in C has a specific type, which determines the size and
layout of the variable's memory; the range of values that can be stored within that
memory; and the set of operations that can be applied to the variable.
• The name of a variable can be composed of letters, digits, and the underscore
character. It must begin with either a letter or an underscore. Upper and lowercase
letters are distinct because C is case-sensitive. There are following basic variable
types −
Type Description
Char Typically a single octet (one byte). This is an integer type.
int The most natural size of integer for the machine.
float A single-precision floating point value.
Double A double-precision floating point value.
void Represents the absence of type.
22
Go, change the world
RV College of
Engineering
Variables
Numeric Variables
Numeric variables can be used to store either integer values or floating point
values. Modifiers like short, long, signed, and unsigned can also be used with
numeric variables.
Character Variables
Character variables are just single characters enclosed within single quotes.
These characters could be any character from the ASCII character set—letters
(‘a’, ‘A’), numerals (‘2’), or special characters (‘&’).
23
Go, change the world
RV College of
Engineering
Variables
Declaring Variables
To declare a variable, specify the data type of the variable followed by its name. The data
type indicates the kind of values that the variable can store. In C, variable declaration
always ends with a semi-colon. For example,
int emp_num;
float salary;
char grade;
double balance_amount;
unsigned short int acc_no;
Initializing Variables
While declaring the variables, we can also initialize them with some value. For example,
int emp_num = 7;
float salary = 9800.99
char grade = ‘A’;
double balance_amount = 100000000; 24
Go, change the world
RV College of
Engineering
Constants
• A constant is a value or an identifier whose value cannot be altered in a program. For
example: 1, 2.5,
• As mentioned, an identifier also can be defined as a constant. eg. const double PI = 3.14
• Here, PI is a constant. Basically what it means is that, PI and 3.14 is same for this program.
Integer constants
• A integer constant is a numeric constant (associated with number) without any fractional
or exponential part. There are three types of integer constants in C programming:
• decimal constant (base 10) ex: 10,525, 22000
• octal constant (base 8) Ex: 023,045,07
• hexadecimal constant (base 16) Ex: 0x24. oxA5, 0x72b
Declaring Constants
To declare a constant, precede the normal variable declaration with const keyword and
assign it a value.
const float pi = 3.14;
25
Go, change the world
RV College of
Engineering
Constants
Floating-point constants
A floating point constant is a numeric constant that has either a fractional
form or an exponent form. For example: 2.0,0.0000234,-0.22E-5
Character constants
A character constant is a constant which uses single quotation around
characters. For example: 'a', 'l', 'm', 'F'
String constants
String constants are the constants which are enclosed in a pair of
double-quote marks. For example: "good" ,"x", "Earth is round\n"
26
Go, change the world
RV College of
Engineering
Escape Sequences
Sometimes, it is necessary to use characters which cannot be typed or has special
meaning in C programming. For example: newline(enter), tab, question mark etc. In
order to use these characters, escape sequence is used.
For example: \n is used for newline. The backslash ( \ ) causes "escape" from the
normal way the characters are interpreted by the compiler.escape
Sequences Character
\b Backspace
\f Form feed
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\' Single quotation mark
\" Double quotation mark
\? Question mark
\0 Null character 27
Go, change the world
RV College of
Engineering
Operators in C
C language supports different types of operators, which can be used with
variables and constants to form expressions. These operators can be
categorized into the following major groups:
28
Go, change the world
RV College of
Engineering
Arithmetic Operators
Consider three variables declared as,
int a=9, b=3, result;
Table shows the arithmetic operators, their syntax, and usage in C language.
Table Arithmetic operators
29
Go, change the world
RV College of
Engineering
Relational Operators
A relational operator, also known as a comparison operator, is an operator
that compares two values or expressions. Relational operators return true
or false value, depending on whether the conditional relationship between
the two operands holds or not.
Table Relational operators
30
Go, change the world
RV College of
Engineering
Equality Operators
C language also supports two equality operators to compare operands for
strict equality or inequality. They are equal to (==) and not equal to (!=)
operators. The equality operators have lower precedence than the relational
operators.
Table Equality operators
31
Go, change the world
RV College of
Engineering
Logical Operators
C language supports three logical operators. They are logical AND (&&),
logical OR (||), and logical NOT (!). Logical AND and LogicaL OR combines
two relational quantities(Ex A>B && B<C). Logical operators in C are used to
combine multiple conditions/constraints. Logical Operators returns either 0 or 1,.
As in case of arithmetic expressions, logical expressions are evaluated from
left to right.
Truth table of logical AND Truth table of logical OR Truth table of logical NOT
32
Go, change the world
RV College of
Engineering
33
Explanation of logical operator program
a= 5, b=5, c=10
•(a == b) && (c > 5) evaluates to 1
•because both operands (a == b) and (c > b) is 1 (true).
•(a == b) && (c < b) evaluates to 0 because operand (c < b) is 0 (false).
•(a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true).
•(a != b) || (c < b) evaluates to 0 because both operand (a != b) and (c < b)
are 0 (false).
•!(a != b) evaluates to 1 because operand (a != b) is 0 (false).
• Hence, !(a != b) is 1 (true).
•!(a == b) evaluates to 0 because (a == b) is 1 (true).
•Hence, !(a == b) is 0 (false).
34
Go, change the world
RV College of
Engineering
Unary Operators
Unary operators act on single operands. C language supports three unary
operators. They are unary minus, increment, and decrement operators.
Unary Minus (–)
Unary minus operator negates the value of its operand. For example,
int a, b = 10;
a = –(b);
The result of this expression is a = –10
Increment Operator (++) and Decrement Operator (– –)
The increment operator is a unary operator that increases the value of its
operand by 1. Similarly, the decrement operator decreases the value of its
operand by 1.
The increment/decrement operators have two variants: prefix and postfix.
In a prefix expression (++x or – –x), the operator is applied before the
operand while in a postfix expression (x++ or x– –), the operator is applied
after the operand. 35
Go, change the world
RV College of
Engineering
Example
int x = 10, y;
y = x++; is equivalent to writing
y = x; /*y = 10*/ (First Assign the value and then Incriment)
x = x + 1; /*x = 11*/
Whereas y = ++x; is equivalent to writing
x = x + 1; /*x = 11*/ (First Increment and than Assign the value)
y = x; /*y = 11*/
int x = 10, y;
y = x- -; is equivalent to writing
y = x; /*y = 10*/ (First Assign the value and then Decriment)
x = x - 1; /*x = 9*/
Whereas y = - -x; is equivalent to writing
x = x - 1; /*x = 9*/ (First Decriment and than Assign the value)
y = x; /*y = 9*/ 36
Go, change the world
RV College of
Engineering
Conditional Operator
The syntax of the conditional operator is
exp1 ? exp2 : exp3
exp1 is evaluated first. If it is true, then exp2 is evaluated and becomes the
result of the expression, otherwise exp3 is evaluated and becomes the result
of the expression. For example,
large = (a > b) ? a : b
The conditional operator is used to find the larger of two given numbers.
First exp1, that is a > b, is evaluated. If a is greater than b, then large = a,
else large = b. Hence, large is equal to either a or b, but not both.
37
Go, change the world
RV College of
Engineering
Bitwise Operators
As the name suggests, bitwise operators perform operations at the bit level.
These operators include: bitwise AND, bitwise OR, bitwise XOR, and shift
operators.
Bitwise AND
Like boolean AND (&&), bitwise AND operator (&) performs operation on
bits instead of bytes, chars, integers, etc.
For example, Table Truth table of bitwise XOR
10101010 & 01010101 = 00000000
Bitwise OR
example,
10101010 | 01010101 = 11111111
Bitwise XOR
example,
10101010 ^ 01010101 = 11111111 38
Go, change the world
RV College of
Engineering
Assignment Operators
In C language, the assignment operator is responsible for assigning values to
the variables. While the equal sign (=) is the fundamental assignment
operator, C also supports other assignment operators that provide
shorthand ways to represent common variable assignments.
For example,
int x;
x = 10;
assigns the value 10 to variable x. The assignment operator has right-to-left
associativity, so the expression
a = b = c = 10;
is evaluated as
(a = (b = (c = 10)));
40
Go, change the world
RV College of
Engineering
Assignment Operators
Table Assignment operators
41
Go, change the world
RV College of
Engineering
Comma Operator
The comma operator, which is also called the sequential-evaluation
operator, takes two operands. It works by evaluating the first expression and
discarding its value, and then evaluates the second expression and returns
the value as the result of the expression.
For example, the following statement first increments a, then increments b,
and then assigns the value of b to x.
int a=2, b=3, x=0;
x = (++a, b+=a);
Now, the value of x = 6.
42
Go, change the world
RV College of
Engineering
sizeof Operator
sizeof is a unary operator used to calculate the size of data types. This
operator can be applied to all data types. When using this operator, the
keyword sizeof is followed by a type name, variable, or expression. The
operator returns the size of the data type, variable, or expression in bytes.
That is, the sizeof operator is used to determine the amount of memory
space that the data type/variable/expression will take.
For example, sizeof(char) returns 1, that is the size of a character data type. If
we have,
int a = 10;
unsigned int result;
result = sizeof(a);
then result = 2, that is, space required to store the variable a in memory.
Since a is an integer, it requires 2 bytes of storage space.
43
Go, change the world
RV College of
Engineering
44
Go, change the world
RV College of
Engineering
Practice Expressions
int a = 1, b = 0, c = 7;
Expression Numeric Value True/False
a
b
c
a+b
a && b
a || b
!c
!!c
a && !b
a < b && b < c
a > b && b < c
a >= b || b > c
46
Go, change the world
RV College of
Engineering
BASIC DATA TYPES Table Basic data types and their variants
• In addition, C also supports Data Type
Size in
Range
four modifiers—two sign
Bytes
char 1 –128 to 127
specifiers (signed and unsigned char 1 0 to 255
unsigned) and two size signed char 1 –128 to 127
specifiers (short and long). int 2 –32768 to 32767
Table 1.3 shows the variants unsigned int 2 0 to 65535
of basic data types. signed int 2 –32768 to 32767
• Using modifirs we can short int 2 –32768 to 32767
extend or limit the range of unsigned short int 2 0 to 65535
I/O statements in C
• The most fundamental operation in a C program is to accept input values
from a standard input device and output the data produced by the
program to a standard output device.
• Input and Output statement are used to read and write the data in C
programming. These are embedded in stdio.h (standard Input/Output
header file).
• Input means to provide the program with some data to be used in the
program and Output means to display data on screen or write the data to
a printer or a file.C programming language provides many built-in
functions to read any given input and to display data on screen when
there is a need to output the result.
• There are mainly two of Input/Output functions are used for this purpose.
These are discussed as:
• Formatted I/O functions
• Unformatted I/O functions 49
Go, change the world
RV College of
Engineering
50
Go, change the world
RV College of
Engineering
scanf()
The scanf() function is used to read formatted data from the keyboard. The
syntax of the scanf() function can be given as,
scanf ("control string", arg1, arg2, arg3...argn);
The prototype of the control string can be given as,
%[*][width][modifier]type
* is an optional argument that suppresses assignment of the input field.
width is an optional argument that specifies the maximum number of
characters to be read.
modifier is an optional argument (h, l, or L) , which modifies the type
specifier.
type specifies the type of data that has to be read.
• The scanf function ignores any blank spaces, tabs, and newlines entered
by the user.
51
Go, change the world
RV College of
Engineering
the following code that shows how we can input value in a variable of int
data type:
int num;
scanf(" %4d ", &num);
The scanf function reads first four digits into the address or the memory
location pointed by num.
Table Type specifiers
Type Qualifying Input
%c For single characters
%d, %i For integer values
%e,%E,%f,%g,%G For floating point numbers
%o For octal numbers
%s For a sequence of (string of) characters
%u For unsigned integer values
%x,%X For hexadecimal values 52
Go, change the world
RV College of
Engineering
printf()
The printf function is used to display information required by the user and also prints
the values of the variables. Its syntax can be given as:
printf ("control string", arg1,arg2,arg3,...,argn);
The prototype of the control string can
be given as below:
%[flags][width][.precision][modifier]type
Each control string must begin with a % sign.
flags is an optional argument, which specifies output justification like decimal point,
numerical sign, trailing zeros or octadecimal or hexadecimal prefixes.
width is an optional argument which specifies the minimum number of positions
that the output characters will occupy.
precision is an optional argument which specifies the number of digits to print after
the decimal point or the number of characters to print from a string.
modifier field is same as given for scanf() function.
type is used to define the type and the interpretation of the value of the
corresponding argument. 53
Go, change the world
RV College of
Engineering
printf("%10f", x); 8 9 0 0 . 7 6 8
printf("%9.2f", x);
8 9 0 0 . 7 7
Table Flags in printf()
Flags Description
– Left–justify within the given field width
+ Displays the data with its numeric sign (either + or –)
Used to provide additional specifiers like o, x, X, 0, 0x, or 0X for octal and hexadecimal
#
values respectively for values different than zero
54
0 The number is left–padded with zeroes (0) instead of spaces
Go, change the world
RV College of
Engineering
55
Go, change the world
RV College of
Engineering
getchar()
This function is an Input function. It is used for reading a single character from
the keyboard. It is a buffered function. Buffered functions get the input from the
keyboard and store it in the memory buffer temporally until you press the Enter
key.
The general syntax is as:
v = getchar();
where v is the variable of character type. For example:
A simple C-program to read a single character from the keyboard is as:
/*To read a single character from the keyboard using the getchar() function
#include <stdio.h>
main()
{
char n;
n = getchar();
} 56
Go, change the world
RV College of
Engineering
putchar()
This function is an output function. It is used to display a single character on the
screen. The general syntax is as:
putchar(v);
where v is the variable of character type. For example:
A simple program is written as below, which will read a single character using
getchar() function and display inputted data using putchar() function:
/*Program illustrate the use of getchar() and putchar() functions*/
#include <stdio.h>
main()
{
char n;
n = getchar();
putchar(n);
}
57
Go, change the world
RV College of
Engineering
gets()
This function is an input function. It is used to read a string from the keyboard. It
is also a buffered function. It will read a string when you type the string from the
keyboard and press the Enter key from the keyboard. It will mark null character
(‘\0’) in the memory at the end of the string when you press the enter key. The
general syntax is as:
gets(v);
where v is the variable of character type. For example:
A simple C program to illustrate the use of gets() function:
/*Program to explain the use of gets() function*/
#include <stdio.h>
main()
{
char n[20];
gets(n);
} 58
Go, change the world
RV College of
Engineering
puts()
This is an output function. It is used to display a string inputted by gets()
function. It is also used to display a text (message) on the screen for program
simplicity. This function appends a newline (“\n”) character to the output.
The general syntax is as:
puts(v);
or
puts("text line");
where v is the variable of character type.
Cont.
59
Go, change the world
RV College of
Engineering
getch()
This is also an input function. This is used to read a single character from the
keyboard like getchar() function. But getchar() function is a buffered is function,
getchar() function is a non-buffered function. The character data read by this
function is directly assigned to a variable rather it goes to the memory buffer, the
character data is directly assigned to a variable without the need to press the
Enter key.
Another use of this function is to maintain the output on the screen till you have
not press the Enter Key. The general syntax is as:
v = getch();
where v is the variable of character type.
Cont.
61
Go, change the world
RV College of
Engineering
getche()
All are same as getch(0 function execpt it is an echoed function. It means when
you type the character data from the keyboard it will visible on the screen. The
general syntax is as:
v = getche();
where v is the variable of character type.
Cont.
63
Go, change the world
RV College of
Engineering
Typecasting
Typecasting is also known as forced conversion. It is done when the value of
one data type has to be converted into the value of another data type. The
code to perform typecasting can be given as:
float salary = 10000.00;
int sal;
sal = (int) salary;
When floating point numbers are converted to integers, the digits after the
decimal are truncated. Therefore, data is lost when floating point
representations are converted to integral representations.
As we can see in the code, typecasting can be done by placing the
destination data type in parentheses followed by the variable name that has
to be converted. Hence, we conclude that typecasting is done to make a
variable of one data type to act like a variable of another type.
66
Go, change the world
RV College of
Engineering
Scope of Variables
A scope is a region of the program and broadly speaking there are three places,
where variables can be declared:
• Inside a function or a block which is called local variables,
• In the definition of function parameters which is called formal parameters.
• Outside of all functions which is called global variables.
Here let us explain what local and global variables are.
Local Variables
Variables that are declared inside a function or block are local variables. They can
be used only by statements that are inside that function or block of code. Local
variables are not known to functions outside their own. Following is the example
using local variables:
69
Go, change the world
RV College of
Engineering
#include <stdio.h>
int main ()
{
// Local variable declaration:
int a, b;
int c; // actual initialization
a = 10;
b = 20;
c = a + b;
Printf(“%d”,c);
return 0;
}
70
Go, change the world
RV College of
Engineering
Global Variables
Global variables are defined outside of all the functions, usually on top of the
program. The global variables will hold their type throughout the life-time of your
program.
A global variable can be accessed by any function. That is, a global variable is
available for use throughout your entire program after its declaration. Following is
the example using global and local variables:
71
Go, change the world
RV College of
Engineering
#include <stdio.h>
// Global variable declaration:
int g;
int main ()
{
// Local variable declaration:
int a, b;
// actual initialization
a = 10;
b = 20;
g = a + b;
printf(”%d”,g);
return 0;
}
72
Go, change the world
RV College of
Engineering
#include <stdio.h>
// Global variable declaration:
int g = 20;
int main ()
{
// Local variable declaration:
int g = 10;
Printf(“%d:,g);
return 0;
}
When the above code is compiled and executed, it produces the following result:
10
73
Go, change the world
RV College of
Engineering
END of UNIT-II
74