KEMBAR78
C - Programming & Mat Lab Unit-1 | PDF | Integer (Computer Science) | Pointer (Computer Programming)
0% found this document useful (0 votes)
11 views28 pages

C - Programming & Mat Lab Unit-1

C is a general-purpose programming language developed in 1972 by Dennis Ritchie at AT&T's Bell Labs, primarily used for system programming and creating operating systems like UNIX. It is considered the 'mother language' for many modern programming languages due to its influence and syntax. C supports various programming paradigms, including procedural and structured programming, and is characterized by features such as simplicity, efficiency, and portability.

Uploaded by

gadiprasad1986
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views28 pages

C - Programming & Mat Lab Unit-1

C is a general-purpose programming language developed in 1972 by Dennis Ritchie at AT&T's Bell Labs, primarily used for system programming and creating operating systems like UNIX. It is considered the 'mother language' for many modern programming languages due to its influence and syntax. C supports various programming paradigms, including procedural and structured programming, and is characterized by features such as simplicity, efficiency, and portability.

Uploaded by

gadiprasad1986
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

UNIT -1

C Programming Basics

Introduction
 C is a programming language developed at AT’s &T’s BELL laboratories of USA in 1972.
 It was designed and written by a man named ”DENNIS RITCHE”.
 C is a general purpose computer programming language.
 It was used in operating systems, devices drives, but used in a wide range of application domains.
 C is commonly used on computer architectures that range from the largest supercomputers to the
smallest microcontrollers and embedded systems.
 C programming is mainly used to develop UNIX Operating System.
 C was originally developed at Bell, to construct uitilities running on Unix.
 It was applied to re-implementing the kernel of Unix Operating System.
 C programming is considered as the base for the programming languages. So it is called as Mother
Language.

It can be defined by the following ways:


 Mother Language
 System Programming Language
 Procedure-Oriented Programming Language
 Structured Programming Language
 Mid-Level Programming Language

Mother Language :

C Programming Language is considered as mother Language for all the modern Programming Languages. Because, most
of the compilers like JVMS, kernels, etc.. are written in C Language and also most of the programming language follows C
syntax. Eg: C++, Java, c#..etc.

System Programming Language:

C Language is used to create system software. Because, it can be used to do low-level programming and also used to
create hardware devices, os drivers, kernals, etc...

Procedural-Oriented Programming Language:

C is a procedural programming language. Procedure is known as function, method, routine, subroutine. Procedural
language specifies a series of steps for the program to solve the program.

Structured Programming Language :

It is a subset of procedural programming language. Structure means to break a program into parts or blocks .So that it
may be easy to understand. In c program, we break the program into parts by using functions. It makes program easier
to understand and modify.

Mid-Level Programming Language:

C is a Mid-level programming language .


because, it supports the features of both low-level and high-level languages.
Low level High level
1. It is known as computer’s native language 1. It is a programming language that means it is user
friendly
2. These languages are considered high memory efficient. 2. These languages are considered as less memory
efficient
3. It is difficult to Comprehend. 3. It is simple to Comprehend.
4.It is complex to debug. 4. It is straight forward to troubleshoot.
5.It is Difficult to maintain 5. It is easy to maintain
6.It is Non-Portable. 6.It is portable
7.Entirely dependent on the machine 7. Compatible with all operating systems.
8.Assembler is required for translation 8.Compiler or Interpreter is required

Features of C Programming :
 Simple
 Recursion
 Memory Management
 Fast & Efficient
 Modularity
 General Purpose Language
 Rich set of built in operations
 Portability
 Easy to extend
 Rich in libraries
 Middle level language
 Statically type
Characteristics:
 Small Size
 Extensive use of function calls
 Structured language
 Powerful programming language
 Portability
 Case Sensitive
Applications of C language:
 C language is used to create computer application software like Databases, Spreadsheets.
 Used to create system software as Operating systems.
 To create applications related to graphics like computer & mobile game.
 UNIX kernel has been fully developed in cLanguage.
 Used to create Network devices & Device drivers.
 Used to make a compiler.

Syntax:
Header files

Main method()

{
Statement 1;
Statement 2;
return 0;
}
// Basic program
#include<stdio.h>
#include<conio.h>
void main()
{
printf(“hello world”);
return 0;
}
Output: hello world

