You are on page 1of 28

Module INTRODUCTION TO C PROGRAMMING

1:
Basics of C Programming: Introduction, Structure of a C program, Concept of a
variable,
Data types in C, Program statement, Declaration, Storing the data in memory,
Tokens, Operators and expressions, Lvalues and Rvalues, Type conversion in C.
Input and Output: Basic screen and keyboard I/O in C, Non-formatted input and
output, formatted input and output functions.

Module CONTROL STATEMENTS AND INTRODUCTION TO


2: PROBLEM SOLVING
Control Statements: Specifying test condition for selection and iteration, Writing
test expression, Conditional execution and selection, Iteration and repetitive
execution, goto statement, Special control statements, Nested loops.
Introduction to Problem Solving: Algorithms, Flowcharts, Problem solving
aspect, Top-down design, Implementation of algorithms, program verification
and efficiency of algorithms.

Module
ARRAYS & STRINGS AND FUNCTIONS
3:
Arrays and Strings: One-dimensional array – Declaration, Initialization, Accessing
elements, operations; Multi-dimensional arrays – Declaration, Initialization,
Working with 2D arrays; Strings – Declaration, Initialization, Printing strings,
String input, Character manipulation, String manipulation; Arrays of strings –
Initialization, manipulating string arrays.
Functions: Concept of function, Using functions, Call by value mechanism,
working with functions, passing arrays to functions, Scope and extent, Storage
classes, Recursion.

Module POINTERS (08 Periods)


4:
Introduction to Pointers: Understanding memory addresses, Address operator
(&), Pointer – declaration, Initialization, Indirection operator and dereferencing,
Void and Null pointers, Use of pointers, Arrays and pointers, Pointers and strings,
Pointer arithmetic, Pointers to pointers, Array of pointers, Pointers to an array,
Two-dimensional arrays and pointers, Pointers to functions, Dynamic memory
allocation.

Module USER-DEFINED DATA TYPES AND FILES (10 Periods)


5:
User-Defined Data Types: Structures - Declaration, Accessing the members,
Initialization, typedef and its use, Arrays of structures, Arrays within structure,
Structures and pointers, Structures and functions; Unions, Enumeration types,
Bitfields.
Files: Using files in C, Working with text and binary files, Direct File Input and
Output, Files of records, Random access to files of records.

Introduction to C
C is a programming language developed at AT & T’s Bell Laboratories of USA in
1972. It was designed and written by a man named Dennis Ritchie. In the late
seventies C began to replace the more familiar languages of that time like PL/I,
ALGOL, etc

ANSI C standard emerged in the early 1980s, this book was split into two
titles: The original was still called Programming in C, and the title that covered
ANSI C was called Programming in ANSI C. This was done because it took several
years for the compiler vendors to release their ANSI C compilers and for them to
become ubiquitous. It was initially designed for programming UNIX operating
system. Now the software tool as well as the C compiler is written in C. Major
parts of popular operating systems like Windows, UNIX, Linux is still written in C.
This is because even today when it comes to performance (speed of execution)
nothing beats C. Moreover, if one is to extend the operating system to work with
new devices one needs to write device driver programs. These programs are
exclusively written in C. C seems so popular is because it is reliable, simple and
easy to use. often heard today is – “C has been already superceded by languages
like C++, C# and Java.

Structure of C Language program

1 ) Comment line

2) Preprocessor directive

3 ) Global variable declaration

4) main function( )

Local variables;

Statements;

User defined function

}
}

Comment line

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.

Preprocessor Directive:
#include<stdio.h> 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 return statement*/

#include <stdio.h>

int main (void)

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


return 0;

Output: welcome to c programming language.

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.

Syntax:

int a;

char c;

float f;

Variable initialization

When we assign any initial value to variable during the declaration, is called
initialization of variables. When variable is declared but contain undefined value
then it is called garbage value. The variable is initialized with the assignment
operator such as

Data type variable

name=constant; Example: int a=20;

Or int a;

a=20;
Data types

