Unit 1 Notes C Programming (2) For First Year
Unit 1 Notes C Programming (2) For First Year
4. Decision: Diamond symbol represents a decision point. Decision based operations such as
yes/no question or true/false are indicated by diamond in flowchart.
5. Connectors: Whenever flowchart becomes complex or it spreads over more than one page, it
is useful to use connectors to avoid any confusions. It is represented by a circle.
6. Flow lines: Flow lines indicate the exact sequence in which instructions are executed. Arrows
represent the direction of flow of control and relationship among different symbols of flowchart.
Rules For Creating Flowchart :
A flowchart is a graphical representation of an algorithm.it should follow some rules while
creating a flowchart
Rule 1: Flowchart opening statement must be ‘start’ keyword.
Rule 2: Flowchart ending statement must be ‘end’ keyword.
Rule 3: All symbols in the flowchart must be connected with an arrow line.
Rule 4: The decision symbol in the flowchart is associated with the arrow line.
Advantages of Flowchart:
It is difficult to draw flowcharts for large and complex programs. There is no standard to
determine the amount of detail.
Some developer thinks that it is waste of time.It makes software processes low.
5. ALGORITHM:
An algorithm is a step-by-step procedure to solve a given problem. In the context of computer
science, particularly with the C programming language, an algorithm is used to create a solution
that computers can understand and execute.
It is essential to have a strong understanding of algorithms in C to create efficient programs and
solve complex problems. Dive deeper into the basic concepts, types, and design techniques of
algorithms in C in the following sections.
Basic concepts of algorithm in C:
#include <stdio.h>
int main() {
printf("Hello World!");
return 0;
}
o/p:Hello World
Simple program:
#include <stdio.h>
int main() {
int a = 10;
printf("%d", a);
return 0;
}
o/p:10
STRUCTURE OF C PROGRAM
The structure of a C program means the specific structure to start the programming in the
C language.
It gives us a basic idea of the order of the sections in a program. We get to know when
and where to use a particular statement, variable, function, curly braces, parentheses, etc.
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. Declaration
5. Main() Function
{
Declaration part;
Executable part;
}
6. Sub Programs
Function 1
Function 2
…………..
…………..
Function n
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.
A comment makes the program easier to read and understand. These are the statements
that are not executed by the compiler or an interpreter.
Syntax
/*Comment starts
continues
continues
Comment ends*/
2. Preprocessor Section
The preprocessor section contains all the header files used in a program. It informs the
system to link the header files to the system libraries, Preprocessors are programs that process
our source code before compilation. Preprocessor directives start with the ‘#’ symbol.
There is no semi-colon (;) at the end
#include<stdio.h>
#include<conio.h>
The #include statement includes the specific file as a part of a function at the time of the
compilation. Thus, the contents of the included file are compiled along with the function being
compiled. The #include<stdio.h> consists of the contents of the standard input output files,
which contains the definition of stdin, stdout, and stderr. There are various header files available
for different purpose
3. Definition
4. Declaration
The variables declared in this section can be used anywhere in the program.
EX:
Float num=2.54;
Int a=5;
Char ch=’z’;
There are two types of declaration
Local variable: A variable that is declared and using inside the function declared and using
inside the function or block is called local variable
Ex:
int a=4;
int b= 5;
return a+b;
Global variable: A variable that is declared outside the function or block is called a global
variable
Ex:
int a=4;
int b=5;
return a+b;
}
5. Main() Function
Every C program must have a 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.
int main()
Or
void main()
6. Sub Programs
The user defined functions specified the functions specified as per the requirements of the
user. For example, color(), sum(), division(), etc.
The control of the program is shifted to the called function whenever they are called
from the main or outside the main() function
Ex:
return x+y;
}
Example Program
/**
* file: sum.c
* author: you
*/
// Link
#include <stdio.h>
// Definition
#define X 20
// Global Declaration
// Main() Function
int main(void)
int y = 55;
printf("Sum: %d", sum(y));
return 0;
// Subprogram
int sum(int y)
return y + X;
Output
Sum: 75
TOKENS IN C:
A token in C can be defined as the smallest individual element of the C programming language
that is meaningful to the compiler. It is the basic component of a C program.
Types of Tokens in C
The tokens of C language can be classified into six types based on the functions they are used to
perform. The types of C tokens are as follows:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
C Token – Keywords
The keywords are pre-defined or reserved words in a programming language. Each
keyword is meant to perform a specific function in a program. Since keywords are referred
names for a compiler, they can’t be used as variable names because by doing so, we are trying to
assign a new meaning to the keyword which is not allowed. You cannot redefine keywords.
However, you can specify the text to be substituted for keywords before compilation by using C
preprocessor directives. C language supports 32 keywords which are given below:
const float short unsigned continue for signed void
default goto sizeof volatile do if static while
C Token – Identifiers
Identifiers are used as the general terminology for the naming of variables, functions, and
arrays. These are user-defined names consisting of an arbitrarily long sequence of letters and
digits with either a letter or the underscore(_) as a first character. Identifier names must differ in
spelling and case from any keywords. You cannot use keywords as identifiers; they are
reserved for special use. Once declared, you can use the identifier in later program statements to
refer to the associated value. A special identifier called a statement label can be used in goto
statements.
Rules for Naming Identifiers
Certain rules should be followed while naming c identifiers which are as follows:
They must begin with a letter or underscore(_).
They must consist of only letters, digits, or underscore. No other special character is
allowed.
It should not be a keyword.
It must not contain white space.
It should be up to 31 characters long as only the first 31 characters are significant.
Note: Identifiers are case-sensitive so names like variable and Variable will be treated as different.
For example,
main: method name.
a: variable name.
C Token – Constants
The constants refer to the variables with fixed values. They are like normal variables but with the
difference that their values can not be modified in the program once they are defined.
Constants may belong to any of the data types.
Examples of Constants in C
const int c_var = 20;
const int* const ptr = &c_var;
C Token – Strings
Strings are nothing but an array of characters ended with a null character (‘\0’). This null
character indicates the end of the string. Strings are always enclosed in double quotes. Whereas,
a character is enclosed in single quotes in C and C++.
Examples of String
char string[20] = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘\0’};
char string[20] = “geeksforgeeks”;
char string [] = “geeksforgeeks”;
Pre-processor (#): The preprocessor is a macro processor that is used automatically by the
compiler to transform your program before actual compilation.
C Token – Operators
Operators are symbols that trigger an action when applied to C variables and other objects. The
data items on which operators act are called operands.
Depending on the number of operands that an operator can act upon, operators can be
classified as follows:
Unary Operators: Those operators that require only a single operand to act upon are known
as unaryoperators.For Example increment and decrement operators
Binary Operators: Those operators that require two operands to act upon are called
binaryoperators. Binary operators can further are classified into:
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operator
Ternary Operator: The operator that requires three operands to act upon is called the ternary
operator. Conditional Operator(?) is also called the ternary operator
CHARACTER SET IN C
In the C programming language, the character set refers to a set of all the valid characters that
we can use in the source program for forming words, expressions, and numbers.
The source character set contains all the characters that we want to use for the source program
text.
On the other hand, the execution character set consists of the set of those characters that we
might use during the execution of any program. Thus, it is not a prerequisite that the execution
character set and the source character set will be the same, or they will match altogether
Digits
The C programming language provides the support for all the digits that help in constructing/
supporting the numeric values or expressions in a program. These range from 0 to 9, and also
help in defining an identifier. Thus, the C language supports a total of 10 digits for
constructing the numeric values or expressions in any program.
Digits 0 to 9 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Characters
We use some special characters in the C language for some special purposes, such as logical
operations, mathematical operations, checking of conditions, backspaces, white spaces, etc.
We can also use these characters for defining the identifiers in a much better way. For instance,
we use underscores for constructing a longer name for a variable, etc.
The C programming language provides support for the following types of special characters:
White Spaces
Blank Spaces
Carriage Return
Tab
New Line
Summary of Special Characters in C
Here is a table that represents all the types of character sets that we can use in the C language:
DATA TYPE IN C
Data types in c refer to an extensive 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.
Each data type has a size defined in bits/bytes and has a range for the values that these
data types can hold.
The Primitive or primary data type in the C programming language are the basic data
types. All the Primitive data types are already defined in the system. There are four primitive
data types
Integer Data type
The integer data type in C is used to store the whole numbers without decimal values.
Integer data type is represented by the ‘int’ keyword, and it can be both signed and
unsigned.
By default, the value assigned to an integer variable is considered positive if it is
unsigned.
The integer data type is further divided into short, int, and long data types.
What is a signed data type: Using signed data type both positive and negative values we
can store.
What is the unsigned data type: Using unsigned data types; we can store only positive
values.
What is a short and long data type:
If you need to use a large number, you can use a type specifier long
If you need to use a small integer number, you can use a type specifier short
Syntax
int variable_name;
Data type Meaning Memory Range Format
size Specifier
signed short int The signed short data type is used 2 -32,768 to 32,767 %hd
to store positive and negative small
integer values.
signed int The signed data type is used to 4 -2,147,483,648 to %d
store positive and negative integer 2,147,483,647
values.
signed long int The signed long data type is used to 4 -2,147,483,648 to %ld
store positive and negative long 2,147,483,647
integer values.
unsigned short int The unsigned short data type is 2 0 to 65,535 %hu
used to store only positive small
integer values.
unsigned int The unsigned data type is used to 4 0 to 4,294,967,295 %u
store only positive integer values.
unsigned long int The unsigned long data type is used 4 0 to 4,294,967,295 %lu
to store only positive long integer
values.
Example program
#include <stdio.h>
int main()
int a = 9;
int b = -9;
return 0;
Output
Character data type allows its variable to store only a single character.
The storage size of the character is 1.
For char data type, it is necessary to enclose our data in single quotes.
Syntax
char variable_name = ‘value’;
The character data type is divided into two types one is signed data type and the second
one is unsigned data type. Both Signed data type and unsigned data type occupy only one
byte of memory.
Unsigned means it will accept only positive values and the signed means it will accept
both positive as well as negative values. Whatever the type either signed or unsigned, the
character occupies only one byte.
Data Type Memory (bytes) Range Format Specifier
Example program
#include <stdio.h>
void main()
char c;
c = 'a' ;
printf("%c"c);
Output
float varaible_name;
Data type Meaning Memory Range PRECISION Format
(byte) Specifier
float float’ used to stores real 4 byte 1.2E-38 to 6 decimal places %f
numbers in 32 bits with 3.4E+38
up to 6 decimal points
precision.
double double type also similar 8 byte 2.3E-308 to 14 decimal places %lf
to float stores in 64 bits 1.7E+308
with more accurate
precision up to 14
decimals
long double Long double further 10 byte 3.4E-4932 19 decimal places %Lf
extends the precision to
using 80 bits and 19 1.1E+4932
decimal places.
Example program
#include <stdio.h>
int main()
float a = 9.0;
double b = 12.293123;
return 0;
Output:
This means no value. This data type is mostly used when we define functions.
The void data type is used when a function does not return anything. It occupies 0
bytes of memory. We use the void keyword for void data type.
Syntax
void function()
DERIVED DATATYPE
The data-types that are derived from the primitive or built-in datatypes are referred to
as Derived Data Types.
Derived data types do not create new data types. Instead, they add some functionality to
the existing data types.
Derived data types are derived from the primitive data types by adding some extra
relationships with the various elements of the primary data types. The derived data type
can be used to represent a single value or multiple values.
Given below are the various derived data types used in C
Array.
Functions.
Pointers.
Array
An array is one of the most frequently used data types (derived) in the C language. We
can form arrays by collecting various primitive data types such as int, float, char, etc. Thus,
when we create a collection of these data types and store them in the contiguous memory
location, they are known as arrays.
Syntax
data_type arr_name[size];
Example program
#include<stdio.h>
int main(){
Int i=0;
int marks[5];//declaration of array
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75; //traversal of array
for(int i=0;i<5;i++)
{
printf("%d \n",marks[i]);
}//end of for loop
return 0; }
Output
80 60 70 85 75
Function
A function is a piece of code that performs some specific task when invoked in the
program. It can be called from anywhere and any number of times in the program. The return
value i.e., what type of value it will return depends upon the return type of the function.
In C, a function can be called by types: call by value and call by reference. When the
function is called by value, a copy of the variable is passed as the argument whereas when the
function is called by the reference, the address or reference of variable itself is passed to the
function.
Syntax
return_type function_name(parameters);
Example program
#include<stdio.h>
Void main()
int x, y;
Printf(“enter 2 number”);
Sum(x,y);
int c;
c=x+y;
Printf(“%d”, c);
Output
Enter 2 number
21
Pointers
A pointer can be defined as a variable that stores the address of other variables. This
address signifies where that variable is located in the memory.
Syntax: datatype *pointer_name;
Description of the syntax
type: This is the data type that specifies the type of value to which the pointer is
pointing.
pointer_name: This is the name of the pointer. To specify the name of a pointer,
you must follow the same rules which are applicable while declaring a usual
variable in C. Apart from these rules, a pointer must always be preceded by an
asterisk(*).
Example program
#include <stdio.h>
#include <conio.h>
int main ()
{
int count = 5; //declaring the local variables
int *ptr = &count; //pointer variable
printf("The value of count variable is %d\n", count);
printf("Address of count variable: %x\n", ptr);
getch();
return 0;
}
Output
The value of count variable is 5
Address of count variable: da5f4764
STRUCTURES
Structures are used to group multiple variables of different data types. It gathers
together, different atomic information that comprises a given entity.
Members of the structures can be accessed using the dot (.) operator.
Syntax
Struct <name>
};
Example program
#include <stdio.h>
char name[100];
int number_of_pages;
char author[100];
float price;
};
int main()
strcpy(myBook.name, "CLRS");
strcpy(myBook.author, "C.L.R.S.");
myBook.price = 1000.0;
myBook.number_of_pages = 2000;
OUTPUT
Price: 1000.000000
UNION
union <name>
Example program
# include<stdio.h>
struct book {
char name[100];
int pages;
int prices;
};
union Book {
char name[100];
int pages;
int price;
};
int main() {
Output
Pages in myBook: 10
Price in myBook: 10
ENUMERATIONS (ENUM)
enum <identifier>
enum month {
JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC
};
enum monthDays {
};
enum colors {
};
int main() {
Output
Favorite Color: 3
VARIABLES IN C
Example:
int rollno;
char gender;
char name[20];
float salary;
1. Local Variable : A variable that is declared and used inside the function or block is
called local variable. It’s scope is limited to function or block. It cannot be used outside
the block.Local variables need to be initialized before use.
2. Global Variable : A variable that is declared outside the function or block is called a
global variable. It is declared at the starting of program. It is available to all the
functions.
3. Example –
If you want to read the information or if you want to display the information, formatting
is very important. In which format do you have to read information and in which format do you
have to print the information. That you have to specify to the computer using a format specifier
Example:
#include <stdio.h>
int main()
{
int a = 10;
printf("%d", a);
return 0;
}
Output: 10
C OPERATORS
Operators in C Language are the special kind of symbols that performs certain operations
on the data.
The collection of operators along with the data or operands is known as expression.
There are following types of operators to perform different types of operations in C
language.
UNARY OPERATION
A Unary Operator in C is an operator that takes a single operand in an expression or a
statement.
Types of Unary Operators are:
Increment operators (++): Example: (++x)
Decrement operators (–): Example: (--x)
Increment Operators
Increment Operators is a unary operator. It takes one value at a time.
Post Increment Operators: A post-increment operator is used to increment the value of the
variable after executing the expression completely in which post-increment is used. In the Post-
Increment, value is first used in an expression and then incremented.
Syntax: Variable++;
Example: x++;
Pre Increment Operators: A pre-increment operator is used to increment the value of a variable
before using it in an expression. In the Pre-Increment, value is first incremented and then used
inside the expression.
Syntax: ++Variable;
Example: ++x;
Example program
#include<stdio.h>
int main()
{
int a = 11, b = 90;
printf("++a = %d \n", ++a);
printf(“b++ = %d \n", b++);
return 0;
}
Output
++a = 12
b++ = 91
Decrement Operators
Decrement Operators is a unary operator. It takes one value at a time.
Decrement Operators are used to increase the value by one
It is classified into two types:
Post Decrement Operator
Pre Decrement Operator
Post Decrement Operators: A post-decrement operator is used to decrement the value of the
variable after executing the expression completely in which post-decrement is used. In the Post-
decrement, value is first used in an expression and then decremented.
Syntax: Variable--;
Example: x--;
Syntax: --Variable;
Example: --x;
Example Program
#include<stdio.h>
int main()
{
int a = 11, b = 90;
printf(“--a = %d \n", --a);
printf(“b--= %d \n", b--);
return 0;
}
Output
--a = 10
b-- = 89
Binary Operators
Arithmetic Operator
Arithmetic Operators are the operators which are used to perform mathematical
calculations. It performs all the operations on numerical values (constants and variables).
Operator Name Description Example
Example Program
#include <stdio.h>
int main()
{
int a = 7,b = 5, c;
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
printf("Remainder when a is divided by b = %d \n",c);
return 0;}
Output
a+b = 12
a-b = 2
a*b = 35
a/b = 1
Remainder when a divided by b = 2
Logical Operator
Logical operators are used to determine the logic between variables or values
The logical operators are used when we want to check or test more than one condition
and make decisions.
It returns either 0 or 1 depending upon the condition whether the expression results in
true or false.
! Logical not Reverse the result, !(x < 5 && x < 10)
returns false if the
result is true
Example Program
#include <stdio.h>
int main()
{ int a = 15, b = 15, c = 20, results;
results = (a == b) && (c > b);
printf("(a == b) && (c > b) is %d \n", results);
results = (a == b) && (c < b);
printf("(a == b) && (c < b) is %d \n", results);
results = (a == b) || (c < b);
printf("(a == b) || (c < b) is %d \n", results);
results = (a != b) || (c < b);
printf("(a != b) || (c < b) is %d \n", results);
results = !(a != b);
printf("!(a != b) is %d \n", results);
results = !(a == b);
printf("!(a == b) is %d \n", results); return 0;
}
Output
(a == b) && (c > b) is 1
(a == b) && (c < b) is 0
(a == b) || (c < b) is 1
(a != b) || (c < b) is 0
!(a != b) is 1
!(a == b) is 0
Bitwise Operator
Bitwise operator is used for the manipulation of data at the bit level.
Bitwise operator first converts the integer into its binary representation then performs its
operation.
Bitwise operators subsist of two digits, either 0 or 1. The truth tables for &, |, and ^ is as
follows –
P q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Output = 8
<< Left Shift Binary Left Shift Operator. A << 2 = 200 i.e.
The value of the left operands is 11001000
moved left by the number of bits
specified by the right operand.
Let us suppose the bitwise AND operation of two integers 12 and 25.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bit Operation of 12 and 25
00001100
&
00011001
___________
00001000 = 8 (In decimal)
Example program
#include <stdio.h>
intmain()
{
inta = 12, b = 25;
printf("Output = %d", a&b);
return0;
}
Output = 8
Right shift operator : Right shift operator shifts all bits towards right by certain number of
specified bits. It is denoted by >>.
Left shift operator: Left shift operator shifts all bits towards left by certain number of specified
bits. It is denoted by <<.
Example program
#include <stdio.h>
int main()
{
intnum=212, i;
for(i=0; i<=2; ++i)
printf("Right shift by %d: %d\n", i, num>>i); printf("\n");
for(i=0; i<=2; ++i)
printf("Left shift by %d: %d\n", i, num<<i);
return0;
}
OUTPUT
Right Shift by 0: 212
Right Shift by 1: 106
Right Shift by 2: 53
Left Shift by 0: 212
Left Shift by 1: 424
Left Shift by 2: 848
Assignment Operator
The above diagram helps us to understand that the RHS value is assigned to
the LHS variable.
So the operand on the LHS of the assignment operator must be a variable and operand
on RHS must be a constant , variable or expression.
For example, x = 4; then that means value 4 is assigned to variable x or we can say that
variable x holds value 4.
Operator Name of Operator What it does How it is used
Example program
#include <stdio.h>
int main()
int a = 7, b;
b = a; // b is 7
b += a; // b is 14
printf("b = %d\n", b);
b -= a; // b is 7
b *= a; // b is 49
b /= a; // b is 7
b %= a; // b = 0
return 0; }
Output
b=7
b = 14
b=7
b = 49
b=7
b=0
Ternary Operator
Sizeof()
Conditional operator (?:)
This is an operator that takes three arguments. The first argument is a comparison
argument, the second is the result of a true comparison, and the third is the result of a false
comparison
Syntax
The testCondition is a boolean expression that results in either true or false. If the
condition is
Example Program
#include <stdio.h>
int main() {
scanf("%d", &age);
return 0;
Output
Sizeof is a compile-time unary operator which can be used to compute the size of its
operand.
The result of sizeof is of the unsigned integral type which is usually denoted by size_t.
sizeof can be applied to any data type, including primitive types such as integer and
floating-point types, pointer types, or compound datatypes such as Structure, union, etc.
Syntax:
sizeof(Expression);
Example program
#include <stdio.h>
int main()
int size_of_int=sizeof(int);
int size_of_float=sizeof(float);
int size_of_double=sizeof(double);
return 0;
}
Output
When sizeof() is used with the expression, it returns the size of the expression.
// C Program To demonstrate
// operand as expression
#include <stdio.h>
int main()
int a = 0;
double d = 10.21;
return 0;
Expressions
An expression is a formula in which operands are linked to each other by the use of
Example : c= (a+b)*d;
There are four types of expressions exist in C:
Arithmetic expressions
Relational expressions
Logical expressions
Conditional expressions
Example:
10 + 20 * 30
Associativity of operators: is used when two operators of same precedence appear in an
expression. Associativity can be either Left to Right or Right to Left. For example: ‘*’ and ‘/’
have same precedence and their associativity is Left to Right, so the expression “100 / 10 *
10” is treated as “(100 / 10) * 10”.
Example Program
#include <stdio.h>
main()
int a = 20;
int b = 10;
int c = 15;
int d = 5; int e;
e = (a + b) * c / d; // ( 30 * 15 ) / 5
printf("Value of (a + b) * c / d is : %d\n", e );
e = ((a + b) * c) / d; // (30 * 15 ) / 5
printf("Value of (a + b) * (c / d) is : %d\n", e );
e = a + (b * c) / d; // 20 + (150/5)
printf("Value of a + (b * c) / d is : %d\n" , e );
return 0; }
INPUT/OUPUT STATEMENT
Input and Output statement are used to read and write the data
These are embedded in stdio.h (standard Input/Output header file).
Input means to provide the program with some data to be used in the program
and Output means to display data on screen or write the data to a printer or a file.
There are mainly two of Input/Output functions are used for this purpose.
Unformatted I/O functions are used only for character data type or character array/string
and cannot be used for any other datatype.
These functions are used to read single input from the user at the console and it allows to
display the value at the console.
There are mainly six unformatted I/O functions discussed as follows:
getchar()
putchar()
gets()
puts()
getch()
getche()
getch()
This function reads a single character from the keyboard by the user but doesn’t display
that character on the console screen and immediately returned without pressing enter key. This
function is declared in conio.h(header file).
Syntax:
getch();
or
#include <conio.h>
#include <stdio.h>
int main()
getch();
return 0;
Output:
getche():
This function reads a single character from the keyboard by the user and displays it on the
console screen and immediately returns without pressing the enter key. This function is declared
in conio.h(header file).
Syntax:
getche();
or
variable_name = getche();
Example program
#include <conio.h>
#include <stdio.h>
int main()
getche();
return 0;
Output:
getchar()
This function is used to read only a first single character from the keyboard whether
multiple characters is typed by the user and this function reads one character at one time until
and unless the enter key is pressed. This function is declared in stdio.h(header file)
Syntax:
Variable-name = getchar();
Example program
#include <conio.h>
#include <stdio.h>
int main()
char ch;
ch = getchar();
printf("%c", ch);
return 0;
Output:
a
putchar():
This function is used to display a single character at a time by passing that character
directly to it or by passing a variable that has already stored a character. This function is
declared in stdio.h(header file)
Syntax:
putchar(variable_name);
Example program
#include <conio.h>
#include <stdio.h>
int main()
char ch;
ch = getchar();
putchar(ch);
return 0;
Output:
gets():
This function reads a group of characters or strings from the keyboard by the user and
these characters get stored in a character array. This function allows us to write space-separated
texts or strings. This function is declared in stdio.h(header file).
Syntax:
char str[length of string in number]; //Declare a char type variable of any length
gets(str);
Example program
#include <conio.h>
#include <stdio.h>
int main()
char name[50];
gets(name);
return 0;
Output:
puts()
This function is used to display a group of characters or strings which is already stored in
a character array. This function is declared in stdio.h(header file).
Syntax:
puts(identifier_name );
Example program
#include <stdio.h>
int main()
char name[50];
puts(name);
return 0;
Output:
putch():
This function is used to display a single character which is given by the user and that
character prints at the current cursor location. This function is declared in conio.h(header file)
Syntax:
putch(variable_name);
Example program
#include <conio.h>
#include <stdio.h>
int main()
char ch;
ch = getch();
putch(ch);
return 0;
}
Output:
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.
printf()
scanf()
printf()
This function is 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
printf("control strings",&v1,&v2,&v3,................&vn);
or
Example program
#include <stdio.h>
int main()
int a;
a = 20;
printf("%d", a);
return 0;
}
Output
20
scanf():
This function is used 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). In scanf() function we use &(address-of operator) which is
used to store the variable value on the memory location of that variable.
Syntax:
Example program
#include <stdio.h>
int main()
int num1;
scanf("%d", &num1);
return 0;
Output:
return 0;
}
Output
sum = 2
Constants
Constants refer to fixed values that do not change during the execution of a program. They are
also called as literals.
Syntax for declaring Constant
constdata_typevariable_name= value;
(or)
constdata_type*variable_name= value;
Example :
const int batch=2019;
const float pi=3.14;
We can also use pre-processor command “define”.
Example :
#define pi 3.14
#define batch 2019
Types of Constants :
1. Integer constants: These are of the integer data type. For example,const int value = 400;
2. Floating constants or real constant :These are of the float data type. For example,const
float pi = 3.14;
3. Characte constants: These are of the character data type. For example,const char gender
= ‘f’;
4. String constants: These are also of the character data type, but differ in the declaration.
For example,const char dept[] = ‘‘ECE’’;
5. Octal constants: The number system which consists only 8 digits, from 0 to7 is called
the octal number system. The constant octal values can be declared as,const int oct =
040;(Itis the octal equivalent of the digit “32” in the decimal number system.)
6. Hexadecimal constants: The number system which consists of 16 digits, from 0 to 9 and
alphabets ‘a’ to ‘f’ is called hexadecimal number system. The constant hexadecimal
values can be declared as,const int hex = 0x40;(It is the hexadecimal equivalent of the
digit 64 in the decimal number system.).
Case-Study Problems
Step 5: Start a loop that continues as long as i is less than or equal to n. a. Add the value of i to sum. b.
Increment i by 1 in each iteration.
Step 6: After the loop, sum will contain the sum of natural numbers from 1 to n.
BEGIN
NUMBER i, sum=0
END
3. Factorial of a Number:
Step 1: Start
Step 2: Read a number n
Step 2: Initialize variables:
i = 1, fact = 1
Step 3: if i <= n go to step 4 otherwise go to step 7
Step 4: Calculate
fact = fact * i
Step 5: Increment the i by 1 (i=i+1) and go to step 3
Step 6: Print fact
Step 7: Stop
BEGIN
END FOR
DISPLAY factorial
END
Step1: START
Step 3: Set A = 0, B = 0
Step 4: DISPLAY A, B
Step 5: C = A + B
Step 6: DISPLAY C
Step 7: Set A = B, B = C
Step9: STOP
BEGIN
IF fib_num equals to 1
DISPLAY 1
IF fib_num equals to 2
DISPLAY 1, 1
1. Define Algorithm.
An algorithm is a set of instructions designed to perform a specific task. It is a step-by-
Step procedure for solving a task or a problem. The different algorithm differs in their requirements of
time and space. The programmer selects the best-suited algorithm for the given task to be solved.
Arrows
Input/Output
Process
Decision
11. Write down the steps involved in writing a program to solve a problem.
To design a program, a programmer must determine three basic steps:
a. The instruction to be performed.
b. The sequence in which those instructions are to be performed.
c. The data required to perform those instructions.
25. What are Operators? What are various types of C? operators? (Jan 2014)
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C language is rich in built-in operators and provides following type of operators
a) Arithmetic Operators
b) Bitwise Operators
c) Relational Operators
d) Assignment Operators
e) Logical Operators
f) Misc Operators
28. What do you meant by conditional or ternary operator? Give an example for Ternary
operator.
Conditional or ternary operator‟s returns one value if condition is true and returns another value is
condition is false. Using ?: reduce the number of line codes and improve the performance of
application.
Syntax: (Condition? true_value: false_value);
Ex: a<b ? printf("a is less") : printf("a is greater");
29. What is the use of sizeof() Operators in C?
sizeof() is used with the data types such as int, float, char... it simply return amount of 5 memory is
allocated to that data types.
sizeof(char); //1
sizeof(int); //4
sizeof(float);//4
sizeof(double); //8 sizeof() is used with the expression, it returns size of the expression.int
a = 0;
double d = 10.21;
printf("%d", sizeof(a+d)); //8
31. Write the limitations of using getchar() and scanf() functions for reading strings.
getchar(): It is written in standard I/O library. It reads a single character only from a standard input
device. This function is not use for reading strings.
Scanf: It is use for reading single string at a time. When there is a blank was typed, the scanf()
assumes that it is an end.
35. Why we don’t use the symbol ‘&’ symbol, while reading a String through scanf()?
The ‘&’ is not used in scanf() while reading string, because the character variable itself specifies as a
base address.
Example: name, &name[0] both the declarations are same.
Operator Meaning
& Bitwise AND
! Bitwise OR
^ Bitwise XOR
<< ShiftLeft
>> Shift Right
~ One‟scomple
ment
4x+100forx<40
Salary=300forx=40
Salary=x<40?4*x+100:x>40?4.5*x+150:300;
PART B