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

Unit-1 Basics of C' Programming

Uploaded by

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

Unit-1 Basics of C' Programming

Uploaded by

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

21CS2152 ESSENTIALS OF C AND C++ PROGRAMMING

UNIT-1 Basics of C Programming


Fundamentals of ‘ C’ programming – Structure of a ‘C’ program – Constants - Variables – Data
Types – Expressions using operators in ‘C’ – Managing Input and Output operations-Branching
and Looping - Arrays – One dimensional and Two dimensional arrays.
Programs: 1. Write a C program to calculate sum of individual digits of a given number. 2. Write
a C program to count no. of positive numbers, negative numbers and zeros in the array. 3.
Write a C program to find sum of two numbers using functions with arguments and without
return type.
1. FUNDAMENTALS OF ‘ C’ PROGRAMMING

 C is general-purpose programming language, developed by Dennis Ritchie between


1969 and 1973 at AT&T Bell Labs.

 In 1972, Dennis Ritchie developed C language, combining the features of B and BCPL
language at bell laboratories.

 C is a structured, procedural, case sensitive, portable programming language.

 C is a middle level language.


1.1 Features of C Language

 C is a robust language with rich set of built-in functions and operators.


 Programs written in C are efficient and fast.
 C is highly portable, programs once written in C can be run on another machines
with minor or no modification
 It is a collection of C library functions; User can create their own function and add
it to the C library.
 It is a Procedural Oriented Language.
 Procedural Programming divides the program into procedures, which are also
known as routines or functions, simply containing a series of steps to be carried
out.
 It groups the code in function. This modular structure makes code debugging,
maintenance and testing easier.

 It uses top-down approach.


 It does not provide Object Oriented Programming (OOP) concepts.
 It is difficult to relate with real world objects.
2. STRUCTURE OF C PROGRAM
The basic structure of a C program is divided into 6 parts which makes it easy to read,
modify, document, and understand in a particular format
A skeleton of a C program is given below
There are 6 basic sections responsible for the proper execution of a program. Sections
are mentioned below:
1. Documentation
2. Preprocessor Section
3. Definition
4. Global Declaration
5. Main() Function
6. Sub Programs
Example
//Program for finding area of a circle
#include<stdio.h>
# define pi 3.14
float r = 4.5;
void main()
{
float area;
area=pi*(r*r);
printf("The Area of a circle %f",area);
}
Output:
The Area of a circle 63.584999

2.1 Documentation

This section consists of the description of the program, the name of the program, and the
creation date and time of the program. It is specified at the start of the program in the form of
comments. Anything written as comments will be treated as documentation of the program
and this will not interfere with the given code.
Documentation can be represented as:
// description, name of the program, programmer name, date, time etc.
 Single line comments //: used when there is a single line to comment
 Multiline comments /* */: used when there is multiple lines to comment.

2.2 Pre-processor section


All the header files of the program will be declared in the preprocessor section of the
program. A copy of these multiple files is inserted into our program before the process of
compilation.
 Pre-processor section tells the complier to link the needed header file during compilation
 It starts with pound symbol (#).It is not terminated with semicolon.
Example
#include<stdio.h>
#include<conio.h>
2.3 Definition Section

Pre-processor directives start with the ‘#’ symbol. The #define pre-processor is used to create a
constant throughout the program. Whenever this name is encountered by the compiler, it is
replaced by the actual piece of defined code.
This section contains all Symbolic constants
Example
# define PI 3.14
#define long long ll
2.4 Global declaration section
The global declaration section contains global variables, function declaration, and static
variables. Variables and functions which are declared in this scope can be used anywhere in the
program.
Example
int num = 18;
int a;
main ()
{
}
2.5 main () function
 Each and every C program should have only one main () function.
 Operations like declaration and execution are performed inside the curly braces of
the main program.
 The return type of the main() function can be int as well as void too. void() main tells
the compiler that the program will not return any value.
 The int main() tells the compiler that the program will return an integer value.
 The execution of C program begins at this function.
 The main() section is divided into two portions
i) Declaration part: It describes the data that will be used in the function. Data
declared within the function are known as local declaration.
ii) Executable part: contains s set of statements executed by the computer.

2.6 Sub Programs


User-defined functions are called in this section of the program. The control of the
program is shifted to the called function whenever they are called from the main or outside the
main() function. These are specified as per the requirements of the programmer.

Example:

int sum(int x, int y)


{
return x+y;
}

3. C PROGRAMMING: DATA TYPES


Each variable in C has an associated data type. Each data type requires different
amounts of memory and has some specific operations which can be performed over it. It
specifies the type of data that the variable can store like integer, character, floating, double,
etc.
The data types in C can be classified as follows:

Types Description

Primitive Data Arithmetic types can be further classified into integer and floating data
Types types.

Void Types The data type has no value or operator and it does not provide a result to
Types Description

its caller. But void comes under Primitive data types.

User Defined It is mainly used to assign names to integral constants, which make a
DataTypes program easy to read and maintain

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

Data Memor Range Format

Short 2 -32,768 to 32,767 %hd

unsigne 2 0 to 65,535 %hu

unsigne 4 0 to 4,294,967,295 %u

int 4 -2,147,483,648 to %d

long int 4 -2,147,483,648 to %ld

unsigne 4 0 to 4,294,967,295 %lu

long 8 -(2^63) to (2^63)-1 %lld