Data types refer to an extensive system used for declaring variables or functions of
different types before its use. The type of a variable determines how much space it
occupies in storage and how the bit pattern stored is interpreted. The value of a variable
can be changed any time.

C has the following 4 types of data types

basic built-in data types: int, float, double, char


Enumeration data type: enum

Derived data type: pointer, array, structure, union


Void data type: void
A variable declared to be of type int can be used to contain integral values only—
that is, values that do not contain decimal places.
A variable declared to be of type float can be used for storing floating- point
numbers (values containing decimal places).
The double type is the same as type float, only with roughly twice the precision.
The char data type can be used to store a single character, such as the letter a,
the digit character 6, or a semicolon similarly A variable declared char can only store
character type value.
The size and range of the different data types on a 16 bit machine is given below:
Basic data type Data type with type Size Range
qualifier (byte)
char char or signed char 1 -128 to 127
Unsigned char 1 0 to 255
int int or signed int 2 -32768 to 32767
unsigned int 2 0 to 65535
short int or signed short int 1 -128 to 127
unsigned short int 1 0 to 255
long int or signed long int 4 -2147483648 to 2147483647
unsigned long int 4 0 to 4294967295
float float 4 -3.4E-38 to 3.4E+38

double double 8 1.7E-308 to 1.7E+308


Long double 10 3.4E-4932 to 1.1E+4932
DECLARATION

In programming, a declaration is a statement describing an identifier, such as the name of a variable


or a function. Declarations are important because they inform the compiler or interpreter what the
identifying word means, and how the identified thing should be used.

A declaration may be optional or required, depending on the programming language. For example,
in the C programming language, all variables must be declared with a specific data type before they
can be assigned a value.

A declaration is a C language construct that introduces one or more identifiers into the program and
specifies their meaning and properties. Declarations may appear in any scope. Each declaration ends
with a semicolon (just like a statement) and consists of three distinct parts:

attr-spec-seq ;

where, attr = Attribute spec = Specifier Seq = Sequence

For example:

int a, *b=NULL;
// "int" is the type specifier, "a" is a declarator, "*b" is a declarator and NULL is its initializer
const int *f(void);
// "int" is the type specifier, "const" is the type qualifier, "*f(void)" is the declarator.
enum COLOR {RED, GREEN, BLUE} c;
// "enum COLOR {RED, GREEN, BLUE}" is the type specifier.
// "c" is the declarator.

STATEMENTS

Statements are fragments of the C program that are executed in sequence. Statements are made by
combining various tokens. Each statement which does not have its body must be terminated by the
semicolon (;). The statements which should be terminated:

 All printf(), scanf() or any other function calls.


 All declarations like variables, constants, function, structures must be terminated by
semicolon.
 All expressions must be terminated by the semicolon (;).

The statements which should not be terminated:

 Header files include statements.


 Macro definition statements.
 If statements, loop statements, function header with the function definitions.

There are five types of statements:

Expression statements, compound statements, selection statements, iteration statements


and jump statements.

1) Expression statements: It is combination of variables, constants, operators, function calls and


followed by a semicolon. Expression can be any operation like Arithmetic operation or Logical
Operation.

Here are few examples for expression statements:

X = Y + 10;
20 > 90;
a?b:c;
a = 10 + 20 * 30;
; //This is NULL Statement

2) Compound statements: Compound statement is combination of several expression statements.


Compound Statement is enclosed within the braces { }. Compound statement is also called as Block
Statement.

There is no need of any semicolon at the end of Compound Statement.

Example for Compound Statement:

{
int a=10,b=20,c;
c = a + b;
printf(“value of C is : %d n”,c);
}

3) Selection statements: Selection Statements are used in decisions making situations. Statements
like if, if...else, switch are selection statements.

Syntax of if…else selection statement:

if(expression) { //code to be executed if condition is true }


else { //code to be executed if condition is false }

Here is an example of selection statements:


if (i < 1)
{
funct(i);
}
else
{
i = x++; funct(i);
}

4) Iteration statements: These are also called as Loops. If we want to execute a part of program
many times we may use loops. Some basic loops used in C language are for loop, while loop, do-
while loop.

Syntax of for iteration statement:

for ( expression-1(initialize);expression-2(End);expression-3(action) )
statements

Example of for loop:

for (int n=1; n <= 10; n++) //Loops from n=1 to n=10.
{
func(n);
};

Syntax of while iteration statement:

while(expression)
statements

Example of while loop:

while (n < 10)


{
a[n] = n;
n++;
}

5) Jump statements: These are unconditional statements; jump statements are useful for
transferring the control one part of program to other part of program. Some basic jump statements
are goto, continue, break and return.

Syntax of goto jump statement:


Syntax 1 | Syntax 2
----------------------------
goto label; | label:
.. | ..
.. | ..
.. | ..
label: | goto label;

Example for goto jump statement:

if (num % 2 == 0)
{ goto even; } // jump to even
else
{ goto odd; } // jump to odd

even:
printf("%d is even", num);
return; // return if even
odd:
printf("%d is odd", num);

Tokens in C

The individual elements of a program are called Tokens. In a C program, a number of individual units
or elements occur. These elements are called C Tokens. In the C language, the following 6 types of
tokens are available:

1. Identifiers
2. Keywords
3. Constants
4. Operators
5. Special Characters
6. Strings

Identifiers:

Each program element in a C program is called an identifier. An identifier is a variable that holds a
value and stores it in the memory.

Rules for declaring identifiers:

1. The identifier should consist of alphabets from a to z and A to Z.


2. It may contain numerical values from 0 to 9.
3. It may contain the underscore value.
4. The starting character of an identifier must always be a letter. Example: Variables, functions,
labels, etc.

Keywords

Keywords are words whose meaning has already been defined by the computer – they are pre-
defined words in the C compiler. Each Keyword is meant to perform a specific function in a C
program. Keywords are case sensitive and are written in lower case. The C language has 32
keywords, they are:

Constants

A constant is a fixed value that cannot be altered during the execution of a program. C Constants can
be classified into two categories:

1. Primary Constants
2. Secondary Constants

Primary constant

A primary constant is, again, divided into these three types:

1. Numeric
2. Character
3. Logical

 Numeric is subdivided into two types, Integer and Float.


 Character is subdivided into two types, Single Character and String

Secondary

The secondary constant is divided into the following types:

1. Arrays
2. Structures
3. Union
4. Pointer
5. Enum etc.

Operators:

Operators are symbols that provide instructions for the performance of various mathematical and
logical operations. Operators are tools that can alter data and variable values.

Operators are classified into the following eight types:

1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Increment/Decrement Operators
5. Assignment Operator
6. Bitwise Operators
7. Conditional Operators
8. Special Operators

Special characters

All the characters other than a to z, A to Z, and 0 to 9 are special characters. Example: {,},[,],(,)

A character data type consumes 8-bits of memory, which means that one can store anything in a
character whose ASCII value lies between -127 and 127. Thus, it can hold any of the 256 different
possible values.

String

A string is a group of characters that should be enclosed in double quotations.

For example: char string[]=“gitam”;

Variable

A variable is a user-defined word that, depending on the data type, will have some storage area. The
variable’s value will be changed during the program execution, and the data type and its value will
be changed during the program execution. The declaration of a variable is:
Datatype var1, var2, ...., varn;

Example: int a, float a, char x1;

Rules for variables

1. A variable is a combination of letters and digits.


2. The length of the variable is no more than 31 characters; however, the length is normally more
than 8 characters.
3. A variable should not be a reserved word.
4. "Special symbols, except the underscore(_),are not allowed.
5. The first character in a variable must be an alphabet.
6. No commas or blank spaces are allowed within a variable.

Expressions

An expression is a combination of variables, constants, operators and function call. It can


be arithmetic, logical and relational for example:-

int z= x+y // arithmatic expression a>b

//relational

a==b // logical func(a, b)


// function call
Expressions consisting entirely of constant values are called constant expressions. So,
the expression
121 + 17 - 110
is a constant expression because each of the terms of the expression is a constant value.
But if i were declared to be an integer variable, the expression
180 + 2 – j
would not represent a constant expression.

Operators:
An operator is symbol which is used to perform some operation in C.

🖛 Arithmetic Operators
🖛 Relational Operators
🖛 Increment and Decrement Operators
🖛 Logical Operators
🖛 Bitwise Operators
🖛 Conditional Operators
🖛 Assignment Operators
🖛 Special Operators

Arithmetic operators:

Operator meaning

+ Addition
- Substraction
* Multiplication
/ Division (finding the quotient)
% modulo division (finding reminder)

Write a program to perform all arithmetic operations.


// to perform all arithmetic operations
#include<stdio.h>
#include “conio.h”
void main ()
{
int a,b,c,d,e,f,g;
clrscr();
printf(“enter two values”);
scanf(“%d%d”,&a,&b); c=a+b;
d=a-b;
e=a*b;
f=a/b;
g=a%b;
printf(“\tarithmetic operations\n\t =================”); printf(“addition \t=\t
%d\n”,c);
printf(“substraction \t=\t%d\n”,d);
printf(“multiplication \t=\t%d\n”,e);
printf(“division \t=\t%d\n”,f);
printf(“reminder \t=\t%d\n”,g); getch();
}
Write a program to read & display Principle, Time, and Rate of Interest
then fine out simple Interest and every month installment?
// To Read & Display Principle , time, rate of interest then find out
simple interest and every month installment
#include<stdio.h>

#include “conio.h”

void main ()

{
int time;

float prncl, rtinrst, smpinrst, emi;

clrscr();

printf(“enter principle and time period and rate of interst”);

emi=(smpinrst+prncl)/time;

printf(“principle=%f”, prncl);

printf(“time period=%f”, time);

printf(“rate of intrest =%f”,rtinrst);

printf(“simple intrest =%f”, simpinrst);

print(“every month installment =%f”, emi);

getch()

Relational Operator:- Operator

Meaning
> Greater than
>= Greater than or equal to

< Less than

<= Less than or Equal to

== Double equal to

!= Is not equal to

Logical Operator:-
Operator Meaning

&& Logical And

|| (pipe) Logical OR

! Logical NOT

Assignment Operator:-

 ‘=’ is the Assignment Operator.


 Which is used to assign the values (or) Variables (or)
expressions which are presented in right side to left side
Variable.

Ex:- a=b, a=3


Write a program to swap two integer no’s
//to swap two no’s

#include<stdio.h>

#include”conio.h” void main()

{
int a,b,t;
clrscr();
printf(“enter two values\

n”); scanf(“%d%d”, &a,

&b);

printf(“before swapping \n a= %d b=%d\

n”,a,b);

t=a;

a=b;

b=t;

printf(“after swapping \n a= %d b= %d\

n”,a,b); getch()

Write a Program to swap two no’s by using 2 Variables.


//To Swap Two No’s

#include<stdio.h>

#include”conio.h” void main()

int a,b;
18 *Under revision
clrscr()
printf(“enter two values\n”); scanf(“%d

%d”,&a,&b);

printf(“before swapping \n a= %d b=%d\n”,a,b);

a=a+b;

b=a-b;

a=a=b;

printf(“after swaping \n a= %d b= %d\n”,a,b);

getch();

Increment and Decrement Operator:-


 ++ is the Increment Operator.
 --Is the decrement Operator.

Bitwise Operators:-

Operator Meanings
& Bitwise AND

| (Pipe) Bitwise OR

^ Bitwise XOR

>> Right Shift Operator

<< Let Shift Operator

Conditional Operator:-

 (? and : ) are the Conditional Operators. These are


used to check for Conditions.
19 *Under revision
 A Condition contains two Boolean values as true (or)
false.
Syntax:-

(Condition)? True: False;

Write a program to check whether the given number is even (or)


odd using conditional operator.

//To check the no is even or

odd no #include<stdio.h>
#include”conio.h”
void main()
{
int no;
clrscr();
printf(“enternumber\n);
scanf(“%d”.&no);
(no%2==0)?printf(“even number”):printf(odd number”);
}
Write a program to check whether the given year is Leap year (or)
not

// To check given Year is Leap Year or

not #include<stdio.h>

#include”conio.h”

void main()

int yea;

clrscr();

printf(“enter 20 *Under revision

year\n”);
scanf(“%d”,

&year);

(year%4==0)?printf(“leap year”):printf(“not leap year”);

getch();

Special Operator:-
 Sizeof() and comma (,) are the Special Operators.

Comma Operator:-
 This Operator is used to separate Variables.

Ex:- int a,b,c;

Sizeof() Operator:-
 It is used to find the Memory size of data type,
constant, arrays, structure etc.

Ex:- x=sizeof(variable)

Write a program to implement sizeof() operator.

//To implement

sizeof()

#include<stdio.h>

#include”conio.h”

void main()

21 *Under revision
{
int a;

long int b;

char c;

float d;

long float e;

clrscr();

printf(“integer memory size = %d\n”, sizeof(a));

printf(“long integer memory size = %d\n”,

sizeof(b)); getch();

Lvalues & Rvalues


In C programming, "lvalues" and "rvalues" are terms that are used to distinguish between
different types of expressions and values.

Lvalue (Left Value): An lvalue refers to an expression that can appear on the left-hand side of an
assignment operation. In other words, an lvalue represents a memory location or an object
that can be assigned a value. Lvalues are essentially identifiers (variables, array elements,
struct members) that can be assigned new values.

Examples of lvalues:

int x;
x = 10; // 'x' is an lvalue in the assignment
int arr[5];
arr[2] = 42; // 'arr[2]' is an lvalue
22 *Under revision
Rvalue (Right Value): An rvalue refers to an expression that can only appear on the right-hand
side of an assignment operation. An rvalue is a value that is computed and can be assigned
to an lvalue, but it doesn't represent a memory location itself. In simpler terms, rvalues are
temporary values that don't have an address that can be modified.

Examples of rvalues:

int y = 5 + 3; // '5 + 3' is an rvalue

int z = x + y; // 'x + y' is an rvalue

Type Conversion in c

In C programming, type conversion is the process of converting a value from one data type to
another. This is often necessary when you want to perform operations on variables of different
data types, or when you want to store a value of one data type in a variable of another data type.
There are two main types of type conversion in C: implicit (automatic) type conversion and explicit
(manual) type conversion.

Implicit Type Conversion (Automatic Type Conversion):

Implicit type conversion is done by the C compiler automatically when it is safe to do so. It
involves converting a value from one data type to another without the need for explicit
instructions from the programmer. This is also known as "type coercion."
For example:

int a = 5;

double b = a; // Implicit conversion from int to double

#include <stdio.h>
int main()
{
int x = 10; // integer x
char y = 'a'; // character c

// y implicitly converted to int. ASCII


// value of 'a' is 97
x = x + y; 23 *Under revision

// x is implicitly converted to float


float z = x + 1.0;

printf("x = %d, z = %f", x, z);


return 0;
}
Output
x = 107, z = 108.000000

Explicit Type Conversion (Manual Type Conversion):


Explicit type conversion, also known as "type casting," is performed by the programmer explicitly
using casting operators. This is used when the programmer wants to force a specific type
conversion that may not be done automatically by the compiler. There are two main casting
operators in C:
● (type): This operator is used for explicit casting. It has the syntax (type) expression. For
example:

double x = 5.67;

int y = (int)x; // Explicit conversion from double to int

#include<stdio.h>

int main()
{
double x = 1.2;

// Explicit conversion from double to int


int sum = (int)x + 1;

printf("sum = %d", sum);

return 0;
}
Output
sum = 2
24 *Under revision
Formatted I/O Functions
Formatted I/O functions are used to take various inputs from the user and display multiple outputs
to the user. These types of I/O functions can help to display the output to the user in different
formats using the format specifiers. These I/O supports all data types like int, float, char, and many
more.
Why they are called formatted I/O?
These functions are called formatted I/O functions because we can use format specifiers in these
functions and hence, we can format these functions according to our needs.
List of some format specifiers-

S
Format Specifier Type Description
NO.

int/signed
1 %d used for I/O signed integer value
int

2 %c char Used for I/O character value

3 %f float Used for I/O decimal floating-point value

4 %s string Used for I/O string/group of characters

5 %ld long int Used for I/O long signed integer value

6 %u unsigned int Used for I/O unsigned integer value

7 %i unsigned int used for the I/O integer value

8 %lf double Used for I/O fractional or floating data

9 %n prints prints nothing

The following formatted I/O functions will be discussed in this section-


1. printf()
2. scanf()
3. sprintf()
4. sscanf()

25 *Under revision
printf():
printf() function is used in a C program to display any value like float, integer, character, string, etc
on the console screen. It is a pre-defined function that is already declared in the stdio.h(header
file).
Syntax 1:
To display any variable value.
printf(“Format Specifier”, var1, var2, …., varn);
Syntax 2:
To display any string or a message
printf(“Enter the text which you want to display”);
#include <stdio.h>
int main()
{
int a;
a = 20;
printf("%d", a);

printf("This is a string");
return 0;
}

Output
20
This is a string

scanf():
scanf() function is used in the C program for reading or taking any value from the keyboard by the
user, these values can be of any data type like integer, float, character, string, and many more. This
function is declared in stdio.h(header file), that’s why it is also a pre-defined function. In scanf()
function we use &(address-of operator) which is used to store the variable value on the memory
location of that variable.
Syntax:
scanf(“Format Specifier”, &var1, &var2, …., &varn);

#include <stdio.h> 26 *Under revision

// Driver code
int main()
{
int num1;
printf("Enter a integer number: ");
scanf("%d", &num1);
printf("You have entered %d", num1);
return 0;
}

Output:
Enter a integer number: 56
You have entered 56

sprintf():
sprintf stands for “string print”. This function is similar to printf() function but this function prints
the string into a character array instead of printing it on the console screen.
Syntax:
sprintf(array_name, “format specifier”, variable_name);

sscanf():
sscanf stands for “string scanf”. This function is similar to scanf() function but this function reads
data from the string or character array instead of the console screen.
Syntax:
sscanf(array_name, “format specifier”, &variable_name);

MEMORY MANAGEMNT IN C
Almost all programming languages can handle system memory. A program and all the variables used
in the program occupy the precise memory space. Therefore, managing the memory with utmost care
is one of the major tasks that the programmer should keep in mind while writing the code.

When a variable is assigned to memory in a program, that memory location cannot be used by
another variable or any other program. So, the C language provides techniques for allocating
memory for various variables and programs.

There are two types used for allocating memory. These are:

Static Memory Allocations


In the static memory allocation technique, memory allocation occurs at compile time and remains the
same throughout the program. There will be no change in the amount of memory nor any change in
the location of the memory.

27 *Under revision
int days;
int snowfall = 0; // Normal variable
const int maxScore = 10; // Constant, can not be changed
Dynamic Memory Allocations
In the dynamic memory allocation technique, memory allocation occurs while running a program. It
has the facility to increase/decrease the allocated memory quantity and can release or free up the
memory whenever not needed or used. Memory can also be reallocated if needed. It is more
beneficial, and it can manage memory efficiently.

Dynamic memory management in C programming language is performed using


the malloc(), calloc(), realloc(), and free() functions. These four functions are defined in
the <stdlib.h> C standard library header file. It uses the heap space of the system memory

calloc()
Dynamically allocates an array of memory blocks of a specified type.
free()
Dynamically de-allocates memory at runtime.
malloc()
Allocates a block of memory in the heap, but does not initialize.
realloc()
Reallocates a block of memory that was previously allocated.

28 *Under revision

You might also like