You are on page 1of 62

Topics

 History of C Language
 Advantages of C Language
 Structure of C Program
 Character Set
 Tokens in C
 Data Types
 Variables
 Input / Output Statements
 Simple Programs
 Operators and Expressions
 Type Conversions
Software
A software is a set of programs, which is designed to
perform a well-defined task.

Program
A program is a set of instructions written to perform a
specific task.

Programmer
A Person who writes a program is known as Programmer.
Types of Computer Programming Languages
• Machine Level Programming Language : The program instructions are
written in zeros and ones, instructions are in binary form. Execution is
faster as instructions are already in 0’s and 1’s.
• Symbolic Level or Assembly Level Programming Language : a
programmer writes instructions using symbolic instruction code instead of
binary codes. Symbolic codes are meaningful abbreviations such as SUB is
used for substation operation, MUL for multiplication etc. A translator
known as Assembler is used to convert instructions into 0’s and 1’s.
• High Level Programming Language : The programming languages that are
close to human languages (example like English languages) are called the
high-level languages. A translator known as Compiler is used to convert
instructions to 0’s and 1’s.
Examples : Fortran, COBOL, Basic, Pascal, C, C++, Java.
History of C Language
 C programming language was developed in 1972 by Dennis
Ritchie at bell laboratories of AT&T (American Telephone &
Telegraph), located in the U.S.A.
 Dennis Ritchie is known as the founder of the C Language.
It was developed to overcome the problems of previous languages
such as B, BCPL, etc.
 Initially, C language was developed to be used in UNIX operating
system. It inherits many features of previous languages such as B and
BCPL.
History of C Language
Features of C Language

• It is Structured Programming Language


• Modularity : Ability to break down large modules into
smaller sub modules.
• Portability : Ability to run programs on different
machines.
• Extendibility : Ability to extend existing software by
adding new features.
• Speed : Execution of program is fast.
• Provides wide variety of operators and data types.
Structure of a C Program

Pre Processor Directives


#include<stdio.h>
Global Declarations
int a,b;
main()
main()
{
{
Local Declarations
int x, y;
Statement 1
printf(“Hello World”);
:
return 0;
:
}
Statement n
}
sum()
{
}
Other user defined functions
Structure of a C Program
• Every C Program is made up of one or more pre processor commands,
a global declaration section and one or more functions.
• The pre-processor commands are always at the beginning of the C
program and they start with #.
• Preprocessor commands are special instructions to the preprocessor
that tells how it, how to prepare the program for compilation, example
#include, #define etc.
• In global declaration section we can declare variables, functions.
Elements declared here are visible throughout the program.
• The actual work of the program is carried out in functions. A program
can have any number of functions, but it can have only one main()
function.
• Execution of the program starts with main function and ends with the
same.
• All functions including main have two parts declaration section and
body of the function which includes the statements to be executed.
• Global Declaration and User defined functions are optional from the
structure of C
Character Set

• All the characters that are used while writing the


program are part of character set.
It includes,
• Lowercase letters
– a b c . . . z
• Uppercase letters
– A B C . . . Z
• Digits
– 0 1 2 3 4 5 6 7 8 9
• Other characters
– + - * / = ( ) { } [ ] < > ‘ “
– ! @ # $ % & _ ^ ~ \ . , ; : ?
• White space characters
– blank, newline, tab, etc.
Tokens in C
• A token is a smallest or a basic unit of a C Program.
• One or more characters are grouped together in sequence to
form a meaningful words, known as Tokens.

There are 6 types of tokens as shown below


1. Keywords
 Keywords are reserved words which have predefined
meaning to the C Compiler. The meaning of keywords
cannot be altered.
 There are 32 Keywords supported in C Language.
auto do goto signed unsigned
break double if sizeof void
case else int static volatile
char enum long struct while
const extern register switch
continue float return typedef
default for short union
2. Identifiers
• Identifiers are the name given to various program elements
such as variables, function names, array names.
Rules for naming an Identifier/Variable :
1. The first character of an identifier should be either an alphabet
or an underscore, and then it can be followed by any of the
character, digit, or underscore.
2. It should not begin with digit.
3. In identifiers, both uppercase and lowercase letters are distinct.
Therefore, we can say that identifiers are case sensitive.
4. Commas or blank spaces cannot be specified within an
identifier.
5. Keywords cannot be represented as an identifier.
6. The length of the identifiers should not be more than 31
characters.
Valid and Invalid Identifiers
Divide the below given identifiers into valid and invalid identifiers
and given reasons for invalid.
KA22, Sum,7Wonders, _9AM, Tom Jerry, Im@Goa, Even_Odd, break

