0% found this document useful (0 votes)
4 views84 pages

C Module 1

The document provides an introduction to the C programming language, detailing its history, structure, and key features. It covers the basic components of a C program, including sections for documentation, linking, definitions, and the main function, as well as data types, constants, variables, and operators. Additionally, it explains the character set, tokens, and the rules for naming identifiers, alongside examples of arithmetic, relational, and logical operations.

Uploaded by

amarnadhmu123
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)
4 views84 pages

C Module 1

The document provides an introduction to the C programming language, detailing its history, structure, and key features. It covers the basic components of a C program, including sections for documentation, linking, definitions, and the main function, as well as data types, constants, variables, and operators. Additionally, it explains the character set, tokens, and the rules for naming identifiers, alongside examples of arithmetic, relational, and logical operations.

Uploaded by

amarnadhmu123
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

PROBLEM SOLVING

USING C
PROGRAMMING
INTRODUCTION
What is C ? Why C?

 C is a computer programming language


 Created for programming in the operating system
called UNIX
 Created by Dennis Richie in 1970s at Bell Labs
 Derived from a language called B - Ken Thompson
 A middle level language with the simplicity of high-
level language and power of low-level language –
very fast hence
 A compiled language
 Portable: run on a variety of operating systems with
little or no change
What is C ? Why C?

 Well suited for structured programming


 Can extend itself
 Wide range of popular programs/applications are written in C
First C Program
Basic Structure of a C Program
Basic Structure of a C Program

• Documentation section: The documentation section consists of a set of comment


lines giving the name of the program, the author and other details

• Link section: The link section provides instructions to the compiler to link functions
from the system library using the #include directive.

• Definition section: The definition section defines all symbolic constants using the
#define directive.

• Global declaration section: There are some variables that are used in more than
one function. Such variables are called global variables and are declared in the
global declaration section. This section also declares all the user-defined
functions.
Basic Structure of a C Program

• main () function section: Every C program must have one main function section.
The program execution starts here.{…}

• Declaration part: The declaration part declares all the variables used in the
executable part.
• Executable part: There is at least one statement in the executable part. All
statements in the declaration and executable part end with a semicolon.

• Subprogram section: If the program is a multi-function program then the


subprogram section contains all the user-defined functions
Program Ex: Sum of 10 and 20
Executing a C Program

1. Creating the program

2. Compiling the program

3. Linking the program with functions that are needed from the C library

4. Executing the program


Executing a C Program

Enter or Edit Link with system


Editor source program Linker
Source library
file(*.c) Executabl
e
Compile source
Compiler file(*.exe)
program Load and execute
Object file Loader
(*.obj)

Yes Syntax
errors? Yes Logical
errors?

No No

Output
C Character Set

 Letters: Uppercase A.............Z Lowercase a...................z


 Digits: All decimal digits. 0................9
 Special characters: such as , comma . period ; semicolon : colon
 White spaces: Such as blank spaces, horizontal tab, new line etc.
C Character Set: Special characters
C Tokens

Keywords float for


The smallest individual
unit in a C program is
Identifiers a sum main known as a C token
C Tokens

Constants 100 -2.15

Strings “hello” “year”

Special Symbols {}[]

Operators +-/
Keywords

 C keywords are the words that convey a special meaning to the c compiler. The
keywords cannot be used as variable names because by doing so, we are trying to
assign a new meaning to the keyword which is not allowed.

auto double int struct


break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Identifiers

 Identifiers are used as the general terminology for the names of variables, functions
and arrays.
Rules for naming c identifiers:
 They must begin with a letter or underscore(_).
 They must consist of only letters, digits, or underscore. No other special character is
allowed.
 It should not be a keyword.
 It must not contain white space.
 It should be up to 31 characters long as only first 31 characters are significant.
Constants

 Constants refers to the data items that do not change their value during the program
execution

Integer Constants

Real Constants
Constants
Character
Constants

String Constants
Constants

 Constants refers to the data items that do not change their value during the program
execution
 Integer Constants: Integer constants are whole numbers without any fractional part. It
must have at least one digit and may contain either + or – sign. A number with no sign
is assumed to be positive.
 Decimal Integer Constants: Integer constants consisting of a set of digits, 0 through 9, preceded by
an optional – or + sign
-341, 0, 8972
 Octal Integer Constants: Integer constants consisting of sequence of digits from the set 0 through 7