History and Structure of C-language program

History
 The root of all modern language is ALGO (Algorithmi c language),it is first computer programming language to
use block structure.
 MARTIN RICHARDS developed a language called “BCPL” (Basic combined programming language).It is
derived from “ALGO”.
 In 1970 kenThompson created “B” language by using BCPL.
 Both BCPL & B programming languages were typeless.
 After this “C” was developed using ‘BCPL’ & ’B’ by Dennis Ritchie at the bell lab in1972.

Language Year Developed by


ALGO 1960 Internationl Group
BCPL 1967 Martin Richard
B 1970 Ken Thompson
Traditional C 1972 Dennis Ritiche
K & Rc 1978 Kernighan &DennisRitchie
ANSI c 1989 ANSI committee
ANSI/ ISO c 1990 ISO committee
C99 1999 Standardization committe

Structure of C –language program

C program can be viewed as a group of building blocks called functions. A function is a subroutine that may
include one or more statements designed to perform a specific task.

There is a specific structure to start the programming in c language. Without structure it is difficult to analyze the
program and the solution. It gives the basic idea of the order of the sections in a program, when and where to
use a particular statements, variables, functions, curly braces and parenthesis.
Document Section

Link Section

Global Declaration Section

Main() Function Section

Deceleration Section

Executable Section
}

Sub Program Section

Function1

Function2

Function3

Document Section:

The Documentation Section Consist of a set of comment lines giving the name of the program, the author
and other details, which the programmer would like to use latter.

Comment lines: It indicates the purpose of the program. It is represented as


/*……………………………..*/
/………………………………..//
Comment line is used for increasing the readability of the program. It is useful in explaining the program
and generally used for documentation. It is enclosed within the decimeters. Comment line can be single or
multiple line but should not be nested. It can be anywhere in the program except inside string constant &
character constant.

Link section or Preprocessor Directive:


# include tells the compiler to include information about the standard input/output library. It is also used in
symbolic constant such as #define PI 3.14(value). The stdio.h (standard input output header file) contains
definition & declaration of system defined function such as printf(), scanf(), pow() etc. Generally printf()
function used to display and scanf() function used to read value.

Global Declaration:

This is the section where variable are declared globally so that it can be access by all the functions used in the
program. And it is generally declared outside the function
Main():

It is the user defined function and every function has one main()function from where actually program is started
and it is encloses within the pair of curly braces. The main( ) function can be anywhere in the program but in
general practice it is placed in the first position.

Syntax:

main()

{……..
……..
……..
}
The main( )function return value when it declared by data type as

int main( )

