SlideShare a Scribd company logo
Introduction to C language
 C is a general-purpose, procedural programming language developed by Dennis Ritchie
at AT &T (American Telephone and Telegraph Company )Bell Labs in the early 1970s
 General-Purpose Language: C is a versatile programming language used for various
applications, from system software to application software.
 Procedural Language: Emphasizes procedures or routines (functions) to perform tasks.
 C was originally created to develop an operating system called UNIX, which was later
almost entirely rewritten in the C programming language.
History of C
Initially, C language was developed to be used in UNIX operating system. It inherits many
features of previous languages.
Let's see the programming languages that were developed before C language.
1. In 1960,The root of all model language is ALGOL (ALGOrithmic Language)
introduced . ALGOL gave the concept of structured programming to the computer
science community.
2. In 1967s Martin Richards developed a language called as BCPL ( Basic Combined
Programming Language) primarily form writing system software.
3. In 1970s Ken Thomson created a language using many feature of BCPL and called it
simply ‘B’. B was used to create early versions of UNIX operating system at Bell
laboratories.
4. In 1972, C language was developed by Dennis Ritchi from ALGOL, BCPL and B at the
Bell Laboratories. Which referred as "Traditional C"
5. In 1978, the C language gained popularity after the release of the book 'The C
Programming Language' by Kernighan and Dennis Ritchie, leading to it being known as
'K&R C'."
6. In 1983, ANSI (American National Standards Institute) appointed a technical
committee to define a standard for C.
7. In 1989, the ANSI committee approved a version of C that is now known as ANSI C.
8. In 1990, it was approved by the International Standards Organization (ISO). This
version of C is also referred to as ANSI ISO C.
9. In 1999, the C standardization committee added several new features to enhance the
language's usefulness. This version is known as C99.
Importance of C
1. Simple: C language is simple and easy to learn, with straightforward syntax and many
built-in functions and data types.
2. Efficient and Fast: Programs in C are efficient and faster than those in BASIC, thanks to
its variety of data types and powerful operators.
3. Robust: C is robust with a rich set of built-in functions and operators, making it suitable
for complex programs and both system software and business applications.
4. Portable: C programs can run on different machines with little or no modification.
5. Supports Structured Programming: C is well-suited for structured programming, making
debugging and testing easier by breaking problems into functions or modules.
6. Fixed Number of Keywords: ANSI C has only 32 keywords.
7. Large Standard Library: C has a large standard library for common tasks like
input/output, string manipulation, and memory allocation.
8. Extendable or Ability to extend itself: C programs are collections of functions, and you
can create and add your own functions to the C library.
9. Middle-Level Language: C supports features of both low-level and high-level
languages.
Basic Structure of C Programs
1. Documentation Section: Contains comments with the programmer's name, author, and
details like date and time, providing an overview of the program.
2. Link Section: Includes header files for functions used in the program, instructing the
compiler to link system library functions.
3. Definition Section: Contains symbolic constants (macros).
4. Global Declaration Section: Declares global variables and user-defined functions that
can be used anywhere in the program.
5. main() Function Section: Every C program must have a main() function, which
includes:
a. Declaration Part: Declares variables used in the executable part.
b. Executable Part: Contains the actual code to be executed.
Enclosed in opening and closing braces, with each statement ending in a semicolon (;).
6. Subprogram Section: Contains user-defined functions called by the main() function to
perform specific tasks.
CHARACTER SET
C characters are grouped into the following categories.
1. Letters
2. Digits
3. Special Characters
4. White Spaces
Letters
Uppercase A….Z
Lowercase a…..z
Digits
All decimal digits 0…..9
Special characters
, Comma & ampersand
. Period ^ Caret
; Semicolon * Asterisk
: Colon - Minus
? Question mark + Plus sign
‘Apostrophe < Less than
“Quotation mark > Greater than
! Exclamation ( Left parenthesis
| Vertical Bar ) Right parentheses
/ Slash [ Left bracket
 Back slash ] Right bracket
~ Tilde { Left brace
_ Underscore } Right brace
$ Dollar sign # Number sign
% Percent sign
White Spaces
Blank Space
Horizontal Tab
Carriage Return
New Line
Form Feed
Trigraph characters:
• C introduces the concept of trigraph sequences to provide a way to enter certain
characters that are not available on some keywords.
• Each trigraph sequence consists of three characters, 2 question marks followed by
another character.
Trigraph Sequence Translation
??= # Number sign
??( [ Left bracket
??) ] Right bracket
??< { Left brace
??> } Right brace
??! | Vertical bar
??/  Back slash
??’ ^ Caret
??- ~ Tilde
C tokens:
• In a C program the smallest individual units known as C tokens.
• C has 6 types of tokens namely:
1) Keywords
2) Identifiers
3) Constants
4) Strings
5) Special symbols
6) Operators.
Keywords and identifiers
Keywords
 Keywords serve as the building blocks for program statements.
C TOKENS
Keywords Identifiers Constants Strings
Special
Symbols
Operators
 All keywords have a fixed meaning and cannot be changed.
 Keywords cannot be used as normal identifier names.
 Few Examples of keywords used in C are listed below
int
break
goto
char
switch
void
The standard keywords are:
auto break case character
const continue default do
double else enum extern
float for goto if
int long register return
short signed sizeof static
struct switch typedef union
unsigned void while
Identifiers
 Identifier refers to the name of variables, functions and arrays.
 These are user defined names and consists of a sequence of letters and digits.
Rules for Identifiers:
1. First character must be an alphabet.
2. Must consist of only letters, digits or underscore.
3. Only first 31 characters are significant.
4. Cannot use keyword.
5. Must not contain white space.
Constants
 Constants refer to fixed values that do not change during the execution of a