starting with 0
010, 0424, 0, 0540
 Hexadecimal Integer Constants: having sequence of digits preceded by 0x or 0X. They may also
include alphabets from A to F representing numbers 10 to 15
0xD, 0X8d, 0X, 0xbD
Constants

 Real Constants: The numbers having fractional parts are called real or floating point
constants
 Represented in two forms - fractional form or the exponent form
 Preceded by + or – sign
0.05, -0.905, 562.05, 0.015
 Exponent form (Scientific notation)
mantissa e exponent
mantissa : integer or a real number expressed in decimal notation.
e : Uppercase or lowercase, separates mantissa and exponent
exponent : an integer
252E85, 0.15E-10, -3e+8
Constants

 Character constants: contains a single character enclosed within single quotes


‘a’ , ‘Z’, ‘5’
 All character constants have numerical values known as ASCII values

Character constant Value


‘A’ 65
‘B’ 66
‘Z’ 90
‘a’ 97
‘z’ 122
Constants

 Backslash character constants/ Escape Characters/ Escape Sequences: Are


character constants used to represent non printable characters.
 Enclosed within single quotes
 Starts with a back slash
 Considers the back slash and the following character together as a single character

printf(“Hello\nGood morning!”);
Output:
Hello
Good morning!
Constants

Escape Sequence Description

\a Audible alert(bell)

\b Backspace

\f Form feed

\n New line

\r Carriage return

\t Horizontal tab

\v Vertical tab

\\ Backslash

\” Double quotation mark

\’ Single quotation mark

\? Question mark

\0 Null
Constants

 String Constants: A sequence of characters enclosed in double quotes


“hello”
“534”
“num100”
 Automatically terminates with a null character (‘\0’)
Variables

 A variable is nothing but a name given to a storage area that our programs can
manipulate.
 May take different values at different times during program execution
 Choose a name which is meaningful or that reflects the purpose or nature of the
variable
 Each variable in C has a specific type, which determines the size and layout of the
variable's memory; the range of values that can be stored within that memory; and the
set of operations that can be applied to the variable

sum, total, n1….


Data Types

1. Primary or fundamental data types.


2. Derived data types.
3. User-defined data types.

Five fundamental data types: integer (int), character (char), floating point (float), double
precision floating point (double), and void
Integer type

 Integer are whole numbers with a range of values supported by a particular machine
 If we use a 16 bit word length, the size of the integer value is limited to the range -
32768 to +32767 (-215 to +215 -1)
 Three classes of integer storage: short int, int and long int. Short int represents fairly
small value than int and int represents fairly small value than long int.
 Unsigned integer: unsigned int – ranges from 0 to 65535
Floating point types

 Floating point numbers are stored in 32 bits, with 6 digits of precision


 3 variants : float, double, long double
 double: 64 bits with 14 digits precision
 long double: 80 bits
Character type

 A single character can be defined as a character (char) type data.


 Characters are usually stored in 8 bits of internal storage
 While unsigned char have values between 0 to 255, sign char have values from -128
to 127.
Void type

 The void types has no values


 Usually used to specify the type of functions. The type of a function is said to be void
when it does not return any values to the calling function.
Fundamental data types
Size and range of data types
Declaration of Variables

 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


Syntax:
data-type v1,v2,…,vn;
Eg:
int count, sum;
double avg;
Data types and their keywords

If a qualifier long, short or unsigned is used without basic datatype specifier, it will be treated as int
Where the variables are declared?
Assigning values to variables

 Assignment statement (using assignment operator)


Variable_name= constant;
Eg:
a = 5;
start = 1;
end = 100; c = ‘a’;
b = a;
d = b + 10;
a = a + 1;
Assigning values to variables

 During assignment operation, C converts type of value on the right hand side to type of
value on the left; which causes truncation when real value is converted.
 Can also assign value to a variable at the time of declaration
datatype variable_name = constant;
Eg:
int start = 0;
int a, b = 10;
 The process of assigning initial value to a variable is called initialization
Assigning values to variables

 C permits multiple assignment operators in one statement to initialize multiple


variables
int a, b, c;
a = b = c = 0;
 If not initialized, a variable will contain garbage value
 Another way of assigning value is to get the value from user at run time
Operators in C

 An operator is a symbol that tells the computer to perform certain mathematical or