{
Return 0

The main function does not return any value when void(means null/empty)as void main(void) or void main()

printf(“C language”);

Output: C language

The program execution start with opening braces and end with closing brace. And in between the two braces declaration
part as well as executable part is mentioned. And at the end of each line, the semi-colon is given which indicates statement
termination.

/*First c program with returnstatement*/

#include<stdio.h>

int main (void)

printf("welcome to c Programming language.\n");

return 0;

Output: welcome to c Programming language.


Character set
A character denotes any alphabet, digit or special symbol used to represent information. Valid alphabets,
numbers and special symbols allowed

Characters that are typically available on most keyboards and character encoding.

1. Alphabets :Upper case(A– Z)


Lower case(a–z)
2. Digits: 10 decimal digits (0– 9)
3. Special characters
4. White spaces
5. Escape Sequence

Keywords

There are certain words reserved for doing specific task, these words are known as reserved word or keywords.
These words are predefined and always written in lower case or small letter. These keywords cann’t be used as
a variable name as it assigned with fixed meaning .C language supports 32 key words, Some examples are:

int, short, signed, unsigned,default,volatile,float,long,double,break,continue,typedef,static,do,for, union,


return, while, extern, register, enum, case, goto, struct, char, auto, const,else, if, sizeof, void, switch.

Data Types

Each variable in C has an associated data type. It specifies the type of data that the variable can store like integer,
character, floating, double, etc. Each data type requires different amounts of memory and has some specific
operations which can be performed over it. The data type is a collection of data with values having fixed values,
meaning as well as its characteristics.

The data types in C can be classified as follows:

Primitive or Primary Data Types : Primitive data types are the most basic data types that are used
for representing simple values such as integers, float, characters, etc.

User Defined Data Types: The user-defined data types are defined by the user himself.

Derived Types : The data types that are derived from the primitive or built-in data types are referred
to as Derived Data Types.

Primitive data type Integer ,character ,floating point, Double floating point, void.
User defined data type Structure ,Union, Enum, Typedef.
Derived data type Function ,Pointer ,Array

Integer Data Type


The integer data type in C is used to store the integer numbers(any number including positive, negative and zero
without decimal part). Octal values, hexadecimal values, and decimal values can be stored in int data type in C.
 Range:-2,147,483,648to 2,147,483,647
 Size:4bytes
 Format Specifier :%d

Syntax of Integer: We use int key word to declare the integer variable:
int var_name;
The integer data type can also be used as
1. Unsigned int: Unsigned int data type in C is used to store the data values from zero to positive
numbers but it can’t store negative values like signed int.
2. short int: It is lesser in size than the int by 2 bytes so can only store values from -32,768 to
32,767.
3. Long int: Larger version of the int data types can store values greater than int.
4. Unsigned short int: Similar in relationship with short int as unsigned int with int

// C program to print Integer data types.


#include <stdio.h>
int main()
{
int a = 9;
int b = -9;
int c=89U;
long int d=99998L;
printf("Integer value with positive data: %d\n", a);
printf("Integer value with negative data: %d\n", b);
printf("Integer value with an unsigned int data:%u\n",c);
printf("Integer value with an long int data: %ld", d);
return 0;
}
Output
Integer value with positive data: 9 Integer value with
negative data: -9
Integer value with an unsigned int data: 89
Integer value with an long int data: 99998

Character Data Type

Character data type allows its variable to store only a single character.
The size of the character is 1 byte. It is the most basic data type in C. It stores a single character and
requires a single byte of memory in almost all compilers.
 Range:(-128to127)or(0to255)
 Size:1byte
 Format Specifier:%c

Syntax of char
The char keyword is used to declare the variable of character type:
Char var_name;
// C program to print Integer data types.
#include <stdio.h>
int main()
{
char a='a';
char c;
printf("Value of a:%c\n", a);
a++;
printf("Value of a after increment is:%c\n",a);
//c is assigned ASCII values which corresponds to the character 'c’ a-->97 b-->98 c99 here c will be printed c = 99;
printf("Value of c:%c", c);
return 0;
}

Output
Value of a: a
Value of a after increment is :b
Value of c: c
Float Data Type

In C programming float data type is used to store floating-point values. Float in C is used to store decimal and
exponential values. It is used to store decimal numbers (numbers with floating point values) with single
precision.
 Range:1.2E-38to 3.4E+38
 Size:4 bytes
 Format Specifier: %f
Syntax of float
The float keyword is used to declare the variable as a floating point:
Float var_name;
//C Program to demonstrate use of Floating types
#include<stdio.h>
int main()
{ float a=9.0f;
float b =2.5f; // 2x10^-4
floatc=2E-4f;
printf("%f\n", a);
printf("%f\n", b);
printf("%f", c);

return 0;
}

Output
9.000000
2.500000
0.000200

}
Double Data Type:
A Double data type in C is used to store decimal numbers (numbers with floating point values) with double precision. It
is used to define numeric values which hold numbers with decimal values. It can easily accommodate about 16 to17
digits after or before a decimal point.
 Range:1.7E-308to1.7E+308
 Size:8 bytes
 Format Specifier : %lf
Syntax of Double
The variable can be declared as double precision floating point using the double keyword:
double var_name;
//C Program to demonstrate use of double data type
#include <stdio.h>
int main()
{
double a=123123123.00;
double b = 12.293123;
double c =2312312312.123123;
printf("%lf\n", a);
printf("%lf\n", b);
printf("%lf", c); return 0;
}
Output
123123123.000000
12.293123
2312312312.123123

Derived DataTypes

Derived data types give the programmer the ability to handel heterogeneous data, directly modify
memory and build complicated data structures.
Derived data types are classified as:
1. Arrays
2. Functions
3. Pointers
4. Structure

Arrays : Arrays are used to store multiple values in a single-variable, instead of declaring separate variables, It
provides a mechanism for joining multiple targets of the same data type under the same name.