Data Memor Range Format

unsigne 8 0 to %llu

signed 1 -128 to 127 %c

unsigne 1 0 to 255 %c

float 4 1.2E-38 to 3.4E+38 %f

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

long 1 3.4E-4932 to 1.1E+4932 %Lf

1. Integer Types
 The integer data type in C is used to store the whole numbers without decimal
values. Octal values, hexadecimal values, and decimal values can be stored in int
data type in C.
 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. Unsigned int is larger in
size than signed int and it uses “%u” as a format specifier in C programming
language.
 Range: -2,147,483,648 to 2,147,483,647
 Size: 2 bytes or 4 bytes
 Format Specifier: %d

Example 1:
// C program to print Integer data types.
#include <stdio.h>
int main()
{
// Integer value with positive data.
int a = 9;

// integer value with negative data.


int b = -9;
// U or u is Used for Unsigned int in C.
int c = 89U;
// L or l is used for long int in C.
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

2. Character Types
Character data type allows its variable to store only a single character. The storage
size of the character is 1. 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: (-128 to 127) or (0 to 255)


Size: 1 byte
Format Specifier: %c
Example 2:
// 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
3. Floating-Point Types
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-38 to 3.4E+38


Size: 4 bytes
Format Specifier: %f

Example 3:
// C Program to demonstrate use of Floating types
#include <stdio.h>
int main()
{
float a = 9.0f;
float b = 2.5f;
// 2x10^-4
float c = 2E-4f;
printf("%f\n",a);
printf("%f\n",b);
printf("%f",c);
return 0;
}
Output
9.000000
2.500000
0.000200

4. Double Types
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 in C. Double data type is basically a precision sort of data type that is
capable of holding 64 bits of decimal numbers or floating points.
Range: 1.7E-308 to 1.7E+308
Size: 8 bytes
Format Specifier: %lf

Example 4:
// 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

5. Void Data types


 The void data type in C is used to specify that no value is present. It does not
provide a result value to its caller.
 It has no values and no operations. It is used to represent nothing.
 Void is used in multiple ways as function return type, function arguments as
void, and pointers to void.
Example 5:
// C program to demonstrate use of void pointers
#include <stdio.h>
int main()
{
int val = 30;
void *ptr = &val;
printf("%d", *(int *)ptr);
return 0;
}
Output
30

4. KEYWORDS

 Keywords are predefined or reserved words that have special meanings to the compiler.
These are part of the syntax and cannot be used as identifiers in the program.
 Keywords are reserved words whose meaning has already explained to the compiler.
 C is a case sensitive language, all keywords must be written in lowercase.
 Keywords are part of the syntax and they cannot be used as an identifier.
 There are 32 reserved keyword.
 A list of keywords in C or reserved words in the C programming language are mentioned
below:
Eg int marks;
int is a keyword
mark is a variable

auto break case char const continue default do

double else enum extern float for goto if

int long register return short signed sizeof static

struct switch typedef union unsigned void volatile while

5. VARIABLES

 A variable in C is a memory location with some name that helps store some form
of data and retrieves it when required.

 Can store different types of data in the variable and reuse the same variable for
storing some other data any number of times.

 It refers to the address of the memory where data is stored.


C Variable Syntax
data_type variable_name = value;
Here,

data_type: Type of data that a variable can store.


variable_name: Name of the variable given by the user.
value: value assigned to the variable by the user.
There are 3 aspects of defining a variable:
Variable Declaration in C
Variable declaration in C tells the compiler about the existence of the variable
with the given name and data type.
No memory is allocated to a variable in the declaration.
Example :
int defined_var;
Variable Definition in C
In the definition of a C variable, the compiler allocates some memory and some
value to it.
A defined variable will contain some random garbage value till it is not initialized.
Example :
int ini_var = 25
Variable Initialization in C
Initialization of a variable is the process where the user assigns some meaningful
value to the variable.
Example
defined_var = 12;
5.1 Rules for defining variables
Rules for Naming Variables in C

 You can assign any name to the variable as long as it follows the following rules:

 A variable name must only contain alphabets, digits, and underscore.

 A variable name must start with an alphabet or an underscore only. It cannot


start with a digit.

 No whitespace is allowed within the variable name.

 A variable name must not be any reserved word or keyword.


Example:
5.2 Types of Variables in C
The C variables can be classified into the following types:

 Local Variables
 Global Variables
 Static Variables
 Automatic Variables
 Extern Variables

5.2.1 Local Variables in C


Local variables in C are those variables that are declared inside a function or a block of
code. Their scope is limited to the block or function in which they are declared.

Example of Local Variable in C

// C program to declare and print local variable inside a function.

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

5.3.2. Global Variables in C


Global variables in C are those variables that are declared outside the function or a block
of code. Their scope is the whole program i.e. we can access the global variable anywhere in
the C program after it is declared.

Example of Global Variable in C

// C program to demonstrate use of global variable


#include <stdio.h>
int x = 20; // global variable
void function1()
{
printf("Function 1: %d\n", x); }
void function2()
{
printf("Function 2: %d\n", x); }
int main()
{
function1();
function2();
return 0;
}
Output
Function 1: 20
Function 2: 20
5.3.3. Static Variables in C
 The static variables in C are those variables that are defined using the static keyword.
 They can be defined only once in a C program and their scope depends upon the region
where they are declared (can be global or local).
 The default value of static variables is zero.
 As their lifetime is till the end of the program, they can retain their value for multiple
function calls as shown in the example.

Syntax of Static Variable in C

static datatype variable_name = initial_value;

Example of Static Variable in C


// C program to demonstrate use of static variable
#include <stdio.h>
void function()
{
int x = 20; // local variable
static int y = 30; // static variable
x = x + 10;
y = y + 10;
printf("\tLocal: %d\n\tStatic: %d\n", x, y);
}
int main()
{
printf("First Call\n");
function();
printf("Second Call\n");
function();
printf("Third Call\n");
function();
return 0;
}
Output
First Call
Local: 30
Static: 40
Second Call
Local: 30
Static: 50
Third Call
Local: 30
Static: 60
5.3.4. Automatic Variable in C
 All the local variables are automatic variables by default. They are also
known as auto variables.
 Their scope is local and their lifetime is till the end of the block. If we
need, we can use the auto keyword to define the auto variables.
 The default value of the auto variables is a garbage value.

Syntax of Auto Variable in C

auto data_type variable_name;


Example of auto Variable in C
// C program to demonstrate use of automatic variable
#include <stdio.h>
void function()
{
int x = 10; // local variable (also automatic)
auto int y = 20; // automatic variable
printf("Auto Variable: %d", y);
}
int main()
{
function();
return 0;
}
Output
Auto Variable: 20

5.3.5. External Variables in C


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

Syntax of Extern Variables in C


extern datatype variable name;

Example

#include "myfile.h"
#include <stdio.h>
void printValue()
{
printf("Global variable: %d", x);
}
5.3.6. Register Variables in C
 Register variables in C are those variables that are stored in the CPU register
instead of the conventional storage place like RAM.
 Their scope is local and exists till the end of the block or a function.
 These variables are declared using the register keyword.
 The default value of register variables is a garbage value.

Syntax of Register Variables in C


register datatype variable name = initial value;

// C program to demonstrate the definition of register variable


#include <stdio.h>
int main()
{
// register variable
register int var = 22;
printf("Value of Register Variable: %d\n", var);
return 0;
}
Output
Value of Register Variable: 22

6. OPERATORS in C

Operators can be defined as the symbols that help us to perform specific


mathematical, relational, bitwise, conditional, or logical computations on operands. In other
words, we can say that an operator operates the operands.
For example, ‘+’ is an operator used for addition, as shown below:
c = a + b;
Here, ‘+’ is the operator known as the addition operator, and ‘a’ and ‘b’ are operands.
The addition operator tells the compiler to add both of the operands ‘a’ and ‘b’.

6.1 Types of Operators in C


C has many built-in operators and can be classified into 6 types:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Other Operators
1. Arithmetic Operations in C
These operators are used to perform arithmetic/mathematical operations on
operands. Examples: (+, -, *, /, %,++,–). Arithmetic operators are of two types:
a) Unary Operators:
Operators that operate or work with a single operand are unary operators. For
example: Increment(++) and Decrement(–) Operators
int val = 5;
cout<<++val; // 6
b) Binary Operators:
Operators that operate or work with two operands are binary operators. For example:
Addition(+), Subtraction(-), multiplication(*), Division(/) operators
Example :
int a = 7;
int b = 2;
cout<<a+b; // 9
3. Ternary operator
A Ternary operator is an operator that operates on three operands and produces a new
value. ?:
Example: (a>b)? b:c (3 operand)