VALID INVALID Reasons for Invalid


KA22 7Wonders Identifiers should not start with digit
Even_Odd Tom Jerry Identifiers should not have spaces in between
Sum Im@Goa Identifiers should not have special symbols
_9AM break Identifiers should not be keyword
3. Constants

• A constant is a value assigned to the variable which will


remain the same throughout the program, i.e., the
constant value cannot be changed.
Types of Constants,
• Integer constants : Example - 10
• Character constants : Example – ‘A’
• Real/Floating point constants : Example – 3.142
• String constants : Example – “INDIA”
4. String
• Strings in C are always represented as an array of characters
having null character '\0' at the end of the string.
• This null character denotes the end of the string.
• Strings in C are enclosed within double quotes. Example,
“Hello All”

5. Special Symbols

• Some special characters are used in C, and they have a


special meaning which cannot be used for another purpose.
Examples: [] , {} # * $ ()
6. Operators
• An operator is symbols that represents the type of the
operation to be performed on operands
Data Types
• A data type tells the type of the value to be stored in the
memory locations.
Basic Data Types,

Data Types Size in Bytes Format Specifier


char 1 %c
int 4 %d
float 4 %f
void 0 NA

Q:When do we use data types?


A:When we declare a variables/functions we use data types.
Data Types

Primitive Non Primitive


char
Arrays
int
Stack
float Queues
Linked List
Primitive Data types:
They are basic data types, which
help us to store single value. Non Primitive Data types:
Example int a; They are derived data types, which are
derived from basic data types. They help
us to store more than one value.
Example int a[10];
List of Data Types in C

Note : Integer Size is Machine Dependent


Variable
• A variable is the name given to a memory location.
• It is "variable" because the value in the memory location can
change.
• Each memory location has an address.
Syntax for declaring a Variable:

Data Type Variable_Name(s);


Example for declaring Variables:
int a;
float b;
char c;
double d;
Variable and Memory Location

Address of
the memory
location.
Usually it’s a
hexadecimal
number
Variable Initialization

• Assigning an initial value to a variable is variable


initialization.
Types of initializing a Variable:
1. Compile Time Initialization int a=20
2. Run Time Initialization int a;
scanf(“%d”, &a);

Both methods are used to specify the values for the variables.
In Compile time the value of the variable is specified before
compiling the program whereas in run time the value for the
variable is specified/prompted when the program is running
with the help of any standard input function, such as scanf()
Input and Output Statements in C
• Any program takes some input from the user processes it and produces
output
• Input means to provide the program with some data to be
used/processed in the program and Output means to display resultant
data on the screen or write the data to a printer or a file.
• C programming language has standard libraries that allows us to give
input and display output in a program. The stdio.h or standard input
output library in C has functions for input and output.
Program
Output
Input
Types of I/O functions in C

Input/output
functions

Formatted Unformatted
I/O functions I/O functions

scanf() getchar()
printf() putchar()
puts()
gets()
Formatted Output Function: printf()
• printf() is a standard formatted output function used to
display output of a program on the output device.
• It is defined in the header file #include<stdio.h>
Syntax of using a printf() statement

printf(“control string”, arguments);


Text Ex: “hi” “area=”
Variables Ex: sum

Escape Sequences Ex:\n, \t Expressions Ex:(a+b)

Format Specifiers Ex:%d, %f, %c Function calls Ex: sqrt()


Examples of printf() statements
1. printf(“Hello World”); 2. printf(“area of circle=%d” ,area); 3. printf(“Sum=%f\n”, a+b);
4. printf(“Square root of given number is %f \n”, sqrt(n));
Formatted Input Function: scanf()
• scanf() is a standard formatted input function used to give
input to the program using standard input device.
• It is defined in the header file #include<stdio.h>
Syntax of using a scanf() statement

scanf(“format specifiers”, &variable_name(s));

Only format specifiers are


allowed inside the double Address
quotes ex: %d, %f, %c, %s Operator

Examples of scanf() statements


1. scanf(“%d”,&a);
2. scanf(“%f”, &radius);
3. scanf(“%c”, &c);
Write a C program to Display Your Name and Place

Expected Output:
Name : Raghavendra Patil
Place : Belagavi
Write a C program to Display Your USN, Name, Branch and Semester

Expected Output:
USN: 2KL20CS001
NAME: AMIT
BRANCH: CSE
SEM : 2
Write a C program to find the sum of two numbers.

Program
Input Output
5
Sum=15
10
Write a C program to find the area of circle.

Program
Input Output

2 Area =12.568
Write a C program to find the area and perimeter of a rectangle.
Write a C program to read the base and height of triangle as input and
then compute area of triangle
Write a C program to compute simple_interest for a given p, t, r.

Program
Input Output
10000 Simple
1
Interest=1000
10
Write a C program to read two integer numbers and swap the numbers.
Write a C program to print square and cube of a given number n.
Operators in C
An Operator is a symbol that tells the type of the operation to be performed on the operands

Types of Operators
Unary Operators

• Unary Operators : A Unary Operator is an operator that


takes a single operand in an expression.

Types of Unary Operators


Operator Type Operator Example Result
1. Unary Minus - -4 -4
2. Unary Increment 7++(Postfix Increment) 8
a. Postfix ++7 (Pre fix Increment) 8
b. Prefix ++
3. Unary Decrement 7--(Postfix Increment) 6
a. Postfix --7 (Pre fix Increment) 6
b. Prefix --
Binary Operators- Arithmetic Operators
• Binary Operators : are the operators that have two
operands in an expression.
• Arithmetic Operators are the operators used to perform
arithmetic operations.
Types of Arithmetic Operators
Operator Type Operator Meaning Example Result
Addition 6+2 8
+
Subtraction 6-2 4
-
Multiplication 6*2 12
*
Division 6/2 3
/
Modulus 6%2 0
%
Note: The % operator should not be used for float numbers.
Relational Operators
• Relational Operators also known as comparison operators
are used to compare two operands.
• Relational operators return result in True (1) or False (0)
Types of Relational Operators
Operator Type Operator Meaning Example Result
Greater Than 6>2 1
>
Greater Than 6>=2 1
>=
Or Equals to
Lesser Than 6<2 0
<
Lesser Than 6<=6 1
<=
Or Equals to
Equality 6==2 0
==
Not Equal 6!=2 1
!=
Logical Operators

• Logical Operator : A logical operator is a symbol, that is


used to combine two or more expressions.
• Logical operators return result in True (1) or False (0)
Example: a>b && a>c
Types of Logical Operators
Operator Type Operator Example Result
Logical AND && 1&&1 1
Logical OR || 1||0 1

Logical NOT ! !1 0
Bitwise Operators
• Bitwise Operators : are those operators that perform
operations at bit level.

Types of Bitwise Operators


Operator Type Operator Meaning Example Result
Bitwise Right Shift 4>>2 1
>>
Bitwise Left Shift 1<<2 4
<<
Bitwise AND 1&2 0
&
Bitwise OR 1|2 3
|
Bitwise XOR 3^2 1
^
Bitwise NOT ~5 10
~

Note: The left shift and right shift operators should not be used for negative numbers.
Bitwise Operators Examples

Consider a=1, b=2 Consider a=1, b=2 Consider a=3, b=2


a= 0001 a= 0001 a= 0011
1&2=0 b= 0010 1|2=3 b= 0010 3^2=1 b= 0010
a & b= 0000 a | b= 0011 a ^ b= 0001

In shift operations the first operand is the number to be shifted and the second
operand tells by how many bits first operand should be shifted. In right shift the
every bits are shifted towards right, and vice versa in left shift.

a= 0 1 0 0 0001 Consider a=10


a= 1010
b= 0 0 1 0 0010 ~10=5 a ~a= 0101

0001 0100
4>>2=1 1<<2=4
Note: 4 bit examples
Assignment Operators

• Assignment Operator : This operator is used to


assign value to a variable.

Example: a = 10
Short Hand Assignment Operators
Operator Type Example Result
a+=2 a=a+2
+=
a-=2 a=a-2
-=
a*=2 a=a*2
*=
a/=2 a=a/2
/=
Ternary Operator (?:)