logical manipulations
 Used to manipulate data and variables
 Form mathematical or logical expressions
 An expression is a sequence of operands and operators that reduces to a single value
 Value can be any type other than void
Eg:
5 + 8 is an expression whose value is 13
Operators in C

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

Operator Meaning
+ Addition or unary plus
- Subtraction or unary minus
* Multiplication
/ Division
% Modulo division

Eg: if a and b are integers, a = 10 and b = 3


a + b gives 13
a – b gives 7
a * b gives 30
a / b gives 3 Here a and b are called operands
a % b gives 1
Arithmetic operators

 Integer Arithmetic:
 Here the operands are integers
 The expression is called integer expression
 Always yields an integer value
 In modulo division , the sign of result is the sign of dividend

Eg:
10 % 3 is 1
-10 % 3 is -1
10 % -3 is 1
-10 % -3 is -1
Arithmetic operators

 Real Arithmetic:
 Involves only real operands
10.0 / 3.0 is 3.333333
 Modulus operator (%) can not be used with real operands

 Mixed- Mode Arithmetic:


 On e operand is real and the other is integer
 If either operand is real, only real operation is performed
 The result is real
Eg:
10/3.0 is 3.333333
10 / 3 is 3
Relational Operators

 Are used for comparisons


 An expression containing a relational operator is called relational expression
 Value is either 1 or 0; 1 for true and 0 for false
 Eg: 5 < 10 is true and 10 < 5 is false

Operator Meaning
< Is less than
<= Is less than or equal to
> Greater than
>= Is greater than or equal to
== Is equal to
!= Is not equal to
Relational Operators

 A simple relational expression takes the following form:


ae-1 relational operator ae-2
Where ae-1 and ae-2 are arithmetic expressions

10.9 > 3 True


a != b
a + b <=20
 Used in decision statements
Logical Operators

Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT

• AND and OR operations are used when we want to test more than one condition and
make decisions

a > 10 && a < 20


a + b ==100 || a==50

• Above expressions re called logical expressions or compound relational expressions


• Yield 1 or 0 ( True or False)
Logical Operators

Value of the expression


op-1 op-2
op-1 && op-2 op-1 || op-2
Non zero Non zero 1 1
Non zero 0 0 1
0 Non zero 0 1
0 0 0 0
Assignment Operators

 Used to assign the result of an expression to a variable


v = exp;
Eg:
n = 10;
s = (a + b + c)/2;
a = b;
 Have a set of Shorthand assignment operators
v op=exp;
Here op is any binary arithmetic or bitwise operator
Assignment Operators

Shorthand assignment examples


a += 10 is equivalent to a = a + 10  add 10 to a
x +=(y+1) is equivalent to x = x+y+1  add y+1 to x
n/=10 is equivalent to n = n / 10
Increment and Decrement operators

 Increment operators are used to increase the value of the variable by one and
decrement operators are used to decrease the value of the variable by one
 Increment operator: ++var_name (or) var_name++
 Decrement operator: --var_name (or) var_name --
++i  pre-increment
i++  post-increment
--i  pre-decrement
i--  post-decrement
 When used as independent statements, both pre- and post- versions have the same
meaning
Increment and Decrement operators

 When used inside expressions, pre- and post- versions behave differently
 A pre-increment operator is used to increment the value of a variable before using it in
an expression(value is first incremented and then used inside the expression)
a = 10;
b = ++a;
Here the value of a and b becomes 11
 A post-increment operator is used to increment the value of variable after executing
expression completely in which post increment is used (value is first used in a
expression and then incremented)
b = a++;
Then b becomes 10 and a becomes 11
Conditional Operator

 It is a ternary operator pair “? :” , which form expressions of the form


exp1?exp2:exp3;
 exp1 is evaluated first. If it is nonzero (true) then the expression exp2 is evaluated and
becomes the value of the expression. If exp1 is false, then exp3 is evaluated and
becomes the value of the expression
a = 25;
b = 30;
l = (a > b)?a:b;
Then l will be assigned with 30.
Bitwise Operators

 Manipulate data at bit level

Operator Meaning
& Bitwise AND
| Bitwise OR
~ Bitwise NOT/ Complement
^ Bitwise XOR
<< Shift left
>> Shift right
Bitwise Operators

op1 op2 op1 & op2 op1 | op2 ~op1 op1^op2


0 0 0 0 1 0
0 1 0 1 1 1
1 0 0 1 0 1
1 1 1 1 0 0

x = 13;
Binary representations
y = 25;
x  0000 0000 0000 1101
z = x & y;
y  0000 0000 0001 1001
z  0000 0000 0000 1001  9
Bitwise Operators

 Shift operators are used to move bit patterns either to the left or to the right
Left shift: op << n
Right shift: op >> n
op is the integer expression that is to be shifted, and n is the number of bit positions to
be shifted
Eg:
x = 5; 0000 0000 0000 0101
y = x << 1; 0000 0000 0000 1010  10
z = x >> 1 0000 0000 0000 0010 2
Special Operators

 Comma operator ( , )
 sizeof operator
 Pointer operators ( & and * )
 Member selection operators ( . and -> )
Special Operators

 Comma Operator: Used to link the related expressions together


 Evaluated from left to right and the value of rightmost expression is the value of the
combined expression
val = (a = 5, b = 10, a + b);
Here val will be assigned with 15
 Comma operator has the lowest priority, so use parentheses
Special Operators

 sizeof operator: Gives the number of bytes the operand occupies


 A compile time operator
 Operand may be a variable, constant or a data type
a = sizeof(sum);
b = sizeof(long int);
c = sizeof(12);
Classification : Based on number of operands
One operand
++ -- + -
sizeof & * ~ !
Operators
Unary
Two operands

Binary + - * / % < <=


> >= == != &&….

Ternary
Three operands
?:
How to represent mathematical expressions
Type Conversion in Expressions

 Implicit / Automatic type conversion: When variables and constants of different


types are combined in an expression then they are converted to same data type
 If the operands are of different data types, the lower type is automatically converted to
the higher type before the operation proceeds
 Explicit type conversion/ type casting: Used when we want to force a type
conversion in a way that is different from automatic conversion
Implicit type conversion

long double
double
float
Conversion
unsigned long int hierarchy
long int
unsigned int
int
char short
Explicit type conversion

 The type conversion performed by the programmer using the type cast operator
Eg:
ratio = male_num/female_num;
Can be written as
ratio = (float)male_num/female_num;
 The conversion is just local
 The general form of a cast is:
(type_name)expression
Operator Precedence and Associativity

 If more than one operators are involved in an expression, C language has a predefined
rule of priority for the operators. This rule of priority of operators is called operator
precedence
 If two operators of same precedence (priority) is present in an expression, Associativity
of operators indicate the order in which they execute.
3 -2 *5+3
a = b = 10
 Precedence rules decides the order in which different operators are applied
 Associativity rule decides the order in which multiple occurrences of the same level of
operators are applied
Operator Precedence and Associativity

Operator Meaning Associativity Rank