6.2 Types of operators


C programming language offers various types of operators having different
functioning capabilities.
6.2.1 Arithmetic Operators
C Arithmetic operators are used to perform mathematical calculations like addition,
subtraction, multiplication, division and modulus in C programs
Arithmetic operator operation Example value
+ Addition 2+3 5
- Subtraction 9-2 6
* multiplication 2*3 6
/ Division 9/3 3
% Modulus 9%2 1

Example Program

#include<stdio.h>
#include<conio.h>
void main()
{
int a=50,b=10,c;
clrscr();
c=a+b;
printf("The sum:%d",c);
getch();
}
Output:
The sum is 60
6.2.2 Relational Operators
 A relational operator checks the relationship between two operands. If the relation is
true, it returns 1; if the relation is false, it returns value 0.
 Relational operators are used in decision making and loops.
Operator Meaning Example value
> Greater than 2>3 0
< Less than 2<3 1
>= Greater than or equal to 2 >= 3 0
<= Less than or equal to 2 <= 3 1
== Equal to 2 == 3 0
!= Not equal 2!=3 1

Example Program

#include<stdio.h>
#include<conio.h>
void main()
{
int a=50,b=10;
clrscr();
printf("%d", a>b);
getch();
}
Output:
1
6.2.3 Logical Operators

 Logical operators combine the result of two or more logical conditions.


 An expression containing logical operator returns either 0 or 1 depending upon whether
expression results true or false.
 Logical operators are commonly used in decision making in C programming.

operator meaning Example value


&& Logical AND (2 > 3)&&(4>1) 0
|| Logical OR (2 >3)||(4>1) 1
! Logical NOT !(2>3) 1
Logical AND Logical OR Logical NOT
C1 C2 C1&&C2 C1 C2 C1||C2 C1 !C1
0 0 0 0 0 0 0 1
0 1 0 0 1 1 1 0
1 0 0 1 0 1
1 1 1 1 1 1