Index is used to access the elements of an array the size of array is fixed at declaration time and it cannot be
changed.

Ex: int a[]={1,2,3,4,5}


Functions : A Function is a set of statements that when we called perform some specific task. It is the
basic building block of c program that provides modularity and code reusability.

Pointers: A pointer is a derived data type that keep strackofanother data type's memory address. When
a pointer is declared, the data type it refers to is stated first,and then the variable name is preceded by
an asterisk (*).
Data type asterisk(*) variable name;

Structure : Structure allows group of many data types under a single name .It gives you the ability to
create your own unique data structures.

Structure members can be accessed by using dot(.) operator.

User defined data types:

The data types that are defined by the user are called the user defined data types.
These are classified into 4 types.
1. Structure
2. Union
3. Enumerations
4. Typedef

Structure: A Structure is a user defined data type in ‘c’. A structure creates a data type that can be used to group of
items of possibly different types into a single type. It store in different memory.

1. A structure's members or fields are used to refer to each variable within it.
2. Any data type, including different structures, can be a member of a structure.
A structure's members can be accessed by using the dot (.) operator.
#include <stdio.h>

#include<strings.h>

struct person

charname[50];

int citno;

floatsalary;

person1;

int main ()

{
Strcpy (person1.name,“ram”);

person1.citno = 1984;

person1.salary = 25000;

printf(“Name:%s\n”,person1.name);

printf(“Citizenship:%d\n”,person1.citno);

printf(“Salary : %f\n”,person1.salary);

return 0;

Out put

Name: Ram

Citizenship: 1984

Salary: 2500.00

Union

Union are similar to structures it is also collection of different data items, but with a common memory. A
derived data type called a union enables you to store various data types in the same memory address. In
contrast to structures, where each member has a separate memory space, members of a union all share a single
memory space. A value can only be held by one member of a union at any given moment. When you need to
represent many data types interchangeably, unions come inhandy. Like structures, you can access the members
of a union by using the dot (.) operator.

#include<stdio.h>

union job;

float salary;

int id;

J;

int main()

{
J.salary=20000;

J.id=15;

printf(“%f\n”, J.salary);

printf(“%d\n”, J.id);

return 0;

Enumerations: A set of named constants or enumerators that represent a collection of connected values
can be defined in C using the enumeration datatype(enum). Enumerations give you the means to given a
mesthat make sense to a group of integral values, which makes your code easier to read and maintain.

Enumerations are mainly used to assign names to integrals constants, the names makes a program easy to read
and maintain.

Here is an example of how to define and use an enumeration in C:

#include<stdio.h>

enum week

{mon, tue, wed, thur, fri, sat, sun};

int main ( )

enum week day;

day = wed;

printf(“%d”,day);

return 0;

Output :2

Typedef: typedef is a keyword used in c programming to provide some meaningful name to the already
existing variable in c program it is like alias name.

We can say that this keyword is used to redefine the name of already existing variable.

Syntax : typedef <existing name><alias name>


#include<stdio.h>

Typedef longlongll;

int main ( )

ll var = 20;

printf(“%d”, var);

return 0;

Out put:20
Constants
Constant is a any value that cannot be changed during program execution. In C, any number, single character, or
character string is known as a constant. A constant is an entity that doesn’t change where as a variable is an
entity that may change.
For example, the number 50 represents a constant integer value. The character string "Programming in C
is fun.\n" is an example of a constant character string.

Syntax:

Const datatype var_name= value;

Eg: const int a= 15;

Defining the constants :there are two ways to define the constants. They are
1. Const keyword
2. #define preprocessor

Const keyword: by using the keyword const we can declare the constants.
#include<stdio.h>
int main()
{
Const float pi=3.14;
printf(“the value of pi is:%f”,pi);
return 0;
}
Output
The value of pi is :3.14

If we try to change the value of pi it will remained compile time error.


#define Preprocessor
#define preprocessor is also used to define constants.
#include<stdio.h>
#define pi3.14
int main ( )
{
printf(“%f”,pi);
return 0;
}

Types of Constants:

Basically there are two types of constants they are: Numeric constant
Character constant

Numeric constant: Numeric constant consists of digits. It required minimum size of 2bytes and max 4bytes. It
may be positive or negative but by default sign is always positive. No comma or space is allowed within the
numeric constant and it must have at least 1 digit.

It is categorized a integer constant and real/floating constant.

Integer constant
An integer constants are whole number which have no decimal point. Types of integer constants
are: Decimal constant: 0 9(base 10)
Octal constant:0--------7(base 8)
Hexa decimal constant:0----9,A ------- F(base16)
Binary constant:0&1(base 2)

Real/floating constant
Real constant is also called floating point constant.
To construct real constant we must follow the rule of,
-real constant must have at least one digit.
-It must have a decimal point.
-It could be either positive or negative.
-Default sign is positive.
-No commas or blanks are allowed within are all constant.
Ex.: +325.34 426.0 -32.76

Real/floating points are two types:

1. Decimal for more real constants:


It contains a decimal part eg:3.14,-1223.456
2. Exponential form:
Exponential form represents decimals or fractions in another way.
Eg:
123e12=123 x1012
123e-12=123x10-12
Character constant

A character constant is written as one character within single quotes such as‘a’.The value of a character constant
is the numerical value of the character in the machines character set.
There are 4types of constants:
1. Single Character Constant :A character which has been specified in a single quotes.
Eg : ‘A’, ‘7’, ‘$’

#include<stdio.h>
int main ()
{
Char ch=‘a’;
printf(“character constant is:%c\n”, ch);
return 0;
}

Output: character constant is: a

2. String Character Constant: A group of characters which are enclosed with double quotes.
Eg: “hello” , “5+0”, “ hello world”.

3. Backslash Character Constant: Backslash characters which are executed directly by compiler.
Eg : \n – new line.
\t–horizontal tab
\v-vertical tab
\r-carriage return
4. Enumeration Character Constant : Enumeration constants are user defined constants created using‘enum’
keyword. They are often used to create sets of named integer constants.
Eg: enumdays{ Sunday,Monday}.

Variables

Variable is a data name which is used to store some data value or symbolic names for storing program computations
and results. The value of the variable can be change during the execution. The rule for naming the variables is same as
the naming identifier. Before used in the program it must be declared. Declaration of variables specify its name, data
types and range of the value that variables can store depends upon its data types.

float–stores floating point numbers

int-stores interger
char–stores single characters

Syntax:

Data type Variable_Name=Value;

For eg:

int a= 15;
int my_num=20;
float f=0.98;
char c = ‘ a’;
Rules for creating a variable:

1. A variable can have alphabets, digits, and underscore.


2. Variable name can start with alphabet & underscore.
3. No white space is allowed within the variable name.
4. A variable name must not be any reserved word or a keyword.

//Programm for Declaring or creating variables.

#include<stdio.h>
int main()
{
//creating variables

int my_num = 15;


float my_num= 15.89;
char my_letter = ‘k’;
//print variables
printf(“%d\n”,my_num);
printf(“%f\n”,my_num);
printf(“%c\n”,my_letter);
return 0;
}

Output:

15
15.89
k

//program for changing the variable values.

#include<stdio.h>
int main()
{
int mynum=13;
mynum = 34;
printf(“%d”,mynum);
return 0;
}

Output:34

//Programm for assigning value to another number

#include<stdio.h>
int main()
{
int a=14;
int b=56;
a = b;
printf(“%d”,a);
return 0;
}

Output:56
//program for multiple variables

#include<stdio.h>
int main()
{
int x=5,y=8,z=6;
printf (“%d”, x+y+z);
return 0;
}

Output:19

Types of Variable in C:

There are 5 types in variables they are:


1. Local variable
2. Global variable
3. Static variable
4. Automatic variable
5. External variable

Local Variable

Local variable in c is a variable that is declared inside a function or a block of code. They can be used only by
statements that are inside that function or block of code. Local variables are not known to functions outside their
own. Its scope is limited to the block or function in which it is declared.

#include<stdio.h>
void function ( )

{
int x= 10;
//local variable #include<stdio.h>
printf(“%d”, x); int main()
} {
int main() (or) int x= 10;
{ printf(“%d”, x);
function(); }
}
Output: 10
Output:10

Global Variable:

A global variable in c is a variable that is declared outside the function or a block of code.usually on top of the
program. Global variables hold their values throughout the lifetime of your program and they can be accessed
inside any of the functions defined for the program. A global variable can be accessed by any function.
Its scope is the whole program.
#include<stdio.h>

int x = 10;
void function1()
{
printf(“%d\n”, x);
}
void function2()
{
printf(“%d\n”, x);
}
int main()
{
function1 ();
function2 ();
}

Output:10
10

Static Variable:

Static variable in C is a variable that is defined using the static keyword. It can be defined only once in a C
program and its scope depends upon the region where it is declared.( can be global or local)

Syntax:

Static datatype variable_name=value;

#include<stdio.>
void function1()

{
int x = 10;
static int y=20;
x = x + 1;
y=y+1;
printf(“%d%d”, x,y);
}
int main()
{
function1();
}

Output :1121

#include<stdio.h>
void function ( )
{
int x= 20;
static int y=30;
x = x+10;
y=y+10;
printf(“\t local:%d\n\t static:%d\n”, x,y);
}
int main()
{
printf (“ first call \n”);
function ( );
printf(“Second call\n”);
function ( );
printf(“Third call\n”);
function ( );
}

Output:

Firstcall
local:20
static:30
Second call
local:20
static:40
Third call
local:20
static:50

Note: local variable print the same value for each function call but, static will print incremented value.
Automatic variable

All the local variables are automatic by default ,They are also known as auto variables. Their scope is local and
their lifetime is till the end of the block. We can use‘ auto’ keyword to define the auto variables . The default
value of the auto variables is a garbage value.

Syntax:
auto datatype variablename=value;

#include<stdio.h>
void function ( )
{
int x=10;
auto int y=20;
printf(“Auto variable:%d”, y);
}
int main()
{
function ();
return 0;
}

Output:20
External variable:

External variable can be shared between multiple C files. We can declare an external variable using the extern
keyword. Their scope is global.

Syntax

extern datatype variablename=value;

#include<stdio.h>
extern int x = 10;
int main ( )
{
printf(“%d”,x);
return0;
}

Output:10

ArithmeticOperator
This operator used for numeric calculation. And these operators are addition, subtraction, multiplication, division.
Binary arithmetic operator on other hand required two operand and its operators are
+ (addition)
- (subtraction)
* (multiplication)
/ (division)
% (modulus).
But module scan not applied with floating point operand as well as there are no exponent operator in c.

Symbol Name
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus

Program
#include<stdio.h>i
nt main ( )
{
inta=20,b=10;
printf(“%d\n”,a+b); output:30
printf(“%d\n”,a-b); 10
printf(“%d\n”,a*b); 200
printf(“%d\n”,a/b); 2
printf(“%d\n”,a%b); 0
return 0;
}
Evaluation of Compound Expressions
Compound Expression: A compound expression is a series of simple expressions joined by arithmetic operators. A simple
expression used in a compound expression must return a numeric value.

Program
#include<stdio.h>
int main ()
{
int a=20, b=10,c=15, d=5, e;
e = (a+b)*c/d;
printf(“value of (a+b)*c/d is:%d\n”, e);
e= ((a+b)*c)/d;
printf(“value of ((a+b)*c)/d is:%d\n”, e);
e = (a+b)*(c/d);
printf(“value of (a+b)*(c/d)is:%d\n”, e);
e = a+(b*c)/d;
printf(“value of a+(b*c)/d is:%d\n”, e);
reurn 0;
}
Output :
value of (a+b)*c/d is : 90
value of(a+b)*c)/d is:90
value of (a+b)*(c/d) is:90
value of a+(b*c)/d is:50

Assignment Operator
Assignment operator are used to assign the result of an expression to a variable. Operand on the left hand side should
be variable and the operand on the right hand side should be variable or constant or any expression.
When variable on the left hand side is occur on the right hand side then we can avoid by writing the compound
statement.
SYNTAX: Var=value;
For example:
int x=y;
int sum=x+y+z;

Program
#include<stdio.h>
int main ( )
{
int a=10;
printf(“%d\n”,a); Output: 10
printf(“%d\n”,a+=10;); 20
return 0;
}

There are two types:


1. Simple:(=)
2. Compound:(+=,-=,*=,/=,%=,<<=,>>=,&=,!=,^=)

Example for simple:


a=5;
Example for compound:
a+=10

a=a+10
=10+10
a=20
Nested Assignment
If more than one assignment operator is present in statement, then that statement is called nested assignment statement.

Syntax: var1=var2=var3=var4=…....... =value or expression.

Increment and Decrement Operators


The Unary operator++,--,is used as increment and decrement which acts upon single operand. Increment
operator increases the value of variable by one .Similarly decrement operator decrease the value of the
variable by one. And these operator can only used with the variable, but cann't use with expression and
constant .
Increment operators
It again categories into prefix(or)pre-increment and postfix(or)post-increment.
Pre-increment:
Increment operator is placed before the operand and value is first incremented and then operation or
expression is performed on it.
Ex: z =++a
a=a+1
z=a
Post-Increment:
Increment operator is placed after the operand and value is incremented after the operationis performed on
it.
Ex:
z=a+
+ z=a
a=a+1
Program
#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
int a=10,z; int a= 10,z;
z=++a; z=a++
printf(“Z=%d\n”,z); printf(“Z=%d\n”,z);
print(“a=%d\n”,a); printf(“a=%d\n”,a);
return0; return 0;
} }