() Functional call Left to right 1
[] Array element reference
-> Indirect member selection
. Direct member selection
! Logical negation Right to left 2
~ Bitwise(1 's) complement
+ Unary plus
- Unary minus
++ Increment
-- Decrement
& Dereference Operator(Address)
* Pointer reference
sizeof Returns the size of an object
(type) Type cast(conversion)
Operator Precedence and Associativity

Operator Meaning Associativity Rank


* Multiply Left to right 3
/ Divide
% Remainder
+ Binary plus(Addition) Left to right 4
- Binary minus(subtraction)
<< Left shift Left to right 5
>> Right shift
< Less than Left to right 6
<= Less than or equal
> Greater than
>= Greater than or equal
== Equal to Left to right 7
!= Not equal to
Operator Precedence and Associativity

Operator Meaning Associativity Rank


& Bitwise AND Left to right 8
^ Bitwise exclusive OR Left to right 9
| Bitwise OR Left to right 10
&& Logical AND Left to right 11
|| Logical OR Left to right 12
?: Conditional operator Left to right 13
= Assignment operators Right to left 14
*=
/=
%=….
, Comma operator Left to right 15
Operator Precedence and Associativity

Example:
a==b+10 && b > 5
Suppose a is 16, b is 6
1. Evaluates b+10
a==16 && b > 5
2. Evaluates b > 5 and then a==16
1 && 1
3. Evaluates &&
1
Managing Input and Output

 C does not have any built-in input/output statements as part of its syntax
 All input operations are carried out through function calls such as printf and scanf
 These functions are collectively called Standard I/O Library
 To use input and output functionality in our program, we need to include stdio header
file
#include<stdio.h>
Formatted Input

 The formatted input refers to an input data that has been arranged in a particular
format.
15 12.3 w
 The scanf() function is used for reading formatted data. Its general form is
scanf(“control string” , arg1, arg2, …, argn);

 the control string (format string) specifies the field format in which the data is to be
entered and the arguments arg1, arg2, … , argn specify the address of locations where
the data is stored. The control string and arguments are separated by commas
scanf(“%d%f%c”, &a, &f, &c);
Formatted Output

 Use the printf() function to print formatted output


printf(“control string”, arg1, arg2, .., argn);
 Control string consists of the following
1. Characters that will be printed on the screen as they appear
2. Format specifications that define the output format for display of each item
3. Escape sequence characters such as \n, \t etc.
 The arguments arg1, arg2,.., argn are the variables whose values are formatted and
printed according to the specifications of the control string
 The arguments should match in number, order and type with the format specifications
Formatted Output

Examples:
printf(“Good morning”);
printf(“ “);
printf(“\n”);
printf(“\t”);
printf(“%d”, n);
printf(“a=%d\tb=%f”, a, b);
printf(“Total mark =%f”, total);
printf(“sum = %d”, 54);
Reading a character

 Using getchar() function


variable_name=getchar();

char ch;
ch = getchar();
Printing a character

 Using putchar()
putchar(variable_name);

char option;
option = ‘a’;
putchar(option);

putchar(‘\n’);
Program to read and print a character
Program to read and print a character
Program to read and print a character
User-Defined type declaration

 C allows users to define an identifier that would represent an existing data type
 The user-defined data type identifier can later be used to declare variables
typedef type identifier;
type : an existing data type
identifier: the new name given to ‘type’
typedef int units;
typedef float height;
units batch1, batch2;
height male, female;
Enumerated data type

enum identifier{value1, value2, …. , valuen};


 Here identifier is the user defined enumerated data type which can be used to declare
variables that can have one of the values enclosed within braces
 Values within braces are called enumeration constants
enum identifier v1, v2,…,vn;
v1=value2;
v3=value1;
Enumerated data type

enum day {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday,


Sunday};
enum day week_st, week_end;
week_st= Monday;
week_end = Friday;
 Compiler automatically assigns integer digits beginning with 0 to all the enumeration
constants
 Automatic assignment can be overridden by assigning values explicitly
enum day {Monday =1, Tuesday,…, Sunday};
enum day {Monday, … ,Sunday} week_st, week_end;
Defining Constants in C

 Something that do not change is called a constant


 Constants can be defined in two ways
1. Using #define directive (symbolic constants)
2. Using const keyword (declares variable as constant)
Symbolic Constants

 Is a name that substitute for a sequence of characters that can not be changed
 When the program is compiled each occurrence of the symbolic constant is replaced
by its corresponding character sequence
 Preprocessor directive #define is used to define a symbolic constant
 Enables
 Modifiability
 Understandability

#define symbolic_name value_of_constant


#define STRENGTH 100
#define MAXSIZE 50
Symbolic Constants: Rules apply to #define statements

 Symbolic name has the same form as variable names but the convention is to use
CAPITALS
 No blank space between # and define
 # must be the first character in the line but can be declared anywhere in the program
before the first use of the constant
 Must not end with semicolon
 Assigning value after definition is illegal
 One statement can define only one name
 No data type is declared
Declaring a variable as constant

 To set the value of certain variables to remain constant during the program execution
 Use const keyword

const int max_size=50;


 Now the variable max_size can not be used on the left hand side of an assignment or
in an input function
Importance of C

 It is robust language – whose rich setup of built in functions and operator can be used
to write any complex program.
 Program written in C are efficient due to several variety of data types and powerful
operators
 The C compiler combines the capabilities of an assembly language with the feature of
high level language. Therefore it is well suited for writing both system software and
business package
 There are only 32 keywords; several standard functions are available which can be
used for developing program
 C is portable language; this means that C programs written for one computer system
can be run on another system, with little or no modification.
Importance of C

 C language is well suited for structured programming, this requires user to think of a
problems in terms of function or modules or block. A collection of these modules make
a program debugging and testing easier
 C language has its ability to extend itself. A c program is basically a collection of
functions that are supported by the C library. We can continuously add our own
functions to the library with the availability of the large number of functions.
 It is easy to learn and understand.

You might also like