Example Program

#include<stdio.h>
#include<conio.h>
void main()
{
int a=10,b=9,c;
clrscr();
c=(a<b)||(a>b);
printf("c is %d",c);
getch();
}
Output:
c is 1
6.2.4 Assignment Operators

 An assignment operator is used for assigning a value to a variable.


 The most common assignment operator is =
Two types
a. Simple Assignment operator
a. Compound Assignment operator
Operator Meaning Example
Simple Assignment operator

= a=5 a=5

Compound Assignment operator

+= a += b a = a+b

-= a -= b a = a-b

*= a *= b a = a*b

/= a /= b a = a/b

%= a %= b a = a%b

Example Program

#include<stdio.h>
#include<conio.h>
void main()
{
int sum=10;
clrscr();
sum=sum+10;
printf("The sum:%d",sum);
getch();
}
Output:

The sum :20


6.2.5. Assignment Operators in C
Assignment operators are used to assign value to a variable. The left side operand of
the assignment operator is a variable and the right side operand of the assignment operator
is a value. The value on the right side must be of the same data type as the variable on the
left side otherwise the compiler will raise an error.
Different types of assignment operators are shown below:
a) “=”
This is the simplest assignment operator. This operator is used to assign the value on
the right to the variable on the left.
Example:

a = 10;
b = 20;
ch = 'y';
b) “+=”
This operator is the combination of the ‘+’ and ‘=’ operators. This operator first adds
the current value of the variable on left to the value on the right and then assigns the result
to the variable on the left.
Example:
(a += b) can be written as (a = a + b)
If initially value stored in a is 5.
Then (a += 6) = 11.
c) “-=”
This operator is a combination of ‘-‘ and ‘=’ operators. This operator first subtracts
the value on the right from the current value of the variable on left and then assigns the
result to the variable on the left.
Example:
(a -= b) can be written as (a = a - b)
If initially value stored in a is 8.
Then (a -= 6) = 2.
d) “*=”
This operator is a combination of the ‘*’ and ‘=’ operators. This operator first multiplies the
current value of the variable on left to the value on the right and then assigns the result to
the variable on the left.
Example:
(a *= b) can be written as (a = a * b)
If initially, the value stored in a is 5.
Then (a *= 6) = 30.
e) “/=”
This operator is a combination of the ‘/’ and ‘=’ operators. This operator first divides the
current value of the variable on left by the value on the right and then assigns the result to
the variable on the left.
Example:

(a /= b) can be written as (a = a / b)
If initially, the value stored in a is 6. Then (a /= 2) = 3.
Other Operators
Apart from the above operators, there are some other operators available in C used
to perform some specific tasks.
Some of them are discussed here:
6.2.1 sizeof operator
 sizeof is much used in the C programming language.
 It is a compile-time unary operator which can be used to compute the size of its
operand.
 Basically, the sizeof the operator is used to compute the size of the variable.
6.2.3 Comma Operator
 The comma operator (represented by the token) is a binary operator that
evaluates its first operand and discards the result, it then evaluates the
second operand and returns this value (and type).
 The comma operator has the lowest precedence of any C operator.
 Comma acts as both operator and separator.
6.2.4 Conditional Operator
The conditional operator is of the form Expression1? Expression2: Expression3
Here, Expression1 is the condition to be evaluated.
If the condition(Expression1) is True then we will execute and return the result of
Expression2 otherwise if the condition(Expression1) is false then we will execute and return
the result of Expression3.
We may replace the use of if..else statements with conditional operators.
To know more about the topic refer to this article.
6.2.5 dot (.) and arrow (->) Operators
 Member operators are used to referencing individual members of classes, structures,
and unions.
 The dot operator is applied to the actual object.
 The arrow operator is used with a pointer to an object.
6.2.6 Cast Operator
Casting operators convert one data type to another.
For example, int(2.2000) would return 2.
 A cast is a special operator that forces one data type to be converted into
another.
6.2.7 &,* Operator
Pointer operator & returns the address of a variable. For example &a; will give the
actual address of the variable.
The pointer operator * is a pointer to a variable. For example *var; will pointer to a variable
var.
6.2.6 Increment and Decrement Operators
 Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1.
 These two operators are unary operators, meaning they only operate on a single
operand.

Operator Meaning
++a Pre increment
--a Pre decrement
a++ Post increment
a-- Post decrement

Prefix
The operator precedes the operand (e.g., ++a). The value of operand will be altered
before it is used.
Postfix
The operator follows the operand. he value operand will be altered after it is used.
Program
#include <stdio.h>
#include<conio.h>
void main()
{
int c=2;
clrscr();
printf("c=%d\n",c++); //this statement displays 2 then,only incremented by 1to 3.
printf("c=%d",c); //this statement increments 1 to c then,only c is displayed.
getch();
}
Output:
C=2
C=3

6.2.7 Conditional Operator


 Conditional operators return one value if condition is true and returns another value is
condition is false.
 This operator is also called as ternary operator.
Syntax : (condition? True_value: false_value);

Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10,b=2,c;
clrscr();
c=a>b?a:b;
printf("The value of c is %d",c);
getch();
}
Output
The value of c is 10
6.2.7 Bitwise Operators
These operators are used to manipulate data at bit level. It operates on integers only.

operator meaning Example