Output:Z=11 Output:Z=10
a=11 a= 11

Decrement Operators
It is used to decrement the value by 1.It is categories into pre decrement and post decrement.
Pre decrement
Decrement operator is placed before the operand and the value is first decremented and then operation or
expression is performed on it.
Ex:z=--a
a=a-1
z=a
Post Decrement
Decrement operator is placed after the operand and the value is decremented after the operation. Ex:
z=a—
z=a
a=a-1

Program

#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
int a=10,Z; int a=10,Z;
Z=--a; Z=a--;
printf(“Z=%d\n”,Z); printf(“Z=%d\n”,Z);
printf(“a=%d\n”,a); printf(“a=%d\n”,a);
} }
Output:Z=9 Output:Z=10
a=9 a=9

Formatted Input function scanf()


Scanf():It is an input function and it is used to read the mixed type of data from the keyboard. The general syntax
is as follows:
scanf(“control string”,&v1,v2,……&vn);
where v1,v2…….vn are all variables. Here ‘&’ specifies the address of location where the data is stores.
Ex: scanf(“%d%d”,&a,&b);
Control string have some format codes (or) format specifies for different data types.

Commonly used scanf format codes:

%c-Reads a single character.


%d-Reads a decimal integer.
%e or %f-Reads a floating point value.
%h-Reads a short integer.
%i-Reads a hexa decimal,decimal,octal integers.
%o-Reads an octal integer.
%s-Reads a string.
%u-Reads a unsigned decimal integer.
%x-Reads a hexa decimal integer.
%[..]-Reads a string of word.

