0% found this document useful (0 votes)
10 views

Basics of C

Uploaded by

manibarathi0606
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Basics of C

Uploaded by

manibarathi0606
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

C Language Topics-unit 1 and 2

UNIT 1 BITS AND BYTES IN COMPUTING 9 Hrs. Computers : Hardware – Software –


Processor – Memory – I/O devices – Interface – Programming Languages – Evolution from
COBOL, FORTRAN to C, Python – Need. Algorithms: Role in problem solving – Analysis –
Design – Flowcharts: Role in problem solving – Symbols – Design – Pseudocode: Role in
problem solving – Design - Program: Role in problem solving – Design.
Practice Problems: 1. Describe a simple real world problem in your domain/department
and describe it in the form of problem statement, input, output and provide its solution in
terms of algorithm, flowchart, pseudo code and program.

UNIT 2 C: MATH BEHIND CODING 9 Hrs. C: Structure of program – Character set – Tokens
– Keywords – Identifiers – Constants – Variables – Datatypes – Strings – Operators and its
types – Functions – Header Files. Algorithmic Strategies: Iteration and Recursion –
Efficiency – Role of Time and Space consumption while building an algorithm –
Complexities
Practice Problems: 1. Describe a simple real world problem in your domain/department
and provide a computing and non-computing solution for the same. Calculate the time
and space consumed in both solutions. Compare and contrast the pros and cons in both
solutions. 2. Write an algorithm, flowchart, pseudo code followed by a simple C code to
do find the Factorial and Fibonacci series using both iteration and recursion.
Documentation Section:
It consist of a set of comment lines
The comment lines begins with /* and ends with */ or a single
set of // in the beginning of the line
These lines are not executable
Comments are very helpful in identifying the program features.

Preprocessor Section:
It is used to link system library files, for defining the macros and
for defining the conditional inclusion
Eg: #include, #include, #define MAX 100, etc.,

Global Declaration Section:


The variables that are used in more than one function
throughout the program are called global variables
Should be declared outside of all the functions i.e., before
main().
main():
Every ‘C’ program must have one main() function, which
specifies the starting of a ‘C’ program.
It contains the following two parts
Declaration Part: This part is used to declare the entire
variables that are used in the executable part of the program
and these are called local variables
Execution Part: It contains at least one valid C Statement.
The Execution of a program begins with opening brace ’,‘ and
ends with closing brace ’-’
The closing brace of the main function is the logical end of the
program.
Sub Program section:
Sub programs are basically functions are written by the user
(user defined functions) They may be written before or after a
main () function and called within main () function.
This is optional to the programmer
Points to be considered while writing a C
program:
 All statements in ‘C’ program should be written in
lower case letters. Uppercase letters are only used
for symbolic constants.
 Blank space may be inserted between the words.
Should not be used while declaring a variable,
keyword, constant and function
 The program statements can be written anywhere
between the two braces following the declaration
part.
 All the statements should end with a semicolon (;)
Compilation and Execution of C program
1. Creating the program
2. Compiling the Program
3. Linking the Program with system library
4. Executing the program
main() is a special function in C
programming language.
Reasons that make it special are -
•It defines starting point of the program.

• main is the first executed function.


•It controls all other child functions.
•Behaves as both user-defined and pre-
defined function.
•Every software written in C must have a
main function.
Various main() function
declarations

int main()
int main(void)
Int main(int argc, char*argv[])
void main()
void main(void)
void main(int argc, char * argv[])
Example Program for structure of C
#include<stdio.h>
#include<conio.h>
void main()
{
int p,n;
float si,r;
clrscr();
printf(“Enter principle amount, year and rate of
interest”); scanf(“%d %d %f”,&p,&n,&r);
si=p*n*r/100;
printf(“The simple interest is : %f”,si);
getch();
}
Tokens
• TOKEN is the smallest unit in a 'C' program. It is each and
every word and punctuation that you come across in your
C program. The compiler breaks a program into the
smallest possible units (tokens) and proceeds to the various
stages of the compilation. A token is divided into six
different types,
• Keywords
• Identifiers
• Strings
• Constants
• Special Characters
• Operators
To
ken
Keywords