& Bitwise AND 2 &3
| Bitwise OR 2|3
^ Bitwise XOR 2^ 3
<< Shift left 2 << 3
>> Shift right 2 >>3
~ one’s compliment ~2

Bitwise AND Bitwise OR Bitwise OR


A b a&b a b a|b a ~a
0 0 0 0 0 0 0 1
0 1 0 0 1 1 1 0
1 0 0 1 0 1
1 1 1 1 1 1
Bitwise XOR

A b a^b

0 0 1

0 1 0

1 0 0

1 1 0

Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10,b=2,c;
clrscr();
c=a>b;
printf("The value of c is%d",c);
getch();
}
Ouput:
The value of c is 1
E.g. 12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bit Operation of 12 and 25
00001100
& 00011001
________
00001000 = 8 (In decimal)
Bitwise OR Operation of 12 and 25
00001100
| 00011001
________
00011101 = 29 (In decimal)
7<< 2 (Shift Left)
0011 1100=12
3 >> 1 (Shift Right)
11 1=1
6.2.8 Special Operators

Operator Meaning
, Comma operators are used to link
related expressions together
& Address of operator
* Pointer to a variable
Sizeof () Returns length of variable in bytes
Program
#include <stdio.h>
int main()
{
int a;
float b;
double c;
char d;
printf("Size of int=%lu bytes\n",sizeof(a));
printf("Size of float=%lu bytes\n",sizeof(b));
printf("Size of double=%lu bytes\n",sizeof(c));
printf("Size of char=%lu byte\n",sizeof(d));
return 0;
}

Output:
Size of int = 4 bytes
Size of float = 4 bytes
Size of double = 8 bytes
Size of char = 1 byte

7. EXPRESSIONS – INPUT / OUTPUT STATEMENTS


7.1 Expression

Expression is a sequence of operands and operators that specifies the computation of the
value.
Example: a=2+3
2, 3 operands
+ = operator
Simple Expression:
If it has only one operator then it is called simple expression.
Example a=2+3
Compound Expression:
If it has more than one operator then it is called Compound expression
Example: A=2+3*5\4

7.2 Input and Output Statements


2.3.1 Streams
Streams acts in two ways. It is a source of a data as well as destination of data programs
input and output data from a stream.
We can input/output from the keyboard/monitor or from any file.

Keyboard Input stream Data

Monitor Output stream Data

Input and output streams


The input/output functions in ‘C’ is classified into two types
i) Formatted Input/output functions
ii) Unformatted Input/output functions

7.2.1 Formatting Input / Output


 C supports two formatting functions printf and scanf.
 When I/P & O/P is required in a specified format then the standard library
functions scanf( ) & printf( ) are used.
 printf is used to convert data stored in the program into text stream for output to
the monitor
 Scanf is used to convert text stream from the keyboard to data values and store
them in a program variables.
 These functions are collectively known as Standard I/O Library and is in stdio.h
header file.
 Formatted input, output functions can be used to read and write all types of data
values.
printf ( )
 The printf function stands for print formatting.
 It is used to display information required by the user and also prints the values of the
variables.
Syntax:
printf (“The text to be printed“);
printf (“control string”, var1,var2,…,varn);
 Some printf statements may contain only a text string that has to be displayed on
the screen.
 The control string may also contain text to be printed, specific format specifier and
escape sequence include \n,\t,\r,\a etc.

scanf ()
 The function scanf () stands for scan formatting.
 It is used to read formatted data from the keyword.
 It ignores any blank spaces, tabs, new lines entered by the user.
Syntax:
scanf(“control string”,&var1,&var2….,&varn);

Example:
int age;
scanf(“%d”,age);

 control string specifies type and format of the data that has to be obtained from
the keyboard and stored in the memory location of the variable.& is a unary
operator, stores the value in the address of a variable

 Basic control string


Data type Control String/Format Specifier
int %d
float %f
char %c
string %s

Program
#include<stdio.h>
#include<conio.h>
void main()
{
int num;
clrscr();
printf("Enter the number");
scanf("%d",&num);
printf("The number is %d",num);
getch();
}
Output:
Enter the number 45
The number is 45

7.2.2 Unformatted Input /Output function


 It does not require any format specifier.
 It works with character data type.
 They are used when I/P & O/P is not required in a specific format.
 C has 3 types I/O functions.
a) Character I/O
b) String I/O
c) File I/O

a) getchar() and putchar():


getchar():It read a single character from the keyword.
putchar():It prints single character on the screen at a time.
Syntax
char variablename = getchar();
putchar(variablename);

Example
char ch;
a=getchar();
putchar(a);
Progrm
#include<stdio.h>
#include<conio.h>
void main()
{
char a;
clrscr();
printf("Enter the charcter\n");
a=getchar();
putchar(a);
}
Output:
Enter the Character
a
a

b) gets() and puts()


gets():It accepts any line of string including spaces from input devices. It stops reading
only when the enter key is pressed.
puts():displays the string on the output screen
Syntax
gets(variablename);
puts(variablename);

Example:
gets(a);
puts(a);

Program
#include<stdio.h>
#include<conio.h>
void main()
{
char a[10];
clrscr();
printf("Enter the string\n");
gets(a);
puts("The string is");
puts(a);
getch();
}
Output:
Enter the string
C programming
The string is
C programming
c) getch() and putch()
getch(): getch() is used to get a character from keyboard but does not echo to the output
screen.
putch(): putch() is used to writes a character directly on the output screen.