Formatted output function printf()


printf(): it is an output function. It is used to display a text message and to display mixed type of data on the
screen.
The general syntax is:
printf(“controlstring”,v1,v2,…..vn); printf(“message line”);
wherev1,v2,vn are called variables. The variables should match in number order and type within the format specifications.
Ex: printf(“%d%d”,a,b);
Printf(“helloworld”);
Example program on Formatted input/output functions:
#include<stdio.h>
int main ()
{
int num;
printf(“Enter a number:”);//printing a message on the out put screen.
scanf(“%d”,& num);//Taking a number value from the keyboard.
printf(“Entered value is :%d”,num);//Displaying the entered value.
return 0;
}

Type Conversion Techniques


Type conversion in c is the process of converting one data type to another.
Type conversion is only performed to those data types where conversion is possible Type
conversion is performed by a compiler and it is done at compile time .
In type conversion the destination data type can’t be smaller than the source data type.

There are two types of conversions:


1. Implicit type conversion
2. Explicit type conversion

Implicit type conversion


It is an automatic type conversion done by thecompiler by it’s own without any external trigger from the user. It
convert the lower data type to higher data type to avoid data loss.
It is also called type promotion(upgrade to largest data type).
Generally it takes place when in an expression more than one data type is present. In such conditions type
conversion (type promotion) takes place to avoid loss of data.