program.
Integer Constants:
• An integer constant refers to a sequence of digits.
• There are 3 types of integers namely:
Decimal integer, octal integer and hexadecimal integer.
• Decimal integer consist of a set of digits 0 through 9, precceded by an optional – or +
sign.
• An octal integer constant consists of any combination of digits from the set 0 through
7. with a leading 0
Eg: 037,0, 0456.
• A sequence of digits preceded by 0x or 0X is considered as hexadecimal integer.
• They may include alphabets A through F or f.
• Letter A through F represents numbers 10 to 15.
Real Constants:
Certain quantities that vary continuously, such as distances, heights etc., are represented by
numbers containing functional parts like 17.548.Such numbers are called real
(or floating point) constants.
• A real number may be expressed in exponential notation.
SYNTAX: mantissa e exponent.
• Mantissa can be either real number expressed in decimal notation or an integer.
• Exponent is an integer number with an optional + or – sign.
• The letter ‘e’ separating the mantissa and the exponent, it can be written either lower
case or upper case.
SYNTAX: 0.65e4,12e-2.
• Exponential notation is useful for representing numbers that are either very large or very
small in magnitude.
Constants
Numeric
Constants
Integer
Constants
Real
Constants
Character
Constants
Single
character
constants
String
constants
Single Character Constants:
• A single character constant contains a single character enclose in a pair of single quote
marks.
• Eg: ‘5’,’x’.
• Character constant ‘5’ is not same as number 5.
• Character constants have integer values known as ASCII values.
• Statement: printf (“%d”, ’a’); would print number 97, the ASCII value of letter ‘a’.
• Since each character constant represent an integer value, it is possible to perform
arithmetic operations on character constants.
String Constants:
• A string constant is a sequence of characters enclosed in double quotes.
• Characters may be letters, numbers, special characters and blank spaces.
Eg: “hello”, “1987”, “?...!”.
• Character constant is not equivalent to single character string constant.
Back Slash Character Constants:
• C supports some special back slash character constants that are used in output
functions.
• These characters combinations are known as escape sequences.
• Back slash character constants are:
‘a’ audible alert; ‘b’ backspace; ‘f’ form feed; ‘n’ newline; ‘r’ carriage return; ‘t’
horizontal tab; ‘v’ vertical tab; ‘”single quote, ‘?’ question mark; ‘’ backslash; ‘0’ null.
Variables
• A variable is a data name that may be used to store a data value.
• A variable may take different values at different times during execution.
• A variable can be chosen by the programmer in a meaningful way.
Rules For Specifying Variables:
1. They must begin with a letter. Some systems may permit underscore as first character.
2. Uppercase and lowercase are significant. The variable TOTAL is different from total
and Total.
3. It should not be keyword.
4. Whitespace is not allowed.
5. Length should be normally more than 8 characters are treated as significant by many
compilers.
Examples of valid variables are:
john, x1,T_raise, first_tag.
Examples of invalid variables are:
123,(area),25th
,price$, %.
DATA TYPES
• C language is rich in its data types.
• Storage representations and machine instructions to handle constants differ from
machine to machine.
• The variety of data types allow to select the type appropriate to the needs of the
application as well as machine.
C supports 3 classes of data types:
1) Primary data types
2) Derived data types
3) User defined data types.
• All C compilers support 5 fundamental data types namely: integer (int), character
(char), floating point (float), double-precision floating point (double) and void.
• Many of them also offer extended data types such as long int, int , long double.
Data type Range of values
char -128 to 127
int -32768 to 32767
float -3.4e+8 to 3.4e+8
Double 1.7e-308 to 1.7e+308.
Integer Types:
• Integers are whole numbers with a range of values supported by particular machine.
• Integers occupy one word storage generally and since the word sizes of machine vary
the size of integer that can be stored depends on computer.
• If we use 16-bit word length, the size of integer value is limited to range -32768 to
32767.
• If we use 32-bit word length can store an integer ranging from -2147483648 to
2147483647.
• In order to provide control over range of numbers and storage space C has 3 classes of
integer storage namely: short int, int, long int in both signed and unsigned.
Floating Point Type:
• Floating point numbers are stored in 32bits, with 6 digit precision.
• Floating point numbers are defined by keyword “float”.
• When accuracy is provided by a float number is not sufficient, double can be used to
define number.
• A double data type number uses 64 bits giving a precision of 14 digits.
• These are known as double precision number.
• Double data type represent the same data type that float represents but with greater
precision.
Void Type:
• Void type has no values. This is used to specify the type of functions.
• The type of function is said to be void when it doesn't return any value to the calling
function.
Character Type:
• A single character can be defined as a character (char) type data.
• Characters are usually store in one byte of internal storage.
• Qualifier signed or unsigned may be used in char explicitly. Unsigned characters have
values between 0 and 255, signed characters have values from -128 to 127
Declaration of variables
After designing suitable variable names, we must declare them to the compiler. Declaration
does two things:
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.
Primary Type Declaration: - A variables can be used to store a value of any data types.
The syntax is
Data-type v1,v2…..vn;
Where v1,v2..vn are different variable name.
Example:- int count;
int number, total;
double ratio;
float price;
char c;
where int, double, float and char are data type.
User-Defined Types Declaration:
There are user defined data types in C
i) Typedef
ii) enum
Typedef :
C supports a feature known as “type definition” that allows users to define an identifiers that
would represent an existing data type.
It takes the general form:
typedef type identifiers;
Example:
typedef int units;
typedef float marks;
Here, units symbolizes int and marks symbolizes float. They can be later used to declare
variables as follows:
units batchl, batch2;
marks height;
Enum:
Another user-defined data type is enumerated data type provided by ANSI standard.
Syntax: enum identifier {val 1, val 2, …...val n};
The identifier is a user-defined enumerated data type which can be used to
declared variables that can have one of the values enclosed within the braces.
Ex: enum day { mon, tue , ……sat};
enum day week-st, week-end;
Declaration of storage classes
Variables in C can have not only data type but also storage class that provide information about
their location and visibility. The storage class decides the portion of the program within which
the variables are recognized.
C supports the following Storage class specifiers:
1. auto: local variable known only to the function where it is declared default is auto.
2. Static: local variable that exists and retains its value even after control is transferred to the
calling function.
3. extern: global variable known to all functions in the file
4. register: local variable, which is stored in the register.
Example:
auto int count;
register char ch;
static int x;
extern long total;
Assigning values to variables
Assignment statement
Assignment operator (=) is used to assign value to a variable.
The syntax is
Variable_name = constant;
Example:- price = 12.50;
ratio = 12.2345;
number=12;
c=‘a’;
It is also possible to assign a value to a variable at the time the variable is decalred. This takes
the following form:
Datatype variable-name=constant;
Ex:
1) int final_value=100;
2) char yes = ‘x’;
3) double balance = 75.84.
The process of giving initial values to variables is called initialization. C permits the
initialization of more than one variable in one statement using multiple assignment operators.
For example the statement
P=q=s=0;
X=y=z=Max; are valid.
Defining symbolic constants
 We often use certain unique constants in a program. These constants may appear
repeatedly in a number of places in the program. One example of such a constant is
3.142, representing the value of the mathematical constant “pi”.
 Modifiability: We may like to change the value of “pi” from 3.142 to 3.145 to
improve the accuracy of calculations.
 Understandability: When a numeric value appears in a program. Its use is not
always clear, especially when the same value mean different things in different
place.
A symbolic constant is defined by writing
#define symbolic_name value of constant
Example: #define STRENGTH 100
#define PASS_MARKS 50
#define MAX 200
#define PI 3.14
It is also known as symbolic name or constant identifier.
Following are the rules apply to symbolic constants.
1. No blank space between the sign ‘#’ and word ‘define’ is permitted
2. ‘#’ must be the first character in the line
3. A blank space is required between #define and symbolic name and value
4. #define statement must not end with semicolon
5. After definition the constant should not assign any value further
6. Symbolic names are not defined for data types
7. #define statement may appear anywhere in the program
Operators and Expressions
 An operator is a symbol that tells the computer to perform certain mathematical or
logical manipulations.
 Operators are used in programs to manipulate data and variables.
 They usually form a part of the mathematical of logical expressions.
C operators can be classified into a number of categories. They include:
1) Arithmetic operators
2) Relational operators
3) Logical operators
4) Assignment operators
5) Increment and decrement operators
6) Conditional operators.
7) Bitwise operators
8) Special operators
ARITHMETIC OPERATORS
 Arithmetic operators are used to perform arithmetic calculations.
Operator Meaning
+
-
*
/
%
Addition
Subtraction
Multiplication
Division
Modulo division - Remainder after
integer division
Example
1) a-b 2) a+b 3) a*b 4) p%q
Integer Arithmetic:
When both the operands in a single arithmetic expression are integers, the expression is
called an integer expression and the operation is called integer arithmetic.
For a = 14 and b = 4, we have the following results :
a - b = 10, a + b = 18, a * b = 56
a / b = 3 (decimal part truncated), a % b = 2 (reminder of division)
Real Arithmetic
An arithmetic operation involving only real operands is called Real arithmetic.
Examples:
x = 6.0 / 7.0 = 0.857143
y = 1.0 / 3.0 = 0.333333
z = -2.0 / 3.0 = -0.666667
Mixed mode arithmetic:
When one of the operands is real and the other is integer, the expression is called a mixed mode
arithmetic expression.
It either operand is of the real type, then only real operation is preformed and the result is
always a real number. Thus
15 / 10.0 = 1.5 where as 15 / 10 = 1
Relational Operators
 Comparisons can be done with the help of relational operators.
 The expression containing a relational operator is termed as a relational expression.
 The value of a relational expression is either one or zero.
Operators Meaning
<
<=
>
>=
==
!=
is less than
is less than or equal to
is greater than
is greater than or equal to
is equal to
is not equal to
Example
Ex: 1. 4.5 <= 10 true
2. 4.5 < -10 false
3. a+b == c+d true (if a+b == c+ d)
Logical operators
Logical operators are used to combine two or more relational expressions C has three logical
operators, which are given in the following table.
 C has the following three logical operators.