Example:
Largest = a > b ? a : b;
Largest = a > b ? ( a > c ? a : c) : (b > c ? b : c) ;
Comma Operator

• The comma operator is used to link related


expressions together.
• A comma-linked list of expressions is evaluated
left to right and the value of the rightmost
expression is the value of the combined
expression.
– sum = (x = 10, y = 5, x + y);
• Assign 10 to x and then
• Assign 5 to y and finally
• Assign 15 (i.e. 10 + 5) to sum.
The sizeof Operator

• The sizeof operator when used with an


operand returns the number of bytes the
operand occupies.
• The operand may be a variable, a constant or
a data type qualifier.
– float x;
– sizeof(x) returns 4
– sizeof(10) returns 2 or 4
– sizeof(char) returns 1.
Expressions
• Expression: Sequence of operators and operands is
known as expression
• Expressions evaluates to a single value.
Precedence
• Precedence : tells the order in which the operators in a
complex expression should evaluated.
Example: 2+5*2. Here 5*2 first evaluates
Associativity
• Associativity : Associativity is used when there are two or
more operators of same precedence in an complex
expression.
• It can LR or RL
Example: 2 *3 / 2
P
R
E
C
D
E
N
C
E

C
H
A
R
T
Evaluate the given expressions
Expressions on Relational and Logical Operators
Expressions on Increment and Decrement Operators

Example 1: Example 2:
Consider, a=10 and b=20 Consider, a=5 and b=2
res = a++ + b++ res = a-- + b--

Example 3: Example 4:
Consider, a=20 and b=5 Consider, a=5 and b=2
res = ++a + ++b What is res?
res = --a + --b

Example 5:
Consider, a=40 ,b=30,c=20,d=10
res = ++a + b++ - --c * d++
Type Conversion in C
• The type conversion process in C is basically converting
one type of data type to other to perform some
operation.
• The conversion is done only between those data types
wherein the conversion is possible, Example – char to int
and vice versa.

There are two types of Type Conversion,

1. Implicit Type Conversion


2. Explicit Type Conversion(type casting)
Implicit Type Conversion

• Implicit Type Conversion : This type of type conversion is


automatically done by the compiler. When an expression has
variables and constants of different types, they are converted into
same type before evaluating the expression. This conversion is
called implicit or automatic type conversion. In such cases either
type promotion or demotion takes place.

Examples:

Down casting
integer to char
Explicit Type Conversion
• Explicit Type Conversion: This process is also called type
casting and it is user defined. Here the user can type
cast the result to make it of a particular data type.
• Explicit type conversion is temporary.
int a = 3 , b = 2;
float c, d;
c = a / b; c=1.000000
d = a / (float)b; c=1.500000

float a= 6.5 , b = 2.0;


int c, d;
d=3 d=a/b;
c=3 c = (int)a /(int) b;
Defining Constants
Defining Symbolic Constants:
• A symbolic constant is a name given to some numeric
constant, or a character constant or string constant, or
any other constants.
• Symbolic constant names are also known as constant
identifiers. Pre-processor directive #define is used for
defining symbolic constants.
Example: #define PI 3.141592, #define MAX 500
Constants

Defining Variable as Constant :


• Using const keyword: The const keyword specifies that a
variable or object value is constant and can’t be
modified at the compilation time.
Example:
Can you write program?
1. Write a program to convert temperature from
centigrade to Fahrenheit.
2. Given two integer values a and b, write a program to
compute the remainder of dividing a by b.
3. Peter wants to convert the distance from kilometer to
meter. Write a program to read distance in Kilometer
and convert and print the same in meters.
Can you write a program?

• A circle is inscribed in a square. Write a


program to find the area of the circle.
Algorithm

1. Accept side of the square in to d.


2. radius = d / 2
3. area = 3.142 * radius * radius
4. Print area
5. Stop
Can you write a program?

• A circle is inscribed in a square. Write an program to


find the area of the square not covered by the circle.
Algorithm

1. Accept side of the square in to d.


2. radius = d / 2
3. c_area = 3.142 * radius * radius
4. s_area = d * d
5. area = s_area – c_area
6. Print area
7. Stop

You might also like