bool->char -> shortint -> int ->unsignedint->long-> unsigned->longlong -> float -


>double ->longdouble
ex: short a = 20;
int b=a;
Program
#include<stdio.h>
int main ( )
{
int x = 10;
char y=‘a’;
x = x+y;
float z=x+10;
printf(“x= %d, z= %f” ,x,z);
return 0;
}
Output: x=107,z=108.00000
Explicit type Conversion
This process is also called type casting and it is user-defined. Here the user can typecast the result to make it of a
particular data type.
This action is done forcefully and there is data loss. Some conversions cannot be made implicit like int to short.
The syntax in C Programming:
(type)expression
Higher datatype to

Lower data type

Program

#include<stdio.h>

int main ()

Double x=1.2;

int sum=(int)x+1;

printf(“sum=%d”,sum);

return 0;

Output:

Sum=2

Relational Operator
It is use to compared value of two expressions depending on their relation. Expression that contain relational
operator is called relational expression.
The value or result of a relational expression is either true or false
Ex:45>58 False(0)
34==24+10 True(1)

Operator Meaning
< Less than
> Greater than
<= Less than or equal
>= Greater than or equal
== equal to
!= Not equal to
Program
#include<stdio.h>
#include<math.>
int main ()
{
int a=10,b=20;
printf(“%d\n”,a<b); Output:1
printf(“%d\n”,a>b); 0
printf(“%d\n”,a<=b); 1
printf(“%d\n”,a>=b); 0
printf(“%d\n”,a==b); 0
printf(“%d\n”,a!=b); 1
return 0;
}