In 'C' every word can be either a keyword or an identifier.

Keywords have fixed meanings, and the meaning cannot


be changed
.
They act as a building block of a 'C' program.

There are a total of 32 keywords in 'C’.

Keywords are written in lowercase letters.


Following table represents the keywords in C
Identifier
An identifier is nothing but a name assigned to an element in
a program.

Example, name of a variable, function, etc.

Identifiers are the user-defined names consisting of 'C'


standard character set.

As the name says, identifiers are used to identify a particular


element in a program.

Each identifier must have a unique name.


Following rules must be followed for
identifiers:
1.The first character must always be an
alphabet(uppercase or lower case) or an underscore.

2.It should be formed using only letters, numbers, or


underscore that is all succeeding characters must
be letters or digits

3.A keyword cannot be used as an identifier.

4.No space and special symbols are allowed


between the identifiers
Constants

The constants refer to fixed values that the program may not change or
modify during its execution. Constants can be of any of the basic data
types like an integer constant, a floating constant and a character constant.
There is also a special type of constant called enumeration constant.
Eg:
Integer Constants- 45, 215u
Floating Constants- 3.14, 4513E-5L
Character Constants- \t, \n
Strings
A string in C is actually a one-dimensional array of characters which is
terminated by a null character '\0'.
Eg:
char str = {‘S’, ’A’, ’T’, ’H’, ’Y’, ’A’, ’B’, ’A’, ’M’, ’A’}

Special Symbols

The symbols other than alphabets, digits and white spaces for example - []
() {} , ; : * … = # are the special symbols.
1.Special characters
•Special characters in 'C' are shown in the given table,

, (comma) { (opening curly bracket)


. (period) } (closing curly bracket)
; (semi-colon) [ (left bracket)
: (colon) ] (right bracket)
? (question mark) ( (opening left
parenthesis)
' (apostrophe) ) (closing right
parenthesis)
" (double quotation mark) & (ampersand)
! (exclamation mark) ^ (caret)
|(vertical bar) + (addition)
/ (forward slash) - (subtraction)
\ (backward slash) * (multiplication)
~ (tilde) / (division)
_ (underscore) > (greater than or closing
angle bracket)
$ (dollar sign) < (less than or opening
angle bracket)
% (percentage sign) # (hash sign)
Operators

An Operator is a symbol that specifies an operation to be


performed on the operands. The data items that operators act upon
are called operands. Operators which require two operands are
called Binary operators. Operators which require one operand are
called Unary Operators.

Types of Operators

Depending upon their operation they are classified as

1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and Decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Size of() Operators
Arithmetic Operators

Arithmetic Operators are used to perform mathematical


calculations like addition, subtraction, multiplication, division
and modulus.
Rules For Arithmetic Operators
1. C allows only one variable on left hand side of = eg.
c=a*b is legal, but a*b=c is not legal.

2. Arithmetic operations are performed on the ASCII values


of the characters and not on characters themselves

3. Operators must be explicitly written.

4. Operation between same type of data yields same type of


data, but operation between integer and float yields a float
result.
Relational Operators
Relational Operators are used to compare two or more
operands. Operands may be variables, constants or
expression
6.6 ASSIGNMENT Operators
Logical Operators

Logical Operators are used to combine the results of two or


more conditions. It is also used to test more than one
condition and make decision.
Conditional Operator
It itself checks the condition and executed the statement
depending on the condition.

Syntax:
Condition? Exp1:Exp2

Example:
X=(a>b)?a:b
The „?:‟ operator acts as ternary operator. It first evaluate the
condition, if it is true then exp1 is evaluated, if condition is false
then exp2 is evaluated. The drawback of Assignment operator is
that after the ? or : only one statement can occur.
Bitwise Operators
Bitwise Operators are used for manipulation of data at bit level. It
operates on integer only.
Special operators:
sizeof () operator:
1. Sizeof operator is used to calculate the size of data type or variables.
2. Sizeof operator will return the size in integer format.
3. Sizeof operator syntax looks more like a function but it is considered as an operator
in c programming

Example of Size of Variables


#include<stdio.h>
int main()
{
int ivar = 100;
char cvar = 'a';
float fvar = 10.10;
printf("%d", sizeof(ivar));
printf("%d", sizeof(cvar));
printf("%d", sizeof(fvar));
return 0;
}
Output :
214
In the above example we have passed a variable to size of operator. It will print the
value of variable using sizeof() operator.
Example of Size of constant
#include<stdio.h>
int main()
{

printf("%d", sizeof(10));
printf("%d", sizeof('A'));
printf("%d", sizeof(10.10));
return 0;
}
Output :
214
In this example we have passed the constant value to a
sizeof operator. In this case sizeof will print the size required
by variable used to store the passed value.
Example of Sizeof Data Type
#include<stdio.h>
int main()
{
printf("%d", sizeof(int));
printf("%d", sizeof(char));
printf("%d", sizeof(float));
return 0;
}
Output :
214
In this case we have directly passed an data type to an sizeof.
Example of Nested sizeof operator
#include<stdio.h>
int main()
{
int num = 10;
printf("%d", sizeof(sizeof(num)));
return 0;
}
Output:
2
We can use nested size of in c programming. Inner size of
will be executed in normal fashion and the result of inner size
of will be passed as input to outer size of operator.
Innermost Size of operator will evaluate size of Variable
“num” i.e 2 bytes Outer Size of will evaluate Size of constant
“2” .i.e 2 bytes
In the C Programming language, data types refer to a broad system used
for declaring variables or functions of different types.

The type of a variable determines how much space it occupies in storage


and how the bit pattern stored is interpreted.
INT DATA TYPE

Integers are whole numbers with a range of values, range of values are
machine dependent. Generally an integer occupies 2 bytes memory
space and its value range limited to -32768 to +32767.
CHAR DATA TYPE

Character type variable can hold a single character.

As there are singed and unsigned int (either short or long), in the
same way there are signed and unsigned chars; both occupy 1
byte each, but having different ranges.

Unsigned characters have values between 0 and 255; signed


characters have values from –128 to 127.
FLOAT DATA TYPE

The float data type is used to store fractional numbers (real


numbers) with 6 digits of precision.

Floating point numbers are denoted by the keyword float. When


the accuracy of the floating point number is insufficient, we can
use the double to define the number.

The double is same as float but with longer precision and takes
double space (8 bytes) than float.

To extend the precision further we can use long double which


occupies 10 bytes of memory space.
TYPE VOID DATA TYPE

The void type has no values therefore we cannot declare it as


variable as we did in case of integer and float.

The void data type is usually used with function to specify its type.
C program we declared "main ()" as void type because it does not
return any value.
Array: An array in C language is a collection of similar data-
type, means an array can hold value of a particular data type
for which it has been declared. Arrays can be created from any
of the C data-types int.

Pointer: C Pointer is a special variable that can be used to


store address of another variable.
ENUMERATED DATA TYPE (ENUM)

Enumerated data type is a user defined data type having finite


set of enumeration constants. The keyword 'enum' is used to
create enumerated data type. Enumeration data type consists of
named integer constants as a list. It start with 0 (zero) by default
and value is incremented by 1 for the sequential identifiers in
the list.

Syntax: Enum *data _ type+ ,const1, const2… constn}; Enum


example in C: enum month { Jan, Feb, Mar }; or /* Jan, Feb and
Mar variables will be assigned to 0, 1 and 2 respectively by
default */ enum month { Jan = 1, Feb, Mar };

/* Feb and Mar variables will be assigned to 2 and 3 respectively


by default */ enum month { Jan = 20, Feb, Mar };

/* Jan is assigned to 20. Feb and Mar variables will be assigned


to 21 and 22 respectively by default */
TYPEDEF DATA TYPE

It is used to create new data type. But it is commonly used to


change existing data type with another name.

Syntax: typedef [data_type] new_data_type;

Example: typedef int integer;

integer roll_no;
STRUCTURE DATA TYPE

C Structure is a collection of different data


types which are grouped together and each
element in a C structure is called member.

Example: struct student {


int roll _ no;
char name[20];
char city[20];
}

You might also like