Syntax:
char variablename=getch();
putch(variablename);
Example:
char ch;
ch= getchar();
putch(ch);

Example:

#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("Enter the character \n");
ch= getchar();
printf("\nEntered charcter is\n");
putch(ch);
getch();
}
Output:
Enter the character
A
Entered character is
A
c) getche(): getche() reads a single character from the keyboard and echoes it to the output
screen
Example:

#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("Enter the string");
ch= getche();
printf("Input char %c",ch);
getch();
}
Output:
Enter the string t
Input char t.

Difference between scanf() and gets()

S.No scanf() gets()


1 It does not read blank spaces in It reads string with blank
between the string space
2 Example: Example:
Input: Hello world Input: Hello world
Output: Hello Output:Hello world

Difference between printf() and puts()

S.No printf() puts()


1 In printf() we use \n to move the In puts() it automatically
cursor to next line moves the cursor to next
line

Difference between getch() and getche()

S.No getch() getche()


1 getch() is used to get a character getche() reads a single
from keyboard but does not character from the keyboard
echo to the output screen. and echoes it to the output
screen

Difference between getchar() and getch()

S.No getchar() getch()


1 After reading the character After reading the character
from keyboard, it is kept in from keyboard, it display
buffer. and it never waits for enter
After pressing ENTER key it is key to pressed
displayed on the screen
8. DECISION MAKING STATEMENTS

 The order in which program statements are executed is known as flow of control.
 By default program control flows sequentially from top to bottom.
 C supports two types of decision control statements that can alter the flow of a sequence
of instruction.
i)Conditional branching
ii) Unconditional branching
8.1 Conditional branching

 The conditional branching statements help to jump from one part of the program to another
depending on a whether a particular condition is satisfied or not.
 These decision control statements include
i) if statement
ii) if else statements
iii) if else if statement
iv) nested if else
v) switch
8.1.1 if statement
 It is a simple decision making statement. It executes only true condition statements.
 It checks for the condition .If the condition is true, if block statements are executed.

Syntax

if (condition)
{
statements;
}

Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
printf("Enter the number");
scanf("%d",&a);
if(a>=0)
{
printf("%d is a positive number ",a);
}
}
Output:
Enter the number
12
12 is a positive number
8.1.2 if..else statement
 It is also called as two way decision statement
 If the condition is true, if block statements are executed and else block is skipped.
 If the condition is false, else block is executed and if block is skipped.
Syntax
if(condition)
{
Statements;
}
else
{
Statements;
}
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
printf("Enter the number");
scanf("%d",&a);
if(a>=0)
{
printf("\n %d is a positive number ");
}
else
{
printf("\n %d is a negative number");
}

getch();
}
Output:
Enter the number
-12
12 is a negative number
8.1.3 if else if statement
 It is known as multiway decision making statement.

 Each and every else block have if statement except last else block.

 Syntax

if( condition)
{
Statements;
}
else if(condition)
{
Statements;
}
else if(condition)
{
Stateemnts;
}
else
{
Statements;
}
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int num;
printf("Enter any number");
scanf("%d",&num);
if(num==0)
{
printf("The numeber is zero");
}
else if(num>0)
{
printf("The number is positive");
}
else
{
printf("The numeber is negative");
}
}
Output:
Enter any number -2
The number is negative
8.1.4 Nested if..else
An if statement or if..else statement in another if..else statement is called as Nesting
and the statement is called nested if..else statements.
syntax
if(condition1)
{
if(condition2)
{
true Statement of condition2;
}
else
{
False Statement of condition 2;

}
}
else
{
False Statement of condition 1;
}
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10,b=20,c=40;
if((a>b)&&(a>c))
{
printf("%d is greatest",a);
}
else
{
if(b>c)
{
printf("%d is greatest",b);
}
else
{
printf("%d is greatest",c);
}
}

}
Output:
40 is greatest

8.1.4 Switch Statement


 It is a multiway decision making statement. The selection is based on the valued in the
switch statement.
 When there are more conditions, it becomes too difficult and complicate to use if and if.
else statement
Syntax
switch(expression)
{
case constant1 :
statement block1;
break;
case constant2:
statement block2;
break;
.
. .
default :
default block;
break;
}
 Expression value must be integer or character.
 Each case label should be followed with a constant
 Case labels must end with a colon
 Each case block and default block must be terminated with break statements
 No case constants are identical
 The default label is optional and can be placed anywhere in the switch statement.
 There can be only one default statement in a switch statement.
 C permits nested switch statement.
 The value of switch expression is compared with the case constant expression from top
to bottom.

Program
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
switch(i)
{
case 1:
printf("One”);
break;
case 2:

printf("Two”);
break;
default:
printf(“Above Three”);
}
getch();
}
Output:
One
9. LOOPING STATEMENTS
Iteration is a process of repeating the same set of statements again and again until
specified condition becomes false
There are 3 types
i) for
ii) while
iii) do-while
Loops are classified as
 Counter controlled loops
 Sentinel controlled loops
Counter controlled loops
The number of iterations is known in advance. They use a control variable called loop
counter.
Also called as definite repetitions loop.
E.g: for
Sentinel controlled loops
The number of iterations is not known in advance. The execution or termination of the
loop depends upon a special value called sentinel value.
Also called as indefinite repetitions loop.
E.g: while