Operator Precedence
Precedence
Precedence simply means that which operation is going to perfom first and which is going to perform last in that
expression.

Precedence Description Operator


Function call ()

Array subscript []
1
Dot operator(structure &union member .
access)

Arrow operator(structure&union ->


member access through pointer)

Suffix/postfix increment and ++,--


decrement
Prefix increment and decrement Unary ++,--
plus and minus +,-
Logical NOT !
2 Bitwise NOT ~
type caste Typ
indirection e
address *
Size in byte &
sizeof
3 Multiplication *
Division /
modulus %
4 Addition +
Subtraction -
5 Left shift <<
Right shift >>
Less than <
6 Less than equal to <=
Greater than >
Greater than equal to >=
7 Equal to ==
Not equal to !=
8 Bitwise AND &
9 Bitwise XOR ^
10 Bitwise OR |
11 Logical AND &&
12 Logical OR ||
13 Conditional operator ?:
Assignment operator or simple =
assignment
Assignment by sum and difference +=.-=
14 Assignment by product and quotient *=,/=,%=
Assignment by bitwise left shift and <<=,>>=
right shift
Assignment by bitwise AND,XOR,and &=,^=,|=
OR
15 Comma operator ,

Logiacal Operator
Operator used with one or more operand and return either value zero(for false) or one (for true). The operand may
be constant, variables or expressions. And the expression that combines two or more expressions is termed as logical
expression.
C has three logical operators:

Operator Meaning Example


&& AND (a>b)&&(a>c)
|| OR (a>b)||(a>c)
! NOT !(a>b)

Where logical NOT is a unary operator and other two are binary operator. Logical AND gives result true if both
the conditions are true, otherwise result is false. And logical OR gives result false if both the condition false,
otherwise result is true.

Exp1 Exp2 AND Exp1 Exp2 OR NOT


T T T T T T Exp1 Exp2
T F F T F T F T
F T F F T T T F
F F F F F F

Program
#include<stdio.h>
int main ( )
{
inta=10,b=20,c=30;
printf(“%d\n”,(a>b)&&(a<c)); Output:0
printf(“%d\n”,(a>b)||(a<c)); 1
printf(“%d\n”,!(a>b)); 0
return 0;
}
Bitwise Operator
Bitwise operator permit programmer to access and manipulate of data at bit level. Various bitwise operator
enlisted are
one's complement(~)
bitwise AND (&)
bitwise OR ( | )
bitwise XOR ( ^ )

Bitwise logical operators

bitwise AND (&)


bitwise OR ( | )
bitwise XOR ( ^ )

#include<stdio.h>
int main ()
{
int a=12,b=10;
printf(“%d\n”, a&b);
printf(“%d\n”, a|b);
printf(“%d\n”, a^b);
return 0;
}
Output:8
14
6

You might also like