Ed Programming Laboratories in USA (AT & T) - Language. C Programming Language Was Developed in The Year of 1972 by Denni
Ed Programming Laboratories in USA (AT & T) - Language. C Programming Language Was Developed in The Year of 1972 by Denni
Link to Session
ed programming
C i s a structured p r o g r a m m i n g language. It i s also k n o w n a s function orientat Planner (SP):S.No….of SP
s Ritchie at Bell
language. C programming language was developed in the year of 1972 by Denni Date Conducted:
Laboratories in U SA (AT & Page No:
T).
The following are the language before ‘c’ & various versions of ‘c’.
1. ALGOL is introduced first in 1960’s
2. BCPL (Basic Combined Programming Language by Martin Richards in 1967 )
3. B Language (Ken Thompson and Dennis Ritchie at Bell Laboratory in 1969)
4. C Language (Dennis Ritchie at Bell Laboratory in 1972)
Features of C language
1. C is a structured programming language.
2. It is a robust language with rich set of built-in functions and operators that can be used to write
any complex program.
3. The C compiler combines the capabilities of an machine language with features of a high-level
language. (it is called as middle level language)
4. Programs Written in C are efficient and fast. This is due to its variety of data type and powerful
operators.
5. C is highly portable this means that programs once written can be run on another machines with
little or no modification.
6. Another important feature of C program, is its ability to extend itself.
7. A C program is basically a collection of functions that are supported by C library. We can also
create our own function and add it to C library.
8. C language is the most widely used language in operating systems and embedded system
development today.
9. C is a Case Sensitive language
Unit No:1
Link to Session
Planner (SP):S.No….of SP
Date Conducted:
Page No:
Structure of C program
Documentation Section (optional): The documentation section contains a set of comments
including the name of the program other necessary details. Comments are ignored by
compiler and are used to provide documentation to people who reads that code.
Comments in C programming are represented in two different ways:
1. Single Line Comment
// This is single line comment
2. Multi Line Comment
/* This is
multi line comment */
Left on its
ignored own
C program to use block and line comments u1_ex1.c
Structure of C program
Link Section (Must): The link section consists of header files while contains function
prototype of Standard Library functions which can be used in program. Header file also
consists of macro declaration. Example:
#include <stdio.h>
# is a pre processor director and
include is a preprocessor command
stdio.h is standard input/output header file
< > called angular braces.
There are two types of files to include in our program
1.Standard header files
All the standard header files must be placed in between angular braces
Ex: #include<math.h> to use mathematical functions in our program
2. User defiles files
All the user defiled files must be placed in between double quotes
Ex: #include”program1.c”
Structure of C program
Definition Section(Optional): The definition section defines all symbolic constants. A
symbolic constant is a constant value given to a name which can't be changed in program.
Example:
#define PI 3.14
#define is a preprocessor command to define a constant value
In above code, the PI is a constant whole value is 3.14
Global Declaration Section(Optional): In global declaration
section, global variables can
be declared.
These global variable can be used in both main and user defined functions.
By default
Ex intall
a,global
b, c; variables are initialized to null.
: void main()
{
}
fun1()
{
}
Structure of C program
main function Section(Must): The main () function section is the most important section of any
C program. The compiler start executing C program from main() function. The main() function
is mandatory in C programming.
It has two parts:
Declaration Part - All the variables that are later used in the executable part are declared in this
part.
Executable Part - This part contains the statements that are to be executed by the
compiler. int main()
{
...
..
...
... ..
...
}
int is the return value from main function. It returns zero to OS if program is successfully
executed.
Sub Program Section(Optional): The subprogram section contains all the user defined
functions. A complete and fully functions C program can be written without use of user-
defined function in C programming but the code maybe be redundant and inefficient if user-
defined functions are not used for complex programs.
First C Programs
1. Our first C program is very simple. No preprocessor commands
2. No global declarations. No local definitions.
3. It only prints simple message
Link to Session
The character set in C Language can be grouped into the following categories
Planner (SP):S.No….of SP
Lecture No:L12
Link to Session
C programming also has words with specific meaning which are used to con struct c program
Planner (SP):S.No….of SP
instructions.
Date Conducted:
In C programming language, keywords are special words with predefined me aning.
Page No:
1. All the keywords in C programming language are defined as lowercase letters so they
must be use only in lowercase letters
2. Every keyword has a specific meaning, users can not change that meaning.
3. Keywords can not be used as user defined names like variable, functions, arrays,
pointers etc...
4. Every keyword in C programming language, represents something or specifies
some
kind of action to be performed by the compiler.
Identifiers
Unit No:1
Lecture No:L13
Link to Session
1. One feature present in all computer languages is the identifier. Planner (SP):S.No….of SP
Page No:
program execution
3. Identifiers allow u s to name data and other objects in the program.
Each
identified object in the computer is stored at a unique address.
4. If we didn’t have identifiers, we would have to know and use object’s addresses.
Instead, we simply give data identifiers and let the compiler keep track of where
they are physically located.
The rules for identifiers are:
1. The first character must be alphabetic character(A-Z, a-z) or
underscore.
2. Must contain only alphabetic characters(A-Z, a-z), digits(0-9) or underscore.
3. First 63 characters of an identifier are significant.
4. Cannot duplicate a keyword.
5. Usually the identifies in the C system libraries start with an underscore, not an
application programs.
Identifiers
Examples of Valid and Invalid Names:
Lecture No:L14
Link to Session
1. A data type defines a set of values and a set of operations that can be applied onSP
Planner (SP):S.No….of
Lecture No:L15
Link to Session
1. The void type designated by the keyword void, has values and no operations . Planner (SP):S.No….of SP
2. Which mainly used with functions and pointers. Date Conducted:
3. It is used in three kinds of situations − Page No:
There are various functions in C which do not return any value or you can say they
return void. A function with no return value has the return type as void. For
example, void exit (int status);
2 Function arguments as void
There are various functions in C which do not accept any parameter. A function
with no parameter can accept a void. For example, int rand(void);
3 Pointers to void
A pointer of type void * represents the address of an object, but not its type. For
example, a memory allocation function void *malloc( size_t size ); returns a
pointer to void which can be casted to any data type.
Variables (1 of 2)
Variables are named memory locations that have a type, such as integer or character,
which is inherited from their type. The type determines the values that a variable may
contain and the operations that may be used with its values.
Variable Declaration:
1. Each variable in our program must be declared and defined.
2. In C, a declaration is used to name an object, such as a variable.
3. Definitions are used to create an object.
4. A variable is declared and defined at the same time.
5. Declaration gives them symbolic name and definition reserves memory for them.
6. Once defined, variables are used to hold the data that are required by the program for
its operation
7. A variable can be any data type, such as char, int or real but a variable cannot be void.
(2 of 2)
Variable Initialization:
Variables
1. We can initialize a variable at the same time that we declare it by including an initializer,
the initializer establishes the first value that the variable will contain.
2. To initialize a variable when it is define, the identifier is followed by assignment operator
and the initializer, which is the value the variable is to have when the function starts.
Example: int count=0;
int count=0,sum=0
Note: When a variable is defined, it is not initialized. We must initialize any variable
requiring prescribed data when the function starts.
When variables are defined ,they usually contain garbage(meaningless) values.
Link to Session
Although our programs have implicitly shown how to print messages, we ha ve not formally
Planner (SP):S.No….of SP
discussed how we use C facilities11)
to input and output data.
Date Conducted:
Stream s Page No:
:1. In C data is input to and output from a stream.
A stream is source of or destination for data.
2. It is Associated with physical device, such as a terminal, or with a file stored in auxiliary
memory. C uses two forms of streams : text and binary.
3. A text stream consists of sequence of characters divided into lines with line terminated by
a newline(\n). A binary stream consists of sequence of data values such as integer, real, or
complex using their memory representation.
4. Here we assume that the source of data is the keyboard and destination of data is the
monitor. Keyboard is known as standard input and monitor is known as standard output
Input/output statements (2 of 11)
Formatted Input/Output:
The C language provides two formatting functions: printf for output formatting and
scanf for input formatting.
Output formatting: printf
1. The printf function takes a set of data values, converts them to a text stream using
formatting instructions contained in a format control string, and sends the resulting text
stream to the standard output(monitor).
2. printf is data to text stream converter.
3. The syntax of printf function is
int printf(“ format control string”, argument list);
Input/output statements (3 of 11)
Output formatting: printf
Format control string
• Input and output
functions use a format
control string.
• Format control string
describes how data is
to be formatted when
read or write.
• Format control string m ay also contain the text to be printed,
su ch as instructions to the user, captions to make the output more readable.
• We can also print control characters, such as (\t), (\n), (a) by including them in
format control string.
Input/output statements (4 of 11)
Output formatting: printf
Conversion specification
1. To insert data into the stream, we use a conversion specification that
contain a start token (%), a conversion code, and up to four optional
modifiers as shown below.
2. The number, order and type of conversion specification must match the
number, order and type of the parameters in the list. Otherwise it
causes unpredictable results resulting in termination of input/output
function.
3. The first element is a conversion specification token (%) and the last
element is the conversion code. Both of these elements are required, the
other elements are optional
Input/output statements (5 of 11)
Conversion codes
Type Size Code Example
char none c %c
short int h d %hd
int none d %d
long int l d %ld
long long int ll d %lld
float none f %f
double none f %f
long double l f %lf
Precision:
If a floating point number is being printed, then we may specify the number
of decimal places to be printed with precision modifier. The precision
modifier has the format
.m ex: %.2f
Where m is the number of decimal digits. If no precision is specified printf
prints six decimal positions.
Input/output statements
Unit No:1
(6 of 11)
Lecture No:L18
Link to Session
Width modifier: Planner (SP):S.No….of SP
1. A width modifier may be used to specify the minimum number ofDateposition Conducted:
in the output. Page No:
2. It is very useful to align the output in columns, such as we need to print a
column of numbers.
3. It we don’t use a width modifier, each output value will take just enough
room for the data.
Ex: often width and precision are used
%2hd //short integer-2 print positions
%4d //integer -4 print positions
%8ld //long int-8 print positions
%7.2f //float-7 print positions. 2 decimal places
%10.3f //long double -10 print positions. 3 decimal places
Flag modifier:
• Flags allows the user to format the output in a desired fashion.
• Four output flags:
1) Justification
2) Padding
3) Sign
4) Alternate form Program for width, precision and size u1_ex15.c
Input/output statements (7 of 11)
The table defines the flag type, flag code and formatting
Arithmetic Operators
Relational Operators
Logical Operators
Increment & Decrement Operators
Assignment Operators
Bitwise Operators
Conditional Operator
Special Operators
Arithmetic Operators (+, -, *, /, %)
The arithmetic operators are the symbols that are used to perform basic
mathematical operations like addition, subtraction, multiplication, division and
percentage modulo.
The following table provides information about arithmetic operators.
Operator Meaning Example
+ Addition 10 + 5 = 15
- Subtraction 10 - 5 = 5
* Multiplication 10 * 5 = 50
/ Division 10 / 5 = 2
% Remainder of the Division 5 % 2 = 1
⇒ The addition operator can be used with numerical data types and character data
type. When it is used with numerical values, it performs mathematical addition and
when it is used with character data type values, It performs
concatenation (appending).
}
Logical Operators (&&, ||, !)
The logical operators are the symbols that are used to combine multiple
conditions into one condition. The following table provides information
about logical operators.
⇒ Logical OR - Returns FALSE only if all conditions are FALSE, if any of the
conditions is TRUE then complete condition becomes TRUE.
Nonzero Nonzero 1 1
&& Logical AND
|| Logical OR Nonzero 0 0 1
0 0 0 0
/* C program using of logical operators */
#include <stdio.h>
int main()
{
int a = 5, b =
5, c = 10,
result;
result = (a
== b) && (c
> b);
printf("(a == b) && (c > b) is %d \n", result);
result = (a == b) && (c < b);
printf("(a == b) && (c < b) is %d \n", result);
result = (a == b) || (c < b);
printf("(a == b) || (c < b) is %d \n", result);
result = (a != b) || (c < b);
printf("(a != b) || (c < b) is %d \n", result);
result = !(a != b);
printf("!(a != b) is %d \n", result);
result = !(a == b);
Assignment operators
The assignment operator evaluates an expression an expression on the right of
the expression and substitutes it to the value or variable on the left of the
expression.
Example: x = a+b
In addition, C has a set of shorthand assignment operators of the form.
Var operator= exp;
Example : x += 1 is same as x = x+1
The commonly used shorthand assignment operators are as follows
+=, -=, *=, /=, %=
#include <stdio.h>
main()
{
int a = 21;
int c ;
c = a;
printf("Lin
e1-=
Operator
Example,
Value of c
= %d\n", c
);
c += a;
printf("Line 2 - += Operator Example, Value of c = %d\n", c );
c -= a;
printf("Line 3 - -= Operator Example, Value of c = %d\n", c );
c *= a;
printf("Line 4 - *= Operator Example, Value of c = %d\n",
c );
c /= a;
printf("Line 5 - /= Operator Example, Value of c = %d\n", c );
c = 200; c %= a;
printf("Line 6 - %= Operator Example, Value of c = %d\n",
c );
}
Increment & Decrement Operators (++ & --)
The increment and decrement operators are called unary operators
because both need only one operand.
The increment operators adds one to the existing value of the operand
and the decrement operator subtracts one from the existing value of
the operand.
The following table provides information about increment and
decrement operators.
Operator Meaning Example
++ Increment - Adds int a = 5;
one to existing a++; ⇒ a = 6
value
-- Decrement - int a = 5;
Subtracts one a--; ⇒ a = 4
from existing
value
Increment & Decrement Operators (++ & --)
The increment and decrement operators are used in front of the
operand (++a) or after the operand (a++). If it is used in front of the
operand, we call it as pre-increment or pre-decrement and if it is used
after the operand, we call it as post-increment or post-decrement.
Pre-Increment or Pre-Decrement
#include<stdio.h> void
main()
{
int i =5,j; j = i++;
printf("i = %d \t j =
%d”,i,j);
}
Output:
Example Program for post decrement
#include<stdio.h>
void main()
{
int x,i = 10;
x=i--;
printf("x: %d",x);
printf("i: %d",i);
}
Bitwise Operators
1 0 0 0 0 0
1 1 1 0 1 0
0 1 1 0 0 1
0 0 1 1 1 1
BITWISE AND:-
The output of bitwise AND is 1 if the corresponding bits of two operands is 1. If
either bit of an operand is 0, the result of corresponding bit is evaluated to 0.
BITWISE OR:-
The output of bitwise OR is 1 if at least one corresponding bit of two operands
is 1. In C Programming, bitwise OR operator is denoted by |.
BITWISE XOR:-
The result of bitwise XOR operator is 1 if the corresponding bits of two
operands are opposite. It is denoted by ^.
BITWISE COMPLEMENT:-
1 2 >>1
2 4 >>2
3 8 >>3
4 16 >>4
….. ……. ……
n 2n >>n
Let’s assume number as 128.
If we shift the number 5 position to the right, the output will be
= 128 >> 5
= 128 / (25)
=128/32
=4.
Bitwise Left-Shift Operators
The bitwise shift right (<<) is a binary
operator that requires two integral
operands .
The first operand is the value to be shifted.
The second operand specifies the number of
bits to be shifted.
Ex: a <<=3; /* shift right 3 bits */
Bits positions
vacated by shift are
filled with zeros
Bitwise Left-Shift Operators
1 2 <<1
2 4 <<2
3 8 <<3
4 16 <<4
…. …….. ……
n 2n <<n
Example
Let’s assume the number as 12
If we shift the number 3 position to the left.
Then the output will be,
Example
12 << 3
= 12 *
(23)
= 12 * 8
= 96.
Bitwise Operators (&, |, ^, ~, >>, <<)
Let us consider two variables A and B as A = 25 (11001) and B = 20
(10100).
Example
In the above syntax, the expression1 is a Boolean condition that can be either true or
false value.
If the expression1 results into a true value, then the expression2 will execute.
The expression2 is said to be true only when it returns a non-zero value.
If the expression1 returns false value then the expression3 will execute.
The expression3 is said to be false only when it returns zero value.
/*ternary or conditional operator */
#include <stdio.h>
int main()
{
int age; //
variable
declaration
printf("Enter
your age");
scanf("%d",&ag
e);
// taking user
input for age
variable
(age>=18)?
(printf("eligible
for voting")) :
(printf("not
eligible for
voting")); //
conditional
operato
r
return 0;
Special Operators (sizeof, pointer, comma, dot, etc.)
The following are the special operators in c programming language.
sizeof operator
This operator is used to find the size of the memory (in bytes) allocated for a
variable.
syntax.
sizeof(variableName);
Example
sizeof(A); ⇒ the result is 2 if A is an integer
Output
Size of variable a : 4
Size of int data type : 4
Size of char data type : 1
Size of float data type : 4
Size of double data type : 8
When the sizeof() is used with an expression, it returns the size of the
expression.
Example
#include <stdio.h>
int main()
{
char a = 'S';
double b = 4.65;
printf("Size of variable a : %d\n",sizeof(a));
printf("Size of an expression : %d\n",sizeof(a+b));
int s = (int)(a+b);
printf("Size of explicitly converted expression : %d\n",sizeof(s));
return 0;
}
Output
Size of variable a : 1
Size of an expression : 8
Size of explicitly
converted expression :
C Expressions
Definition:
An expression is a of operators and operands that
collection
represents a specific value.
Ex: 2+3*4=(2+(3*4))=14
-b++=(-(b++))
Precedence and Associativity
Associativity
Associativity is used to determine the order in which operators
with the same precedence are evaluated in a complex
expression.
+ - Addition/subtraction 4 left-to-right
Example 1:
a*4+b/2-c*b consider a=3 b=4
c=5 Replace variables by their
values
3 * 4 + 4 /2 –5 * 4
Apply precedence rules
(3 * 4) Associativity
Apply + (4 / 2) – (5 rules
* 4) as they are left to right associative
(((3 * 4) + (4 / 2)) – (5 * 4))
In evaluation of this expressions there are no side effects
Example 3:
Example 2:
Example 4:
Type Conversion
Up to this point, we have assumed that all of our expressions involved data of the
same type. But, what happens when we write an expression that involves two
different data types, such as multiplying an integer and a floating-point number? To
perform these evaluations, one of the types must be converted.
Type conversion is of two types:
1. Implicit Type Conversion
2. Explicit Type Conversion (Cast)
Conversion rank:
int i = 10 ;
float x = 15.5 ;
char ch = 'A' ;
i = x ;
=======> x
value 15.5 is
converted as
15 and
assigned to
variable i
Type Conversion
Conversion Rank
Type Conversion
Explicit type conversion (Type casting)
1.In explicit type conversion we convert the data from one type to another type
using explicit type conversion.
2. Explicit type conversion uses the unary type cast operator
3. To cast the data from one type to another, we specify the new type in parentheses
before the value we want to convert.
Ex: (float) a
Output:
In the above program, we assign i = x, i.e., float variable value is assigned to the
integer variable. Here, the compiler automatically converts the float value
(90.99) into integer value (90) by removing the decimal part of the float value
(90.99) and then it is assigned to variable i.
Similarly, when we assign x = i, the integer value (90) gets converted to float
value (90.000000) by adding zero as the decimal part.
Typecasting
Typecasting is also called an explicit type conversion. Compiler converts data from
one data type to another data type implicitly. When compiler converts implicitly,
there may be a data loss. In such a case, we convert the data from one data type to
another data type using explicit type conversion. To perform this we use the unary
cast operator.
To convert data from one type to another type we specify the target data type in
parenthesis as a prefix to the data value that has to be converted.
syntax of typecasting.
(TargetDatatype) DataValue
Example
int totalMarks = 450, maxMarks = 600 ;
float average ;
average = (float) totalMarks /
maxMarks * 100 ;
In the above example code, both totalMarks and maxMarks are integer data values.
When we perform totalMarks / maxMarks the result is a float value, but the
destination (average) datatype is a float. So we use type casting to convert
totalMarks and maxMarks into float data type.
#include<stdio.h>
void main()
{
int a, b, c ;
float avg ;
printf("Enter any three integer values : ");
scanf("%d%d%d",&a,&b,&c);
avg = (a + b + c) / 3 ;
printf("avg before casting = %f\n",avg);
avg = (float)(a + b + c) / 3 ;
printf("avg after casting =%f\n",avg);
}