9.1 for loop:

 It is a repetitive control structure. It executes set of statements repeatedly until the


condition is false
 Number of iteration known in advance

Syntax:

for(initialization; condition; increment/decrement)


{
body of the loop;
}

Initialization section: It is used to initialize the staring value of the loop counter
Condition: The expression is evaluated.
1.if it evaluates true, body of the loop is executed
2. if it evaluates false, program control is transferred to statements
present next to the for loop
Increment/decrement: After the execution of body of the loop, increment and decrement of
loop counter is performed.
Execution of for loop
1. Initialization section is executed only once.
2. Condition is evaluated
a. If it is true, loop body is executed.
b. If it is false, loop is terminated
3. After the execution of loop, the manipulation expression is evaluated.
4. Steps 2 & 3 are repeated until step 2 condition becomes false.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
printf("The numbers are");
for(i=1;i<=4;i++)
{
printf("\n%d",i);
}
getch();
}
Output:
The numbers are
1
2
3
4

Example: To find the sum of n natural number. 1+2+3…+n


#include<stdio.h>
#include<conio.h>
main()
{
int n, i, sum=0;
clrscr();
printf(“Enter the value for n”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
sum=sum+i;
}
printf(“Sum=%d”, sum);
getch();
}
Output:
Enter the value for n 4
sum=10
9.2. While loop

 They are also known as Entry controlled loops because here the condition is
checked before the execution of loop body.
 The condition is checked first, if it is true it executes the body of the loop until the
condition becomes false.
 The number of iteration need not be known in advance

Syntax
while(condition)
{
Statements;
}

Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
printf("The numbers are");
i=1;
while(i<4)
{
printf("\n%d",i);
i++;
}
getch();
}

Output:
The numbers are
1
2
3

9.3 do..while loop

 They are also known as Exit controlled loops because here the condition is checked after
the execution of loop body.
 The body of the loop is executed first and test condition is checked at the end of the
loop.
 The body of the loop is executed atleast once even if the condition is false.
Number of iteration need not be known in advance

Syntax
do
{
Statements

}while(condition);

Example:

#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
printf("The numbers are");
i=1;
do
{
printf("\n%d",i);
i++;

} while(i<4);
getch();
}
Output:
The numbers are
1
2
3

9.4 Nested loops


If the body of a loop contains another iteration statement, then we say that the loops are
nested.
Loops within a loop are known as nested loop.
While do…while
The condition is checked at the beginning The condition is checked at the end
The condition must be initially true The condition need not be initially true
It may or may not be executed at least once It may be executed at least once
It is an entry controlled loop It is an exit controlled loop

10. Introduction to Arrays


 An Array is a collection of similar data elements. These data elements have same data
types
 Array is a collection of elements of same data type stored under common name.
 An array is a data structure that is used for storage of homogeneous data.
 It is classified into three types
i) One dimensional Array
ii) Two dimensional Array
iii) Multi-dimensional Array
10.1 Characteristics of an Array
 The elements of the array are stored in continuous memory location.
 Individual elements of an array can be accessed with the integer value known as index.
 Array index starts from 0.

 Memory space of an array can be calculated as


Size of datatype * number of elements of an array
 The location of an array in the location of its first element.
 A variable that can store multiple values is an array variable.
 It is a derived data type which stores related information together.
 The length of an array is the number of elements in the array.
 Arrays are used in the situation where we are asked read and prints the marks of 30
students .It is inefficient way of declaring 30 variables to hold marks. So the concept of
Array is used where one common variable is used for assigning 30 values.

10.2 Advantage of an array


 It is used to represent multiple data items of same type by using only single name.
 2D arrays are used to represent matrices.
 It allows random accessing of elements i.e. any element of the array can be randomly
accessed using indexes
10.3 Disadvantage of an array
 Insertion and deletion of elements in an array is difficult
 Size of the Array should be known in advance.
 Elements in the Array must be same data type

10.4 One dimensional array - Declaration, Initialization


 One dimensional array is collection of elements of same data type organized as a
simple linear sequence.
 Elements of an array can be accessed by using a single subscript.
10.4.1 Declaration of one dimensional Array
We need to declare the array variable before they are used. To declare and define
an array we must specify its name, type and size.
Syntax:
datatype arrayname[size];
datatype : kind of values it can store Example int, float, char, double.
arrayname : variable name of an Array
Size : maximum number of values that an array can hold.
Example
int a[4];

a. Initialization of One Dimensional Array


10.4.1.1 Compile time initialization: Initialization of the values of an array at the time of
declaration.
datatype arrayname [size] = {list of values separated by comma};

Example
int a[4]={20,45,67,89};
Sample program1:

Array element can be accessed using the index

#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a[4]={20,45,67,89};
printf(“%d \t%d\t%d\t%d”,a[0],a[1],a[2],a[3]);
getch();
}

Output:

20 45 67 89

Sample program2:
The efficient way of accessing array elements is using loop

#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a[4]={20,45,67,89};
int i;
for(i=0;i<4;i++)
{
printf(“%d\t”,a[i]);
}
getch();
}
Output:
20 45 67 89

Note:
By default the elements of an array are not initialized. They may contain some garbage
value, so before using array we must initialize the array or read some meaningful data into it.
10.4.1.2 Run time initialization:
The value of an Array can be initialized during run time.