Operators Meaning
&&
||
!
(Logical AND)
(Logical OR)
(Logical NOT)
Truth table for logical AND operators
-----------------------------
op1 op2 op1&&op2
----------------------
T T T
T F F
F T F
F F F
Truth for logical OR operator
---------------------
op1 op2 op1||op2
-----------------------
T T T
T F T
F T T
F F F
Truth table for NOT operator
----------------------------
op1 !op1
---------------
T F
F T
Assignment operators
The assignment operator (=) is used to assign a value to a variable.
The general form is
variable = expression;
The expression is first evaluated, and then its resulting value is assigned to the variable.
Compound Assignment operator.
C supports five additional assignment operators.
The General form is
-------------------
variable operator=expression;
C contains the following five compound assignment operators.
+=, - =, *=, /=, %=
Simple Statements Assignment Operators
Statements
a=a+1
a=a–1
a = a * (n+1)
a = a / (n+1)
a=a%b
a + =1
a -=1
a *= n + 1
a /= n + 1
a %= b
Increment and decrement operators
C has two very useful operators not generally found in many other languages. These are the
increment and decrement operators: ++ and --
The operator ++ adds 1 to the operand while -- subtracts 1. Both are unary operators and
are used in the following form.
++m or m++;
--m or m--;
When used as a standalone expression statement,++m and m++ are
both equivalent to the assignment
m=m+1;
similarly, the expression statement --m and m-- are both equivalent to the assignment
m=m-1;
While the pre-increment ++m and post increment m++ mean the same
thing when they form statements independently they behave differently when they are used in
expression on the right hand side of an assignment statement.
Example:
n=++m; this statement is equivalent to two statements
m=m+1;
n=m;
If m=6,then
m=7
n=7
Similarly , the statement n=m++ is equivalent to two statements
n=m;
m=m+1;
if m=6, then n=6 and m=7
Similar is the case for pre decrement & post decrement operators.
Conditional Operator
 A ternary operator pair “?:” is available in C to construct conditional expression.
Syntax
Condition? exp1: exp2;
Here exp1 is evaluated first. If it is true then the expression exp2 is evaluated and
becomes the value of the expression. If exp1 is false then exp3 is evaluated and its value
becomes the value of the expression.
Example
if(a>b)
x = a;
else
x = b;
It is equal to same as
(a>b)?( x = a):(x=b);
Bitwise Operators
 C supports bitwise six bit operators
Operator Meaning
&
|
^
<<
>>
~
Bitwise AND
Bitwise OR
Bitwise XOR
Shift left
Shift right
One’s complement
Example
1) C=a&b;
2) C=a|b;
3) C=a^b;
4) X<<=3;
5) X>>=2;
Special operators
Pointer operator(*)
The pointer operator is used to get the content of the address operator pointing to a particular
memory element.
Address operator(&)
The address operator & is used to get the address of the variable.
Sizeof operator
The sizeof operator gives the size of its operand in bytes.
sizeof(operand);
Examples :
Sizeof(a); //here it return 2 byte if a is of type integer
Sizeof(2.5); //here it return 4 bytes because 2.5 is float
Sizeof(double) //here it returns 8 bytes
Comma operator(,)
 The comma operator can be used to link related expression together.
 The expressions are evaluated left to right.
 The value of the right most expression is the value of the combined expression.
Example :
z = (x = 10, y = 5 , x + y);
First the value of 10 is assigned to x, then value of 5 is assigned to y.
Finally the value of x + y (10+5=15)is assigned to z
 The comma operator is used initialize/increment more than one variable in the for loop.
Ex: for(n=1,m=10,n<=m;n++,m++)
Arithmetic Expression
• An arithmetic expression is a combination of variables, constants and operators arranged
as per the syntax of the language.
Example:
a*x + y;
length*breadth;
(m+n+*((x+y);
Evaluation of Expressions
• Expression are evaluated using an assignment statement of the form
variable = expression;
Examples:
Precedence of Arithmetic Operators
 An arithmetic expression without parenthesis will be evaluated from left to right using
the rules of precedence of operators.
 There are two distinct priority levels of arithmetic operators in C.
High Priority * / %
Low Priority + -
 For example:
8+9*2–10 = 16
Rules for evaluation of expression
1. First parenthesized sub expression from left to right are evaluated.
2. If parentheses are nested, the evaluation begins with the innermost sub expression
3. The precedence rule is applied in determining the order of application of operators in
evaluating sub expressions
4. The associatively rule is applied when 2 or more operators of the same precedence level
appear in a sub expression.
5. Arithmetic expressions are evaluated from left to right using the rules of precedence
6. When parentheses are used, the expressions within parentheses assume highest priority
Mathematical functions
 Mathematical functions such as cos,sin,sqrt,log etc. are frequently used in real-life
problems.
 For use these math functions we have to use math library file #include<math.h> in the
beginning of the program.
The table below shows the mathematical functions
Note:
1) x and y should be declared as double
2) In trigonometric and hyperbolic functions, x and y are in radians
3) All the functions return a double.
Managing Input and Output Operations
 Reading, processing and writing of data are three essential functions of a computer
program.
 Most programs take some data as input and display the processed data or result as
output.
 So, we need some methods that can read input and write output on a suitable
input/output medium.
 Input Output operations are useful for program that interact with user, take input from
the user and print messages.
 C hasn’t any built-in input/output statements as part of its syntax.
 All of input/output operations are carried out through standard input/output functions
getchar( ), putchar( ),scanf( )printf( )
 To use input and output functionality in your program, you need to include the header
file #include <stdio.h>
Reading a Character – getchar() function
The getchar() function is used to read a single character from the keyboard.
The general form is,
Var_name= getchar();
Example:
char name;
name=getchar();
 getchar() can be used inside a loop with proper terminating condition, to accept
multiple characters.
Character related functions
we have to include the header file <ctype.h>
1.isalnum(c) - Is c an alphanumeric character?
2.isalpha(c) – Is c an alphabetic character?
3. isdigit(c) – Is c a digit?
4. islower(c) – Is c a lower case letter?
5. isprint(c) –Is c a printable character?
6. isspace(c) –Is c a white space character?
7. isupper(c) – Is c an upper case letter?
Writing a character – putchar() function
The putchar() function writes a single character to the screen.
The general form is,
putchar (variable name);
For Example, a='x'
putchar(a); will display the character 'x' on the screen.
Examples:
putchar(65); /* displays character A*/
putchar('n'); /* outputs a new line character to the screen*/
putchar('a');/* displays a */
Example
# include <stdio.h>
# include <ctype.h>
main()
{
int l,u;
l = getchar();
u = toupper(l);
putchar(u);
}
Formatted Input- scanf() function
Formatted function reads integers, floating point values, characters and strings from the
standard input.
The general form is
scanf("format string",arg1,arg2,...argn);
The format string is made up of input format codes, which are preceded by a '%'
sign.arg1,arg2,.......arg n are arguments that represent the individual input data items.
 Each variable name must be preceded by an ampersand(&).
 However, array names should not begin with an ampersand.
 if two or more data items are entered they must be separated by white space characters.
The commonly used scanf format codes are listed below.
Code Meanings
%c read a single character
%d read a decimal integer
%e read a floating point value
%f read a floating point value
%g read a floating point value
%h read a short integer
%i read decimal, hexadecimal or octal integer
%o read an octal integer
%s read a string
%u read an unsigned decimal integer
%x read a hexadecimal integer
%[....] read a string of word(s)
String Input and Output Functions
The functions gets( ) and puts ( ) are used to read and write strings of characters at the
console.
Each of these functions accepts a single argument. The arguments must be a string (i.e)
character array.
gets()
syntax: gets(s);
This function is used to read a string of characters including blank from the
keyboard and put the string into the character array s.
Input is terminated when a carriage return is typed before returning, the gets( ) function
appends the null character to the stored set of characters.
Example
char message[80];
gets(message);
puts( )
syntax: puts(s);
This function writes its string argument on the screen.
A puts( ) recognizes the back slash codes such as n for new line.
The argument can be the text to be displayed itself; the text should be enclosed with in
double quotes.
The puts( ) function automatically sends a new line escape sequence to the terminal after
the string has been printed.
Example
1. puts(message);
2. puts("n welcome to c n");
Decision Making and Branching
Introduction
-----------------
 A C program is a set of statements, which are normally executed sequentially in the
order in which they appear.
 However, in practice, we have a number of situations, where we may have to change
the order of execution of statements based on certain conditions or repeat a group of
statements until certain specified conditions are met.
 This involves a kind of decision making to see whether a particular condition has
occurred or not and then direct the computer to execute certain statements accordingly.
 When a program breaks the sequential flow and jumps to another part of the code, it is
called branching.
C language includes such decision making capabilities and supports the following statements
known as control or decision making statements to implement branching.
1. if statement.
2. Switch statement.
DECISION MAKING WITH IF STATEMENT
-------------------------------------
The if statement is a powerful decision making statement and is used to control the flow of
execution of statements.
The if statement may be implemented in different forms depending on the complexity of
conditions to be tested.
1. Simple if statement
2. if..else statement
3. Nested if..else statement
4. else if ladder.
1.Simple if statement
-------------------
The general format of simple if statement is
if (condition)
{
statement-block;
}
statement-x;
The statement block may be a single statement or a group of statements. If the
condition is true, the statement block will be executed, otherwise the statement-block will be
skipped and the execution jumps to the statement-x. Note the parenthesis are required around
the condition.
Examples
1) if (n%d ==0) printf(" %d is divisible by%dn",n,d);
2) if (weight<50 && height > 170) count =count+1;
3) if (x>y)
{
temp = x;
x=y;
y= temp;
}
2. if...else statement
The if-else statement is an extension of the simple if statement.
This statement executes one of two alternative statements according
to the value of the specified condition. The general form is
if (condition)
{
True-block statements;
}
else
{
False-block statements;
}
statement-x;
If the condition is true, then the true block statements immediately following the
if statement are executed. Otherwise the false- block statements are executed. In both cases the
control is transferred subsequently to the statement-x.
Examples
--------
1) if (n%d == 0)
printf("%d is divisible by%dn",n,d);
else
printf("%d is not divisible by %dn",n,d);
2) if (ans =='Y'||ans =='y')
printf("you are enrolledn");
else
printf("you are not enrolledn");
3. Nested if..else statements
When a series of decisions are involved, we may have to use more
than one if..else statements in nested form as follows.
if (condition-1)
{
if (condition-2)
{
statements-1;
}
else
{
statement-2;
}
else
{
statement-3;
}
statement-x;
If condition-1 is false, the statement-3 will be executed, otherwise it continues to perform the
second test. If the condition-2 is true the statement-1 will be executed; otherwise statement-2
will be executed and then control will be transferred to the statement-x.
Example
if(d>0)
if(n%d == 0)
printf("%d divides %dn",d,n);
else
printf("%d does not divide%dn",d,n);
else
printf("%d does not divide%dn");
To parse the statement the complier uses the following "else" matching rule.
Match each else with last unmatched if.
4.The else if ladder
A common programming construct in C is the if-else-if ladder,
sometimes called the if-else-if staircase because of its appearance.
The general format is.
if(condition)
statement-1;
else
if (condition-2)
statement-2;
else
if (condition-3)
statement-3;
.
.
.
.
else
statement;
The conditions are evaluated from the top to down. As soon as the true condition is found,the
statement associated with it is executed and the rest of the ladder is bypassed. If none of the
conditions are true. the final else is executed. If the final else is not present no action takes place
if all other conditions are false.
Example
if (marks>79)
grade ="honors";
else
if (marks>59)
grade ="First Division";
else
if(marks > 49)
grade ="Second Division";
else
if(marks>39)
grade ="Third Division";
else
grade="FAIL";
PROGRAMMING EXAMPLES:
-----------------------
1.Write a program to solve the quadratic equation
# include<stdio.h>
# include<math.h>
# include<conio.h>
/* Program for Quadratic Equation */
void main()
{
float a,b,c,d,r1,r2,rp,ip;
clrscr();
printf("ttquadratic Equationnn");
printf("Enter the Numbers: ");
scanf("%f%f%f",&a,&b,&c); d=b*b-4.0*a*c;
if(d<0)
{
printf("nImaginary Roots:n");
rp=-b/2*a;
ip=sqrt(-d)/(2*a);
printf("%f+i%fn",rp,ip);
printf("%f-i%fn",rp,ip);
}
if(d==0)
{
printf("nEqual Roots:n");
r1=-b/2*a;
r2=r1;
printf("R1=%f R2=%f",r1,r2);
}
if(d>0)
{
printf("nReal And Unequal Roots:n");
r1=(-b+sqrt(d))/(2*a);
r2=(-b-sqrt(d))/(2*a);
printf("R1=%f R2=%f",r1,r2);
}
getch();
}
3. Write a Program to read the marks obtained by a student and
declare the result.
# include<stdio.h>
# include<conio.h>
void main()
{
int m1,m2,m3,tot,status;
clrscr();
printf("Enter The Mark");
scanf("%d%d%d",&m1,&m2,&m3); if(m1<40 || m2<40 || m3<40)
printf("FAIL");
else if(m1>=40 && m1<=50 || m2>=40 && m3<=50 || m3>=40 && m3<=50)
printf("PASS");
else if(m1>=60 && m2>=60 &&m3>=60)
printf("FIRST CLASS");
tot=m1+m2+m3;
printf("nTOTAL MARK IS %d",tot);
getch();
}
THE SWITCH STATEMENT:
The switch statement is an appropriate statement when a
number of possible states for a variable have to be evaluated at one
time.
The syntax is
switch(expression)
{
case value-1 :block-1;
break;
case value-2 :block-2;
break;
case value-n :block-n;
break; default: default block;
break;
}
This statement evaluates the expression and then looks for its value among the case values. If
the value is found among the case values listed, then statements in that block are executed.
Otherwise if there is a default, then the program branches to that block. Note that the expression
must evaluate to an integer type and that the case values must be integer constants (which
include characters). Note that if break statement is omitted, execution
will continue until a break statement is found or switch ends.
Example
-------
switch(c)
{
case 1:printf("enter a decimal numbern");
scanf("%d",&i);
printf("n octal equivalent is %on",i);
break;
case 2:printf(" enter a decimal numbern");
scanf("%d",&i);
printf("n hexa decimal equivalent is %h n");
break;
default:printf("ERROR:base is out of rangen");
}
PROGRAMMING EXAMPLES
1. Write a program that simulates a simple calculator. It reads two integers and a character. If
the character is a + , the sum is printed, if the character is -, the difference is printed.
If the character is a * ,the product is printed. If the character is /, the quotient is printed, and if it
is a %, the remainder is printed. Use switch statement.
#include <stdio.h>
void main()
{
int x,y;
char op;
printf("enter two integers:");
scanf("%d%dn",&x,&y);
printf("enter an operator:");
scanf("%c",&op);
switch(op) {
case'+':printf("%dn",x+y);
break;
case'-':printf("%dn",x-y);
break;
case'*':printf("%dn",x*y);
break;
case'/':printf("%dn",x/y);
break;
case'%':printf("%dn",x%y);
break;
}
}

More Related Content

Similar to C and DS -unit 1 -Artificial Intelligence and ML.docx (20)

PPTX
unit2.pptx
sscprep9
 
PPTX
C programming Training in Ambala ! Batra Computer Centre
jatin batra
 
PPTX
Introduction to C Programming
Preeti Kashyap
 
PPT
history of c.ppt
arpanabharani
 
PPTX
4 Introduction to C.pptxSSSSSSSSSSSSSSSS
EG20910848921ISAACDU
 
PPTX
C Program basic concepts using c knoweledge
priankarr1
 
PDF
C PADHLO FRANDS.pdf
RishiBhardwaj65
 
PPTX
C language ppt
Ğäùråv Júñêjå
 
PPTX
Chapter1.pptx
SREEVIDYAP10
 
PPTX
Copy of UNIT 2 -- Basics Of Programming.pptx
rahulrajbhar06478
 
PPT
Lecture 01 2017
Jesmin Akhter
 
PPTX
Msc prev completed
mshoaib15
 
PPTX
Msc prev updated
mshoaib15
 
PPT
C Language
Aakash Singh
 
PDF
Unit 2 introduction to c programming
Mithun DSouza
 
PPTX
unit 1 cpds.pptx
madhurij54
 
PPTX
structure of a c program - slideshare.pptx
PoovizhiP1
 
PPT
All C ppt.ppt
JeelBhanderi4
 
PPTX
C introduction
AswathyBAnil
 
PDF
Basic of the C language
Sachin Verma
 
unit2.pptx
sscprep9
 
C programming Training in Ambala ! Batra Computer Centre
jatin batra
 
Introduction to C Programming
Preeti Kashyap
 
history of c.ppt
arpanabharani
 
4 Introduction to C.pptxSSSSSSSSSSSSSSSS
EG20910848921ISAACDU
 
C Program basic concepts using c knoweledge
priankarr1
 
C PADHLO FRANDS.pdf
RishiBhardwaj65
 
C language ppt
Ğäùråv Júñêjå
 
Chapter1.pptx
SREEVIDYAP10
 
Copy of UNIT 2 -- Basics Of Programming.pptx
rahulrajbhar06478
 
Lecture 01 2017
Jesmin Akhter
 
Msc prev completed
mshoaib15
 
Msc prev updated
mshoaib15
 
C Language
Aakash Singh
 
Unit 2 introduction to c programming
Mithun DSouza
 
unit 1 cpds.pptx
madhurij54
 
structure of a c program - slideshare.pptx
PoovizhiP1
 
All C ppt.ppt
JeelBhanderi4
 
C introduction
AswathyBAnil
 
Basic of the C language
Sachin Verma
 

Recently uploaded (20)

PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PPTX
Soil and agriculture microbiology .pptx
Keerthana Ramesh
 
PPTX
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PPTX
HYDROCEPHALUS: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
PPTX
grade 5 lesson ENGLISH 5_Q1_PPT_WEEK3.pptx
SireQuinn
 
PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PPT
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPTX
Views on Education of Indian Thinkers Mahatma Gandhi.pptx
ShrutiMahanta1
 
PDF
LAW OF CONTRACT ( 5 YEAR LLB & UNITARY LLB)- MODULE-3 - LEARN THROUGH PICTURE
APARNA T SHAIL KUMAR
 
PPTX
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PPTX
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PPTX
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PDF
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
Soil and agriculture microbiology .pptx
Keerthana Ramesh
 
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
HYDROCEPHALUS: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
grade 5 lesson ENGLISH 5_Q1_PPT_WEEK3.pptx
SireQuinn
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
Views on Education of Indian Thinkers Mahatma Gandhi.pptx
ShrutiMahanta1
 
LAW OF CONTRACT ( 5 YEAR LLB & UNITARY LLB)- MODULE-3 - LEARN THROUGH PICTURE
APARNA T SHAIL KUMAR
 
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
Dimensions of Societal Planning in Commonism
StefanMz
 
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
Ad

C and DS -unit 1 -Artificial Intelligence and ML.docx

  • 1. Introduction to C language  C is a general-purpose, procedural programming language developed by Dennis Ritchie at AT &T (American Telephone and Telegraph Company )Bell Labs in the early 1970s  General-Purpose Language: C is a versatile programming language used for various applications, from system software to application software.  Procedural Language: Emphasizes procedures or routines (functions) to perform tasks.  C was originally created to develop an operating system called UNIX, which was later almost entirely rewritten in the C programming language. History of C Initially, C language was developed to be used in UNIX operating system. It inherits many features of previous languages. Let's see the programming languages that were developed before C language. 1. In 1960,The root of all model language is ALGOL (ALGOrithmic Language) introduced . ALGOL gave the concept of structured programming to the computer science community. 2. In 1967s Martin Richards developed a language called as BCPL ( Basic Combined Programming Language) primarily form writing system software. 3. In 1970s Ken Thomson created a language using many feature of BCPL and called it simply ‘B’. B was used to create early versions of UNIX operating system at Bell laboratories. 4. In 1972, C language was developed by Dennis Ritchi from ALGOL, BCPL and B at the Bell Laboratories. Which referred as "Traditional C" 5. In 1978, the C language gained popularity after the release of the book 'The C Programming Language' by Kernighan and Dennis Ritchie, leading to it being known as 'K&R C'." 6. In 1983, ANSI (American National Standards Institute) appointed a technical committee to define a standard for C. 7. In 1989, the ANSI committee approved a version of C that is now known as ANSI C. 8. In 1990, it was approved by the International Standards Organization (ISO). This version of C is also referred to as ANSI ISO C. 9. In 1999, the C standardization committee added several new features to enhance the language's usefulness. This version is known as C99. Importance of C 1. Simple: C language is simple and easy to learn, with straightforward syntax and many built-in functions and data types. 2. Efficient and Fast: Programs in C are efficient and faster than those in BASIC, thanks to its variety of data types and powerful operators. 3. Robust: C is robust with a rich set of built-in functions and operators, making it suitable for complex programs and both system software and business applications. 4. Portable: C programs can run on different machines with little or no modification.
  • 2. 5. Supports Structured Programming: C is well-suited for structured programming, making debugging and testing easier by breaking problems into functions or modules. 6. Fixed Number of Keywords: ANSI C has only 32 keywords. 7. Large Standard Library: C has a large standard library for common tasks like input/output, string manipulation, and memory allocation. 8. Extendable or Ability to extend itself: C programs are collections of functions, and you can create and add your own functions to the C library. 9. Middle-Level Language: C supports features of both low-level and high-level languages. Basic Structure of C Programs 1. Documentation Section: Contains comments with the programmer's name, author, and details like date and time, providing an overview of the program. 2. Link Section: Includes header files for functions used in the program, instructing the compiler to link system library functions. 3. Definition Section: Contains symbolic constants (macros). 4. Global Declaration Section: Declares global variables and user-defined functions that can be used anywhere in the program.
  • 3. 5. main() Function Section: Every C program must have a main() function, which includes: a. Declaration Part: Declares variables used in the executable part. b. Executable Part: Contains the actual code to be executed. Enclosed in opening and closing braces, with each statement ending in a semicolon (;). 6. Subprogram Section: Contains user-defined functions called by the main() function to perform specific tasks. CHARACTER SET C characters are grouped into the following categories. 1. Letters 2. Digits 3. Special Characters 4. White Spaces Letters Uppercase A….Z Lowercase a…..z Digits All decimal digits 0…..9 Special characters , Comma & ampersand . Period ^ Caret ; Semicolon * Asterisk : Colon - Minus ? Question mark + Plus sign ‘Apostrophe < Less than “Quotation mark > Greater than ! Exclamation ( Left parenthesis | Vertical Bar ) Right parentheses / Slash [ Left bracket Back slash ] Right bracket ~ Tilde { Left brace _ Underscore } Right brace $ Dollar sign # Number sign % Percent sign White Spaces Blank Space Horizontal Tab
  • 4. Carriage Return New Line Form Feed Trigraph characters: • C introduces the concept of trigraph sequences to provide a way to enter certain characters that are not available on some keywords. • Each trigraph sequence consists of three characters, 2 question marks followed by another character. Trigraph Sequence Translation ??= # Number sign ??( [ Left bracket ??) ] Right bracket ??< { Left brace ??> } Right brace ??! | Vertical bar ??/ Back slash ??’ ^ Caret ??- ~ Tilde C tokens: • In a C program the smallest individual units known as C tokens. • C has 6 types of tokens namely: 1) Keywords 2) Identifiers 3) Constants 4) Strings 5) Special symbols 6) Operators. Keywords and identifiers Keywords  Keywords serve as the building blocks for program statements. C TOKENS Keywords Identifiers Constants Strings Special Symbols Operators
  • 5.  All keywords have a fixed meaning and cannot be changed.  Keywords cannot be used as normal identifier names.  Few Examples of keywords used in C are listed below int break goto char switch void The standard keywords are: auto break case character const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void while Identifiers  Identifier refers to the name of variables, functions and arrays.  These are user defined names and consists of a sequence of letters and digits. Rules for Identifiers: 1. First character must be an alphabet. 2. Must consist of only letters, digits or underscore. 3. Only first 31 characters are significant. 4. Cannot use keyword. 5. Must not contain white space. Constants  Constants refer to fixed values that do not change during the execution of a program.
  • 6. Integer Constants: • An integer constant refers to a sequence of digits. • There are 3 types of integers namely: Decimal integer, octal integer and hexadecimal integer. • Decimal integer consist of a set of digits 0 through 9, precceded by an optional – or + sign. • An octal integer constant consists of any combination of digits from the set 0 through 7. with a leading 0 Eg: 037,0, 0456. • A sequence of digits preceded by 0x or 0X is considered as hexadecimal integer. • They may include alphabets A through F or f. • Letter A through F represents numbers 10 to 15. Real Constants: Certain quantities that vary continuously, such as distances, heights etc., are represented by numbers containing functional parts like 17.548.Such numbers are called real (or floating point) constants. • A real number may be expressed in exponential notation. SYNTAX: mantissa e exponent. • Mantissa can be either real number expressed in decimal notation or an integer. • Exponent is an integer number with an optional + or – sign. • The letter ‘e’ separating the mantissa and the exponent, it can be written either lower case or upper case. SYNTAX: 0.65e4,12e-2. • Exponential notation is useful for representing numbers that are either very large or very small in magnitude. Constants Numeric Constants Integer Constants Real Constants Character Constants Single character constants String constants
  • 7. Single Character Constants: • A single character constant contains a single character enclose in a pair of single quote marks. • Eg: ‘5’,’x’. • Character constant ‘5’ is not same as number 5. • Character constants have integer values known as ASCII values. • Statement: printf (“%d”, ’a’); would print number 97, the ASCII value of letter ‘a’. • Since each character constant represent an integer value, it is possible to perform arithmetic operations on character constants. String Constants: • A string constant is a sequence of characters enclosed in double quotes. • Characters may be letters, numbers, special characters and blank spaces. Eg: “hello”, “1987”, “?...!”. • Character constant is not equivalent to single character string constant. Back Slash Character Constants: • C supports some special back slash character constants that are used in output functions. • These characters combinations are known as escape sequences. • Back slash character constants are: ‘a’ audible alert; ‘b’ backspace; ‘f’ form feed; ‘n’ newline; ‘r’ carriage return; ‘t’ horizontal tab; ‘v’ vertical tab; ‘”single quote, ‘?’ question mark; ‘’ backslash; ‘0’ null. Variables • A variable is a data name that may be used to store a data value. • A variable may take different values at different times during execution. • A variable can be chosen by the programmer in a meaningful way. Rules For Specifying Variables: 1. They must begin with a letter. Some systems may permit underscore as first character. 2. Uppercase and lowercase are significant. The variable TOTAL is different from total and Total. 3. It should not be keyword. 4. Whitespace is not allowed. 5. Length should be normally more than 8 characters are treated as significant by many compilers. Examples of valid variables are: john, x1,T_raise, first_tag. Examples of invalid variables are: 123,(area),25th ,price$, %.
  • 8. DATA TYPES • C language is rich in its data types. • Storage representations and machine instructions to handle constants differ from machine to machine. • The variety of data types allow to select the type appropriate to the needs of the application as well as machine. C supports 3 classes of data types: 1) Primary data types 2) Derived data types 3) User defined data types. • All C compilers support 5 fundamental data types namely: integer (int), character (char), floating point (float), double-precision floating point (double) and void. • Many of them also offer extended data types such as long int, int , long double. Data type Range of values char -128 to 127 int -32768 to 32767 float -3.4e+8 to 3.4e+8 Double 1.7e-308 to 1.7e+308. Integer Types: • Integers are whole numbers with a range of values supported by particular machine. • Integers occupy one word storage generally and since the word sizes of machine vary the size of integer that can be stored depends on computer. • If we use 16-bit word length, the size of integer value is limited to range -32768 to 32767. • If we use 32-bit word length can store an integer ranging from -2147483648 to 2147483647.
  • 9. • In order to provide control over range of numbers and storage space C has 3 classes of integer storage namely: short int, int, long int in both signed and unsigned. Floating Point Type: • Floating point numbers are stored in 32bits, with 6 digit precision. • Floating point numbers are defined by keyword “float”. • When accuracy is provided by a float number is not sufficient, double can be used to define number. • A double data type number uses 64 bits giving a precision of 14 digits. • These are known as double precision number. • Double data type represent the same data type that float represents but with greater precision. Void Type: • Void type has no values. This is used to specify the type of functions. • The type of function is said to be void when it doesn't return any value to the calling function. Character Type: • A single character can be defined as a character (char) type data. • Characters are usually store in one byte of internal storage. • Qualifier signed or unsigned may be used in char explicitly. Unsigned characters have values between 0 and 255, signed characters have values from -128 to 127 Declaration of variables After designing suitable variable names, we must declare them to the compiler. Declaration does two things: 1. It tells the compiler what the variable name is. 2. It specifies what type of data the variable will hold. Primary Type Declaration: - A variables can be used to store a value of any data types. The syntax is Data-type v1,v2…..vn; Where v1,v2..vn are different variable name. Example:- int count; int number, total; double ratio; float price;
  • 10. char c; where int, double, float and char are data type. User-Defined Types Declaration: There are user defined data types in C i) Typedef ii) enum Typedef : C supports a feature known as “type definition” that allows users to define an identifiers that would represent an existing data type. It takes the general form: typedef type identifiers; Example: typedef int units; typedef float marks; Here, units symbolizes int and marks symbolizes float. They can be later used to declare variables as follows: units batchl, batch2; marks height; Enum: Another user-defined data type is enumerated data type provided by ANSI standard. Syntax: enum identifier {val 1, val 2, …...val n}; The identifier is a user-defined enumerated data type which can be used to declared variables that can have one of the values enclosed within the braces. Ex: enum day { mon, tue , ……sat}; enum day week-st, week-end; Declaration of storage classes Variables in C can have not only data type but also storage class that provide information about their location and visibility. The storage class decides the portion of the program within which the variables are recognized. C supports the following Storage class specifiers: 1. auto: local variable known only to the function where it is declared default is auto. 2. Static: local variable that exists and retains its value even after control is transferred to the calling function. 3. extern: global variable known to all functions in the file 4. register: local variable, which is stored in the register.
  • 11. Example: auto int count; register char ch; static int x; extern long total; Assigning values to variables Assignment statement Assignment operator (=) is used to assign value to a variable. The syntax is Variable_name = constant; Example:- price = 12.50; ratio = 12.2345; number=12; c=‘a’; It is also possible to assign a value to a variable at the time the variable is decalred. This takes the following form: Datatype variable-name=constant; Ex: 1) int final_value=100; 2) char yes = ‘x’; 3) double balance = 75.84. The process of giving initial values to variables is called initialization. C permits the initialization of more than one variable in one statement using multiple assignment operators. For example the statement P=q=s=0; X=y=z=Max; are valid.
  • 12. Defining symbolic constants  We often use certain unique constants in a program. These constants may appear repeatedly in a number of places in the program. One example of such a constant is 3.142, representing the value of the mathematical constant “pi”.  Modifiability: We may like to change the value of “pi” from 3.142 to 3.145 to improve the accuracy of calculations.  Understandability: When a numeric value appears in a program. Its use is not always clear, especially when the same value mean different things in different place. A symbolic constant is defined by writing #define symbolic_name value of constant Example: #define STRENGTH 100 #define PASS_MARKS 50 #define MAX 200 #define PI 3.14 It is also known as symbolic name or constant identifier. Following are the rules apply to symbolic constants. 1. No blank space between the sign ‘#’ and word ‘define’ is permitted 2. ‘#’ must be the first character in the line 3. A blank space is required between #define and symbolic name and value 4. #define statement must not end with semicolon 5. After definition the constant should not assign any value further 6. Symbolic names are not defined for data types 7. #define statement may appear anywhere in the program Operators and Expressions  An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations.  Operators are used in programs to manipulate data and variables.  They usually form a part of the mathematical of logical expressions. C operators can be classified into a number of categories. They include: 1) Arithmetic operators 2) Relational operators 3) Logical operators 4) Assignment operators 5) Increment and decrement operators 6) Conditional operators.
  • 13. 7) Bitwise operators 8) Special operators ARITHMETIC OPERATORS  Arithmetic operators are used to perform arithmetic calculations. Operator Meaning + - * / % Addition Subtraction Multiplication Division Modulo division - Remainder after integer division Example 1) a-b 2) a+b 3) a*b 4) p%q Integer Arithmetic: When both the operands in a single arithmetic expression are integers, the expression is called an integer expression and the operation is called integer arithmetic. For a = 14 and b = 4, we have the following results : a - b = 10, a + b = 18, a * b = 56 a / b = 3 (decimal part truncated), a % b = 2 (reminder of division) Real Arithmetic An arithmetic operation involving only real operands is called Real arithmetic. Examples: x = 6.0 / 7.0 = 0.857143 y = 1.0 / 3.0 = 0.333333 z = -2.0 / 3.0 = -0.666667 Mixed mode arithmetic: When one of the operands is real and the other is integer, the expression is called a mixed mode arithmetic expression. It either operand is of the real type, then only real operation is preformed and the result is always a real number. Thus 15 / 10.0 = 1.5 where as 15 / 10 = 1
  • 14. Relational Operators  Comparisons can be done with the help of relational operators.  The expression containing a relational operator is termed as a relational expression.  The value of a relational expression is either one or zero. Operators Meaning < <= > >= == != is less than is less than or equal to is greater than is greater than or equal to is equal to is not equal to Example Ex: 1. 4.5 <= 10 true 2. 4.5 < -10 false 3. a+b == c+d true (if a+b == c+ d) Logical operators Logical operators are used to combine two or more relational expressions C has three logical operators, which are given in the following table.  C has the following three logical operators. Operators Meaning && || ! (Logical AND) (Logical OR) (Logical NOT) Truth table for logical AND operators ----------------------------- op1 op2 op1&&op2 ---------------------- T T T T F F F T F F F F Truth for logical OR operator --------------------- op1 op2 op1||op2 ----------------------- T T T T F T
  • 15. F T T F F F Truth table for NOT operator ---------------------------- op1 !op1 --------------- T F F T Assignment operators The assignment operator (=) is used to assign a value to a variable. The general form is variable = expression; The expression is first evaluated, and then its resulting value is assigned to the variable. Compound Assignment operator. C supports five additional assignment operators. The General form is ------------------- variable operator=expression; C contains the following five compound assignment operators. +=, - =, *=, /=, %= Simple Statements Assignment Operators Statements a=a+1 a=a–1 a = a * (n+1) a = a / (n+1) a=a%b a + =1 a -=1 a *= n + 1 a /= n + 1 a %= b Increment and decrement operators C has two very useful operators not generally found in many other languages. These are the increment and decrement operators: ++ and -- The operator ++ adds 1 to the operand while -- subtracts 1. Both are unary operators and are used in the following form. ++m or m++; --m or m--; When used as a standalone expression statement,++m and m++ are both equivalent to the assignment m=m+1;
  • 16. similarly, the expression statement --m and m-- are both equivalent to the assignment m=m-1; While the pre-increment ++m and post increment m++ mean the same thing when they form statements independently they behave differently when they are used in expression on the right hand side of an assignment statement. Example: n=++m; this statement is equivalent to two statements m=m+1; n=m; If m=6,then m=7 n=7 Similarly , the statement n=m++ is equivalent to two statements n=m; m=m+1; if m=6, then n=6 and m=7 Similar is the case for pre decrement & post decrement operators. Conditional Operator  A ternary operator pair “?:” is available in C to construct conditional expression. Syntax Condition? exp1: exp2; Here exp1 is evaluated first. If it is true then the expression exp2 is evaluated and becomes the value of the expression. If exp1 is false then exp3 is evaluated and its value becomes the value of the expression. Example if(a>b) x = a; else x = b; It is equal to same as (a>b)?( x = a):(x=b);
  • 17. Bitwise Operators  C supports bitwise six bit operators Operator Meaning & | ^ << >> ~ Bitwise AND Bitwise OR Bitwise XOR Shift left Shift right One’s complement Example 1) C=a&b; 2) C=a|b; 3) C=a^b; 4) X<<=3; 5) X>>=2; Special operators Pointer operator(*) The pointer operator is used to get the content of the address operator pointing to a particular memory element. Address operator(&) The address operator & is used to get the address of the variable. Sizeof operator The sizeof operator gives the size of its operand in bytes. sizeof(operand); Examples : Sizeof(a); //here it return 2 byte if a is of type integer Sizeof(2.5); //here it return 4 bytes because 2.5 is float Sizeof(double) //here it returns 8 bytes Comma operator(,)
  • 18.  The comma operator can be used to link related expression together.  The expressions are evaluated left to right.  The value of the right most expression is the value of the combined expression. Example : z = (x = 10, y = 5 , x + y); First the value of 10 is assigned to x, then value of 5 is assigned to y. Finally the value of x + y (10+5=15)is assigned to z  The comma operator is used initialize/increment more than one variable in the for loop. Ex: for(n=1,m=10,n<=m;n++,m++) Arithmetic Expression • An arithmetic expression is a combination of variables, constants and operators arranged as per the syntax of the language. Example: a*x + y; length*breadth; (m+n+*((x+y); Evaluation of Expressions • Expression are evaluated using an assignment statement of the form variable = expression; Examples: Precedence of Arithmetic Operators  An arithmetic expression without parenthesis will be evaluated from left to right using the rules of precedence of operators.  There are two distinct priority levels of arithmetic operators in C. High Priority * / %
  • 19. Low Priority + -  For example: 8+9*2–10 = 16 Rules for evaluation of expression 1. First parenthesized sub expression from left to right are evaluated. 2. If parentheses are nested, the evaluation begins with the innermost sub expression 3. The precedence rule is applied in determining the order of application of operators in evaluating sub expressions 4. The associatively rule is applied when 2 or more operators of the same precedence level appear in a sub expression. 5. Arithmetic expressions are evaluated from left to right using the rules of precedence 6. When parentheses are used, the expressions within parentheses assume highest priority Mathematical functions  Mathematical functions such as cos,sin,sqrt,log etc. are frequently used in real-life problems.  For use these math functions we have to use math library file #include<math.h> in the beginning of the program. The table below shows the mathematical functions Note: 1) x and y should be declared as double
  • 20. 2) In trigonometric and hyperbolic functions, x and y are in radians 3) All the functions return a double. Managing Input and Output Operations  Reading, processing and writing of data are three essential functions of a computer program.  Most programs take some data as input and display the processed data or result as output.  So, we need some methods that can read input and write output on a suitable input/output medium.  Input Output operations are useful for program that interact with user, take input from the user and print messages.  C hasn’t any built-in input/output statements as part of its syntax.  All of input/output operations are carried out through standard input/output functions getchar( ), putchar( ),scanf( )printf( )  To use input and output functionality in your program, you need to include the header file #include <stdio.h> Reading a Character – getchar() function The getchar() function is used to read a single character from the keyboard. The general form is, Var_name= getchar(); Example: char name; name=getchar();  getchar() can be used inside a loop with proper terminating condition, to accept multiple characters. Character related functions we have to include the header file <ctype.h> 1.isalnum(c) - Is c an alphanumeric character? 2.isalpha(c) – Is c an alphabetic character? 3. isdigit(c) – Is c a digit? 4. islower(c) – Is c a lower case letter? 5. isprint(c) –Is c a printable character? 6. isspace(c) –Is c a white space character? 7. isupper(c) – Is c an upper case letter?
  • 21. Writing a character – putchar() function The putchar() function writes a single character to the screen. The general form is, putchar (variable name); For Example, a='x' putchar(a); will display the character 'x' on the screen. Examples: putchar(65); /* displays character A*/ putchar('n'); /* outputs a new line character to the screen*/ putchar('a');/* displays a */ Example # include <stdio.h> # include <ctype.h> main() { int l,u; l = getchar(); u = toupper(l); putchar(u); } Formatted Input- scanf() function Formatted function reads integers, floating point values, characters and strings from the standard input. The general form is scanf("format string",arg1,arg2,...argn); The format string is made up of input format codes, which are preceded by a '%' sign.arg1,arg2,.......arg n are arguments that represent the individual input data items.  Each variable name must be preceded by an ampersand(&).  However, array names should not begin with an ampersand.  if two or more data items are entered they must be separated by white space characters. The commonly used scanf format codes are listed below.
  • 22. Code Meanings %c read a single character %d read a decimal integer %e read a floating point value %f read a floating point value %g read a floating point value %h read a short integer %i read decimal, hexadecimal or octal integer %o read an octal integer %s read a string %u read an unsigned decimal integer %x read a hexadecimal integer %[....] read a string of word(s) String Input and Output Functions The functions gets( ) and puts ( ) are used to read and write strings of characters at the console. Each of these functions accepts a single argument. The arguments must be a string (i.e) character array. gets() syntax: gets(s); This function is used to read a string of characters including blank from the keyboard and put the string into the character array s. Input is terminated when a carriage return is typed before returning, the gets( ) function appends the null character to the stored set of characters. Example char message[80]; gets(message);
  • 23. puts( ) syntax: puts(s); This function writes its string argument on the screen. A puts( ) recognizes the back slash codes such as n for new line. The argument can be the text to be displayed itself; the text should be enclosed with in double quotes. The puts( ) function automatically sends a new line escape sequence to the terminal after the string has been printed. Example 1. puts(message); 2. puts("n welcome to c n"); Decision Making and Branching Introduction -----------------  A C program is a set of statements, which are normally executed sequentially in the order in which they appear.  However, in practice, we have a number of situations, where we may have to change the order of execution of statements based on certain conditions or repeat a group of statements until certain specified conditions are met.  This involves a kind of decision making to see whether a particular condition has occurred or not and then direct the computer to execute certain statements accordingly.  When a program breaks the sequential flow and jumps to another part of the code, it is called branching. C language includes such decision making capabilities and supports the following statements known as control or decision making statements to implement branching. 1. if statement. 2. Switch statement. DECISION MAKING WITH IF STATEMENT ------------------------------------- The if statement is a powerful decision making statement and is used to control the flow of execution of statements.
  • 24. The if statement may be implemented in different forms depending on the complexity of conditions to be tested. 1. Simple if statement 2. if..else statement 3. Nested if..else statement 4. else if ladder. 1.Simple if statement ------------------- The general format of simple if statement is if (condition) { statement-block; } statement-x; The statement block may be a single statement or a group of statements. If the condition is true, the statement block will be executed, otherwise the statement-block will be skipped and the execution jumps to the statement-x. Note the parenthesis are required around the condition. Examples 1) if (n%d ==0) printf(" %d is divisible by%dn",n,d); 2) if (weight<50 && height > 170) count =count+1; 3) if (x>y) { temp = x; x=y; y= temp; } 2. if...else statement The if-else statement is an extension of the simple if statement. This statement executes one of two alternative statements according to the value of the specified condition. The general form is if (condition) { True-block statements; } else { False-block statements; } statement-x; If the condition is true, then the true block statements immediately following the if statement are executed. Otherwise the false- block statements are executed. In both cases the control is transferred subsequently to the statement-x.
  • 25. Examples -------- 1) if (n%d == 0) printf("%d is divisible by%dn",n,d); else printf("%d is not divisible by %dn",n,d); 2) if (ans =='Y'||ans =='y') printf("you are enrolledn"); else printf("you are not enrolledn"); 3. Nested if..else statements When a series of decisions are involved, we may have to use more than one if..else statements in nested form as follows. if (condition-1) { if (condition-2) { statements-1; } else { statement-2; } else { statement-3; } statement-x; If condition-1 is false, the statement-3 will be executed, otherwise it continues to perform the second test. If the condition-2 is true the statement-1 will be executed; otherwise statement-2 will be executed and then control will be transferred to the statement-x. Example if(d>0) if(n%d == 0) printf("%d divides %dn",d,n); else printf("%d does not divide%dn",d,n); else printf("%d does not divide%dn"); To parse the statement the complier uses the following "else" matching rule. Match each else with last unmatched if. 4.The else if ladder A common programming construct in C is the if-else-if ladder,
  • 26. sometimes called the if-else-if staircase because of its appearance. The general format is. if(condition) statement-1; else if (condition-2) statement-2; else if (condition-3) statement-3; . . . . else statement; The conditions are evaluated from the top to down. As soon as the true condition is found,the statement associated with it is executed and the rest of the ladder is bypassed. If none of the conditions are true. the final else is executed. If the final else is not present no action takes place if all other conditions are false. Example if (marks>79) grade ="honors"; else if (marks>59) grade ="First Division"; else if(marks > 49) grade ="Second Division"; else if(marks>39) grade ="Third Division"; else grade="FAIL"; PROGRAMMING EXAMPLES: ----------------------- 1.Write a program to solve the quadratic equation # include<stdio.h> # include<math.h> # include<conio.h> /* Program for Quadratic Equation */ void main() { float a,b,c,d,r1,r2,rp,ip;
  • 27. clrscr(); printf("ttquadratic Equationnn"); printf("Enter the Numbers: "); scanf("%f%f%f",&a,&b,&c); d=b*b-4.0*a*c; if(d<0) { printf("nImaginary Roots:n"); rp=-b/2*a; ip=sqrt(-d)/(2*a); printf("%f+i%fn",rp,ip); printf("%f-i%fn",rp,ip); } if(d==0) { printf("nEqual Roots:n"); r1=-b/2*a; r2=r1; printf("R1=%f R2=%f",r1,r2); } if(d>0) { printf("nReal And Unequal Roots:n"); r1=(-b+sqrt(d))/(2*a); r2=(-b-sqrt(d))/(2*a); printf("R1=%f R2=%f",r1,r2); } getch(); } 3. Write a Program to read the marks obtained by a student and declare the result. # include<stdio.h> # include<conio.h> void main() { int m1,m2,m3,tot,status; clrscr(); printf("Enter The Mark"); scanf("%d%d%d",&m1,&m2,&m3); if(m1<40 || m2<40 || m3<40) printf("FAIL"); else if(m1>=40 && m1<=50 || m2>=40 && m3<=50 || m3>=40 && m3<=50) printf("PASS"); else if(m1>=60 && m2>=60 &&m3>=60) printf("FIRST CLASS"); tot=m1+m2+m3; printf("nTOTAL MARK IS %d",tot);
  • 28. getch(); } THE SWITCH STATEMENT: The switch statement is an appropriate statement when a number of possible states for a variable have to be evaluated at one time. The syntax is switch(expression) { case value-1 :block-1; break; case value-2 :block-2; break; case value-n :block-n; break; default: default block; break; } This statement evaluates the expression and then looks for its value among the case values. If the value is found among the case values listed, then statements in that block are executed. Otherwise if there is a default, then the program branches to that block. Note that the expression must evaluate to an integer type and that the case values must be integer constants (which include characters). Note that if break statement is omitted, execution will continue until a break statement is found or switch ends. Example ------- switch(c) { case 1:printf("enter a decimal numbern"); scanf("%d",&i); printf("n octal equivalent is %on",i); break; case 2:printf(" enter a decimal numbern"); scanf("%d",&i); printf("n hexa decimal equivalent is %h n"); break; default:printf("ERROR:base is out of rangen"); } PROGRAMMING EXAMPLES 1. Write a program that simulates a simple calculator. It reads two integers and a character. If the character is a + , the sum is printed, if the character is -, the difference is printed. If the character is a * ,the product is printed. If the character is /, the quotient is printed, and if it is a %, the remainder is printed. Use switch statement. #include <stdio.h> void main()
  • 29. { int x,y; char op; printf("enter two integers:"); scanf("%d%dn",&x,&y); printf("enter an operator:"); scanf("%c",&op); switch(op) { case'+':printf("%dn",x+y); break; case'-':printf("%dn",x-y); break; case'*':printf("%dn",x*y); break; case'/':printf("%dn",x/y); break; case'%':printf("%dn",x%y); break; } }