int a[4];
for(i=0;i<4;i++)
{
scanf(“%d”,&a[i]);
}
Sample program 3
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a[4],i;
printf(“Enter the Elements\n”);
for(i=0;i<4;i++)
{
scanf(“%d\t”,&a[i]);
}
Printf(“The Elements are\n”);
for(i=0;i<4;i++)
{
printf(“%d\t”,a[i]);
}
getch();
}
Output:
Enter the Elements
20 45 67 89
The Elements are
20 5 67 89
10.5 Two dimensional array
 It is a collection of data elements of same data type arranged in rows and columns.
 It is collection of one dimensional array.
 An array with two subscript is called two dimensional arrays.
 It enables us to store multiple rows of elements such as table of values or matrix.
 Referring to Array Elements:
To access the elements of a two-dimensional array, we need a pair of indices: first
index selects the row and the second index selects the column.
Syntax:
datatype arrayname[size of row][size of column];
Example: int A[3][2];
Col Col
0 1
Row 0 A[0][0] A[0][1]
Row 1 A[1][0] A[1][1]
Row 2 A[2][1] A[2][2]

10.5.1 Compile Time Initialization


 An two-dimensional array can be initialized along with declaration.
 For two-dimensional array initialization, elements of each row are enclosed within
curly braces and separated by commas.
 All rows are enclosed within curly braces.
Syntax:
datatype arrayname[size of row][size of column]={values separated by comma};
Example:
int a[3][2]={{10,20},{30,40},{50,60}};

Col 0 Col 1

Row 0 10 20
Row 1 30 40
Row 2 50 60
Sample program 4:
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a[3][2]={{10,20},{30,40},{50,60}};
printf(“%d\t”,a[0][0]);
printf(“%d\n”,a[0][1]);
printf(“%d\t”,a[1][0]);
printf(“%d\n”,a[1][1]);
printf(“%d\t”,a[2][0]);
printf(“%d\n”,a[2][1]);
}

Output:
10 20
30 40
50 60
Sample program 5

#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][2]={{10,20},{30,40},{50,60}};
int i,j;
printf("\nThe Matrix");
for(i=0;i<2;i++)
{
printf("\n");
for(j=0;j<2;j++)
{
printf("\t%d",a[i][j]);
}
}
getch();
}
Output:
10 20
30 40
50 60

10.5.2 Run time initialization:


Two-dimensional array can be initialization at run time using loop.

int a[2][3];
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
scanf(“%d”, &a[i][j]);
}
}

Sample program 5:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[2][3];
int i,j;
printf(“Enter the elements\n”);
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
scanf(“%d”, &a[i][j]);
}
}

printf(“\nThe elements are”);


for(i=0;i<2;i++)
{
printf(“\n”);
for(j=0;j<3;j++)
{
printf(“%d\t”, a[i][j]);
}
}

}
Output:
Enter the elements
1
2
3
4
The elements are
1 2
2 4

1. Write a C program to calculate sum of individual digits of a given number.


ALGORITHM:
1. Get the number
2. Declare a variable to store the sum and set it to 0
3. Repeat the next two steps till the number is not 0
4. Get the rightmost digit of the number with help of remainder ‘%’ operator by dividing it
with 10 and add it to sum.
5. Divide the number by 10 with help of ‘/’ operator
6. Print or return the sum

PROGRAM:
#include<stdio.h>
int main()
{
int n,sum=0,m;
printf("Enter a number:");
scanf("%d",&n);
while(n>0)
{
m=n%10;
sum=sum+m;
n=n/10;
}
printf("Sum is=%d",sum);
return 0;
}

Output:
Enter a number:654
Sum is=15
2. Write a C program to count no. of positive numbers, negative numbers and zeros in the
array.

ALGORITHM:
Step 1: Get the 10 values in an array
Step 2: if arr[i]>0
increment the positive count(countp)
else if arr[i]==0
increment the zero count (countz)
else
increment the negative count (countn)
Step 3: stop

PROGRAM:
#include<stdio.h>
#include<stdio.h>
#define N 10
int main()
{
int a[N], i, p = 0, n = 0, z = 0;

printf("Enter %d integer numbers\n", N);


for(i = 0; i < N; i++)
scanf("%d", &a[i]);

for(i = 0; i < N; i++)


{
if(a[i] > 0)
p++;
else if(a[i] < 0)
n++;
else
z++;
}

printf("\nPositive no: %d\nNegative no: %d\nZeros: %d\n", p, n, z);

return 0;
}

OUTPUT:
Enter 10 numbers : 12
23
-56
0
-34
23
0
0
56
-76
Positive numbers=4
Negative numbers=3
Zero=3

3. Write a C program to find sum of two numbers using functions with arguments and
without return type.
ALGORITHM:
Step 1: Read the values of a and b
Step 2: Call the function sum with arguments a and b
Step 3: 3.1In the function definition
3.2 Compute the addition of x and y and store the result in z
3.3 print the result
Step 4: Function does not return any value
Step 5: stop
PROGRAM:
#include<stdio.h>
void main()
{
int a,b;
//clrscr();
printf("Enter Two Number : ");
scanf("%d%d",&a,&b);
sum(a,b);
getch();
}
sum(int x,int y)
{
int z;
z=x+y;
printf("Sum of Two Number is : %d",z);
}
Output :
Enter Two Number : 10 20
Sum of Two Number is : 30

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy