CSC 1
CSC 1
Introductory Concepts
C Fundamentals
Program Structure
Preparing and Running a Complete C Program
Operators and Expressions
Data Input and Output
Control Statements
Structure and Unions
Arrays
Pointers
Functions
Data Files
Low-Level Programming.
1
Introductory Concepts
COMPUTER? An electronic device which is capable of receiving information (data) in a particular
form and of performing a sequence of operations in accordance with a predetermined but variable set
of procedural instructions (program) to produce a result in the form of information or signals.
COMPUTING? the use or operation of computers
Use of a computer? Word Processing, Web Surfing, Instant Messaging / Email, Music, Movies,
Games, Air traffic control, Car diagnostics, Climate control
Parts of Computer Processor brains, Memory scratch paper, Disk long term memory, I/O
communication (senses), Software reconfigurability
Types of Computers:
Servers
Server usually refers to a computer that is dedicated to provide a service. For example, a
computer dedicated to a database may be called a "database server". "File servers" manage a
large collection of computer files. "Web servers" process web pages and web applications.
Many smaller servers are actually personal computers that have been dedicated to provide
services for other computers.
Workstations
Workstations are computers that are intended to serve one user and may contain special
hardware enhancements not found on a personal computer. By the mid 1990s personal
computers reached the processing capabilities of Mini computers and Workstations. Also,
with the release of multi-taskingsystems such as OS/2, Windows NT and Linux, the operating
systems of personal computers could do the job of this class of machines.
Mainframe computers
The term mainframe computer was created to distinguish the traditional, large, institutional
computer intended to service multiple users from the smaller, single user machines. They are
measured in MIPS (million instructions per second) and respond to up to 100s of millions of
users at a time.
Supercomputers
A Supercomputer is focused on performing tasks involving intense numerical calculations
such as weather forecasting, fluid dynamics, nuclear simulations, theoretical astrophysics,
and complex scientific computations. Supercomputer processing speeds are measured in
floating point operations per second, or FLOPS.
2
3
4
1. Input unit – Input unit is a unit that accepts any input device. The input device is used to input data
into the computer system.
Function of input unit: It converts inputted data into binary codes. It sends data to main memory.
2. Central Processing Unit (CPU) – CPU is called the brain of a computer. An electronic circuitry that
carries out the instruction given by a computer program. CPU can be sub classified into three parts.
a. Control unit (CU) b. Arithmetic & Logic unit (ALU) c. Memory Unit (MU)
a. Control unit (CU) - the control unit manages the various components of the computer. It reads
instructions from memory and interpretation and changes in a series of signals to activate other parts
of the computer. It controls and co-ordinate is input output memory and all other units.
b. Arithmetic & Logic unit (ALU) – The arithmetic logic unit (ALU), which performs simple
arithmetic operation such as +,-, *, / and logical operation such as >, <, =<, <= etc.
c. Memory Unit (MU) - Memory is used to store data and instructions before and after processing.
Memory is also called Primary memory or internal memory. It is used to store data temporary or
permanently.
Function of CPU-
It controls all the parts and software and data flow of computer.
It performs all operations.
It accepts data from input device.
It sends information to output device.
Executing programs stored in memory
It stores data either temporarily or permanent basis.
It performs arithmetical and logical operations.
3. Output Unit –Output unit is a unit that constituents a number of output device. An output device is
used to show the result of processing.
Function of Output unit: It accepts data or information sends from main memory of computer
It converts binary coded information into HLL or inputted languages.
5
Cabinet: SMPS 450, 500, 550, 600, 650, 750, 850, 900 WATT
Mother Board: Intel, Zebronics, Asus, Gigabyte, Mercury, Frontech, Msi, Ecs, Chipset,
Memoryslots, Form Factor (size, configuration)
Processors: AMD A10-5800K. AMD FX-9590. AMD Sempron 3850, Intel Core i3-6100.
Intel Core i7-6700K. Intel Core i5-4690K, CPU Cores 4, 8, GPU Cores, CPU Frequency,
3M, 6M, 8M, Cache (L2), 3.00GHz, 3.1GHz, 3.2GHz, 3.4GHz, 3.5GHz, 3.9GHz, 4.0GHz,
4.2GHz, 4.40GHz, first, second, third, fourth generation.
ROM / RAM: BIOS, DDR1, DDR2, DDR3, DDR4, 2GB, 4GB, 8GB.
HDD: HP, Kingston, ADATA, Sony, Toshiba, Seagate, WD, Barracuda – SSD, SATA,
SCSI, 5400RPM, 7200RPM, 10,000RPM, 500GB, 1TB, 2TB, 3TB.
BD, DVD, CD: HP, LG, Sony, Samsung. 8x, 18x, 24x, 48x, SATA, RW, Cache, Form Factor
5.25”.
USB – 2.0, 3.0, 3.1, Keyboard – QWERTY, Mouse – Optical mouse, left, right click, scroll
Monitors – CRT (Cathode Ray Tube), TFT, LCD (Liquid crystal display), LED (Light
Emitting Diode), OLED (Organic LED), Plasma. Screen Size (13, 15, 17, 19, 21, 23, 27 and
32 inches), Viewing Angle (The viewing angle indicates at what angle the monitor can be
viewed vertically and horizontally and still be seen.), Contrast Ratio (The contrast ratio
determines how rich colors will appear on-screen, the higher the ratio the better. Contrast
ratios range from 200:1 up to 1000:1), Resolution and Refresh Rates. The resolution is the
number of dots displayed on the entire screen. The higher the resolution the smaller
everything on the screen will be. This can be a benefit for running multiple applications at the
same time but can also be a burden for someone with poor eyesight. Common resolution
supports include 640 * 480, 800 * 600 and 1,024*768 and so forth. The refresh rate of a
monitor is the frequency at which the screen is redrawn. The higher the number the more
often the screen is redrawn and the less flicker will occur. Common Refresh rate are 60 to
80Hertz.
Speakers – Mono, Stereo, Home Theatre, 2.1, 5.1, 7.1, SubWoofer, Wireless, Bluetooth.
System Software: Dedicated to managing the computer itself, such as the operating system,
file management utilities, and disk operating system. The computer programs used to start
and run computer systems.
6
level languages use specific symbols for instructions. Detailed information is required about
computer hardware. Example: Assembly Language.
Compiler: is a computer program (or a set of programs) that transforms source code
(Program) written in a programming language (the source language) into another computer
language / object code (binary language).
Interpreter: is a computer program that directly executes, i.e. performs, instructions written in
a programming or scripting language, without previously compiling them into a machine
language program.
Booting: is the initialization of a computerized system. The booting process can be "hard",
after electrical power to the CPU is switched from off to on (in order to diagnose particular
hardware errors), or "soft", when those power-on self-tests (POST) can be avoided. A boot
loader is a computer program that loads an operating system or some other system software
for the computer after completion of the power-on self-tests; it is the loader for the operating
system itself. Within the hard reboot process, it runs after completion of the self-tests, then
loads and runs the software. A boot loader is loaded into main memory from persistent
memory, such as a hard disk drive.
7
Number system
Computers can understand only numbers. Thus, all data such as the words, images, music,
etc. are translated by the computer to numbers. A computer can understand the positional
number system where there are only a few symbols called digits and these symbols represent
different values depending on the position they occupy in the number.
The value of each digit in a number can be determined using −
The digit
The position of the digit in the number
The base of the number system (where the base is defined as the total number of digits
available in the number system)
8
Last position in an octal number represents a x power of the base (8). Example
8x where x represents the last position - 1
Example Octal Number: 125708
Calculating Decimal Equivalent −
Step Octal Number Decimal Number
Step 2 19FDE16 ((1 x 164) + (9 x 163) + (15 x 162) + (13 x 161) + (14 x 160))10
Step 1 − Divide the decimal number to be converted by the value of the new base.
Step 2 − Get the remainder from Step 1 as the rightmost digit (least significant digit) of the
new base number.
Step 3 − Divide the quotient of the previous divide by the new base.
Step 4 − Record the remainder from Step 3 as the next digit (to the left) of the new base
number.
Repeat Steps 3 and 4, getting remainders from right to left, until the quotient becomes zero in
Step 3.
The last remainder thus obtained will be the Most Significant Digit (MSD) of the new base
number.
Example Decimal Number: 2910
Calculating Binary Equivalent −
9
Step Operation Result Remainder
Step 1 29 / 2 14 1
Step 2 14 / 2 7 0
Step 3 7/2 3 1
Step 4 3/2 1 1
Step 5 1/2 0 1
As mentioned in Steps 2 and 4, the remainders have to be arranged in the reverse order so
that the first remainder becomes the Least Significant Digit (LSD) and the last remainder
becomes the Most Significant Digit (MSD).
Decimal Number: 2910 = Binary Number: 111012.
Step 1 21 / 2 10 1
Step 2 10 / 2 5 0
Step 3 5/2 2 1
Step 4 2/2 1 0
Step 5 1/2 0 1
10
Octal Number: 258 = Binary Number: 101012
Step 2 101012 28 58
11
Shortcut Method - Hexadecimal to Binary
Step 1 − Convert each hexadecimal digit to a 4-digit binary number (the hexadecimal digits
may be treated as decimal for this conversion).
Step 2 − Combine all the resulting binary groups (of 4 digits each) into a single binary
number.
Example Hexadecimal Number: 1516
Calculating Binary Equivalent −
Step Hexadecimal Number Binary Number
• Divide each digit from right side of radix point till the end by 21, 22, 23, … respectively.
• Add all the result coming from step 1.
• Equivalent fractional decimal number would be the result obtained in step 2.
=> 0.1012 = (1*1/2) + (0*1/22) + (1*1/23)
=> 0.1012 = 1*0.5 + 0*0.25 + 1*0.125
=> 0.1012 = 0.62510
12
Convert hexa fraction to decimal
• 0.1616
• multiply 1 by 1/16 and take the integer part
1 x 1/16 = 0.625
• multiply 6 by 16 and take the integer part
6 x 1/162 = 0.023
0.1616 = 0.64810
Algorithm
Flowchart
13
C Language Introduction
In 1988, the American National Standards Institute (ANSI) had formalized the C language. C
was invented to write UNIX operating system. C is a successor of 'Basic Combined
Programming Language' (BCPL) called B language. Linux OS, PHP, and MySQL are written
in C. C has been written in assembly language.
Low-Level Programming
Object code is small and efficient. Optimize the use of three resources: Execution time,
Memory, Development/maintenance time.
14
The white spaces used in C programs are: blank space, horizontal tab, carriage return, new
line and form feed.
Identifiers are names given to various program elements such as variables, functions, and
arrays. Identifiers consist of letters and digits, in any order, except that the first character
must be a letter. Both uppercase and lowercase letters are permitted and the underscore may
also be used, as it is also regarded as a letter. Uppercase and lowercase letters are not
equivalent, thus not interchangeable. This is why it is said that C is case sensitive. An
identifier can be arbitrarily long.
The same identifier may denote different entities in the same program, for example, a
variable and an array may be denoted by the same identifier, example below.
int sum, average, A[10]; // sum, average and the array name A are all identifiers.
The predefined identifier __func__ makes a function name available for use within the
function. Immediately following the opening brace of each function definition, _ _func_ _ is
implicitly declared by the compiler in the following way:
#include <stdio.h>
void myfunc(void) {
printf("%s",__func__);
return;
}
void main() {
myfunc();
}
The output would be myfunc
Keywords
Keywords are reserved words that have standard predefined meanings. These keywords can
only be used for their intended purpose; they cannot be used as programmer defined
identifiers. Examples of some keywords are: int, main, void, if.
15
Data Types
Data values passed in a program may be of different types. Each of these data types are
represented differently within the computer’s memory and have different memory
requirements. These data types can be augmented by the use of data type qualifiers /
modifiers.
int:
It is used to store an integer quantity. An ordinary int can store a range of values from
INT_MIN to INT_MAX as defined by in header file <limits.h>. The type modifiers for the
int data type are: signed, unsigned, short, long, and long long.
• A short int occupies 2 bytes of space and a long int occupies 4 bytes.
• A short unsigned int occupies 2 bytes of space but it can store only positive values in
the range of 0 to 65535.
• An unsigned int has the same memory requirements as a short unsigned int. However,
in case of an ordinary int, the leftmost bit is reserved for the sign.
• A long unsigned int occupies 4 bytes of memory and stores positive integers in the
range of 0 to 4294967295.
• By default the int data type is signed.
• A long long int occupies 64 bits of memory. It may be signed or unsigned. The signed
long, long int stores values from −9,223,372,036,854,775,808 to
9,223,372,036,854,775,807 and the unsigned long long ranges from 0 to
18,446,744,073,709,551,615.
char:
It stores a single character of data belonging to the C character set. It occupies 1 byte of
memory, and stores any value from the C character set. The type modifiers for char
are signed and unsigned.
Both signed and unsigned char occupy 1 byte of memory but the range of values differs. An
unsigned char can store values from 0 to 255 and a signed char can store values from -128 to
+127. Each char type has an equivalent integer interpretation, so that a char is really a special
kind of short integer. By default, char is unsigned.
float:
It is used to store real numbers with single precision i.e. a precision of 6 digits after decimal
point. It occupies 4 bytes of memory. The type modifier for float is long. It has the same
memory requirements as double.
double:
It is used to store real numbers with double precision. It occupies 8 bytes of memory. The
type modifier for double is long. A long double occupies 10 bytes of memory.
16
void:
It is used to specify an empty set containing no values. Hence, it occupies 0 bytes of memory.
_Bool:
A boolean data type, which is an unsigned integer type, that can store only two values, 0 and
1. Include the file <stdbool.h> when using _Bool.
_Complex:
It is used to store complex numbers. There are three complex types: float _Complex, double
_Complex, and long double _ComplexIt is found in the <complex.h> file.
Constants:
Integer Constants:
Octal (base 8): An octal constant can consist of any combination of digits from 0 to 7. The
first digit must be a 0 to identify the constant as an octal number, for example: const int a=
074; const int b= 0;
Hexadecimal constant (base 16): A hexadecimal constant can consist of any combination of
digits from 0 to 9 and a to f (either uppercase or lowercase). It must begin with 0x or oX to
identify the constant as a hexadecimal number, for example: const int c= 0x7FF;
Integer constants can also be prefixed by the type modifiers unsigned and long. Unsigned
constants must end with uor U, long integer constants must end with lor L and unsigned long
integer constants must end with ul or UL. Long long integer constants end with LL or ll.
unsigned long long end with UL or ul
Its a base 10 or a base 16 number that contains a decimal point or an exponent or both. In
case of a decimal floating point constant the exponent the base 10 is replaced by e or E. Thus,
1.4 *10^-3 would be written as 1.4E-3 or 1.4e-3.
17
In case of a hexadecimal character constant, the exponent is in binary and is replaced by p or
P. For example:
Character Constants:
A character literal without the L prefix is an ordinary character constant or a narrow character
constant. A character literal with the L prefix is a wide character constant. The type of a
narrow character constant and a multicharacter constant is int. The type of a wide character
constant with prefix L is wchar_t defined in the header file <stddef.h> .A wide character
constant with prefix u or U is of type char16_t or char32_t. These are unsigned character
types defined in <uchar.h>.
An ordinary character literal that contains more than one character or escape sequence is a
multicharacter constant, for example: const char p= 'A';
Escape Sequences are also character constants that are used to express certain non printing
characters such as the tab or the carriage return.An escape sequence always begins with a
backward slash and is followed by one or more special characters. for eg. b will represent the
bell, n will represent the line feed.
String Literals:
The compiler recognizes and supports the additional characters (the extended character set)
which you can meaningfully use in string literals and character constants. The support for
extended characters includes the multibyte character sets. A multibyte character is a character
whose bit representation fits into one or more bytes.
Symbolic Constants:
A symbolic constant is a name that substitutes for a numeric constant, a character constant or
a string constant throughout the program. When the program is compiled each occurrence of
a symbolic constant is replaced by its actual value.
18
A symbolic constant is defined at the beginning of a program using the # define feature. The
# define feature is called a preprocessor directive, more about the C preprocessor in a later
article.
A symbolic constant definition never ends with a semi colon as it is not a C statement rather
it is a directive, for example:
#define True 1
Program Structure
C program basically consists of the following parts −
• Preprocessor Commands
• Functions
• Variables
• Statements & Expressions
• Comments
Let us look at a simple code that would print the words "Hello World" −
#include <stdio.h>
int main() {
/* my first program in C */
printf("Hello, World! \n");
return 0;
}
The first line of the program #include <stdio.h> is a preprocessor command, which tells a C
compiler to include stdio.h file before going to actual compilation.
The next line int main() is the main function where the program execution begins.
The next line /*...*/ will be ignored by the compiler and it has been put to add additional
comments in the program. So such lines are called comments in the program.
The next line printf(...) is another function available in C which causes the message "Hello,
World!" to be displayed on the screen.
The next line return 0; terminates the main() function and returns the value 0.
Preparing and Running a Complete C Program
Operators and Expressions
19
An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions. C language is rich in built-in operators and provides the following types of
operators −
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators
We will, in this chapter, look into the way each operator works.
Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language. Assume
variable A holds 10 and variable B holds 20 then –
Relational Operators
The following table shows all the relational operators supported by C. Assume
variable A holds 10 and variable B holds 20 then −
Operator Description Example
> Checks if the value of left operand is greater than the value of (A > B) is
right operand. If yes, then the condition becomes true. not true.
< Checks if the value of left operand is less than the value of (A < B) is
right operand. If yes, then the condition becomes true. true.
20
>= Checks if the value of left operand is greater than or equal to (A >= B) is
the value of right operand. If yes, then the condition becomes not true.
true.
<= Checks if the value of left operand is less than or equal to the (A <= B) is
value of right operand. If yes, then the condition becomes true. true.
Logical Operators
Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then –
Operator Description Example
&& Called Logical AND operator. If both the operands are non- (A && B) is
zero, then the condition becomes true. false.
! Called Logical NOT Operator. It is used to reverse the logical !(A && B) is
state of its operand. If a condition is true, then Logical NOT true.
operator will make it false.
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. 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
Assume A = 60 and B = 13 in binary format, they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
Decimal Binary 2's complement
0 00000000 -(11111111+1) = -00000000 = -0(decimal)
1 00000001 -(11111110+1) = -11111111 = -256(decimal)
12 00001100 -(11110011+1) = -11110100 = -244(decimal)
220 11011100 -(00100011+1) = -00100100 = -36(decimal)
2’s complement of N = -(N+1)
Example, 2’s complement of 35 = -36, 2’s complement of -12 = 11
21
The following table lists the bitwise operators supported by C. Assume variable 'A' holds 60
and variable 'B' holds 13, then −
Operator Description Example
& Binary AND Operator copies a bit to the result if it exists in (A & B) = 12,
both operands. i.e., 0000 1100
^ Binary XOR Operator copies the bit if it is set in one operand (A ^ B) = 49,
but not both. i.e., 0011 0001
~ Binary Ones Complement Operator is unary and has the (~A ) = -61,
effect of 'flipping' bits. i.e,. 1100 0011
in 2's
complement
form.
<< Binary Left Shift Operator. The left operands value is moved A << 2 = 240
left by the number of bits specified by the right operand. i.e., 1111 0000
>> Binary Right Shift Operator. The left operands value is A >> 2 = 15
moved right by the number of bits specified by the right i.e., 0000 1111
operand.
#include <stdio.h>
main() {
unsigned int a = 60; /* 60 = 0011 1100 */
unsigned int b = 13; /* 13 = 0000 1101 */
int c = 0;
c = a & b; /* 12 = 0000 1100 */
printf("Line 1 - Value of c is %d\n", c );
c = a | b; /* 61 = 0011 1101 */
printf("Line 2 - Value of c is %d\n", c );
c = a ^ b; /* 49 = 0011 0001 */
printf("Line 3 - Value of c is %d\n", c );
c = ~a; /*-61 = 1100 0011 */
printf("Line 4 - Value of c is %d\n", c );
c = a << 2; /* 240 = 1111 0000 */
printf("Line 5 - Value of c is %d\n", c );
c = a >> 2; /* 15 = 0000 1111 */
printf("Line 6 - Value of c is %d\n", c );
}
Assignment Operators
The following table lists the assignment operators supported by the C language −
Operator Description Example
22
right side operands to left side operand value of A + B to C
& Returns the address of a variable. &a; returns the actual address of
the variable.
23
?: Conditional Expression. If Condition is true ? then value
X : otherwise value Y
Operators Precedence in C
Operator precedence determines the grouping of terms in an expression and decides how an
expression is evaluated. Certain operators have higher precedence than others; for example,
the multiplication operator has a higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.
24
When we say Output, it means to display some data on screen, printer, or in any file. C
programming provides a set of built-in functions to output the data on the computer screen as
well as to save it in text or binary files.
The Standard Files
C programming treats all the devices as files. So devices such as the display are addressed in
the same way as files and the following three files are automatically opened when a program
executes to provide access to the keyboard and screen.
Standard File File Pointer Device
When the above code is compiled and executed, it waits for you to input some text. When
you enter a text and press enter, then the program proceeds and reads only a single character
and displays it as follows −
$./a.out
Enter a value : this is test
You entered: t
25
int main( ) {
char str[100];
printf( "Enter a value :");
gets( str );
printf( "\nYou entered: ");
puts( str );
return 0;
}
When the above code is compiled and executed, it waits for you to input some text. When
you enter a text and press enter, then the program proceeds and reads the complete line till
end, and displays it as follows −
$./a.out
Enter a value : this is test
You entered: this is test
When the above code is compiled and executed, it waits for you to input some text. When
you enter a text and press enter, then program proceeds and reads the input and displays it as
follows −
$./a.out
Enter a value: seven 7
You entered: seven 7
Here, it should be noted that scanf() expects input in the same format as you provided %s and
%d, which means you have to provide valid inputs like "string integer". If you provide "string
string" or "integer integer", then it will be assumed as wrong input. Secondly, while reading a
26
string, scanf() stops reading as soon as it encounters a space, so "this is test" are three strings
for scanf().
int a;
scanf("%5d", &a);
take just first 5 digit as input. Any digits after 5th one would be ignored.
char str[100];
scanf("%[^\n]", str);
%[0–9]
Control Statements
Branching:
Branching is so called because the program chooses to follow one branch or another.
if statement
if (expression)
statement;
or
if (expression) {
Block of statements;
}
or
if (expression) {
Block of statements;
}
else {
Block of statements;
}
or
if (expression) {
Block of statements;
}
27
else if(expression) {
Block of statements;
}
else {
Block of statements;
}
? : Operator
The ? : operator is just like an if ... else statement except that because it is an operator you can
use it within expressions.
? : is a ternary operator in that it takes three values, this is the only ternary operator C has.
? : takes the following form:
if condition is true ? then X return value : otherwise Y value;
switch statement:
The switch statement is much like a nested if .. else statement. Its mostly a matter of
preference which you use, switch statement can be slightly more efficient and easier to read.
switch( expression )
{
case constant-expression1: statements1;
[case constant-expression2: statements2;]
[case constant-expression3: statements3;]
[default : statements4;]
}
Using break keyword:
If a condition is met in switch case then execution continues on into the next case clause also
if it is not explicitly specified that the execution should exit the switch statement. This is
achieved by using break keyword.
What is default condition:
If none of the listed conditions is met then default condition executed.
Looping
Loops provide a way to repeat commands and control how many times they are repeated. C
provides a number of looping way.
while loop
The most basic loop in C is the while loop. A while statement is like a repeating if statement.
Like an If statement, if the test condition is true: the statements get executed. The difference
is that after the statements have been executed, the test condition is checked again. If it is still
true the statements get executed again. This cycle repeats until the test condition evaluates to
false.
Basic syntax of while loop is as follows:
while ( expression )
{
Single statement
or
Block of statements;
}
for loop
for loop is similar to while, it's just written differently. for statements are often used to
proccess lists such a range of numbers:
Basic syntax of for loop is as follows:
for( expression1; expression2; expression3)
{
28
Single statement
or
Block of statements;
}
In the above syntax:
• expression1 - Initialisese variables.
• expression2 - Condtional expression, as long as this condition is true, loop will keep
executing.
• expression3 - expression3 is the modifier which may be simple increment of a
variable.
do...while loop
do ... while is just like a while loop except that the test condition is checked at the end of the
loop rather than the start. This has the effect that the content of the loop are always executed
at least once.
Basic syntax of do...while loop is as follows:
do
{
Single statement
or
Block of statements;
}while(expression);
break and continue statements
C provides two commands to control how we loop:
• break -- exit form loop or switch.
• continue -- skip 1 iteration of loop.
You already have seen example of using break statement. Here is an example showing usage
of continue statement.
#include
main()
{
int i;
int j = 10;
for( i = 0; i <= j; i ++ ) {
if( i == 5 ) {
continue;
}
printf("Hello %d\n", i );
}
}
Hello 0
Hello 1
Hello 2
Hello 3
Hello 4
Hello 6
Hello 7
Hello 8
Hello 9
Hello 10
29
Function
• input
• process
• output
return-type function_name (parameter-list){
statements ;
return value;
}
Example
function-name (parameters);
add_values (5,4);
int a=3,b=6;
add_values (a, b);
printf(“%d”, add_values (5,4));
Function Parameters
A literal value or a value stored in variable or an address in memory or a more complex
expression built by combining these
int foo (int a) { a = 2 * a; return a; }
x = foo (x);
void foo (int *x) { *x = *x + 42; } int a = 15; foo (&a);
• Every program requires at least one function, called ‘main’. This is where the program
begins executing.
• You do not need to write a declaration or prototype for main, but you do need to define it.
• The return type for main is always int. You do not have to specify the return type
for main, but you can.
• However, you cannot specify that it has a return type other than int.
• the return value from main indicates the program’s exit status.
• A value of zero or EXIT_SUCCESS indicates success and EXIT_FAILURE indicates an
error.
• Reaching the } at the end of main without a return, or executing a return statement with
no value (that is, return;) are both equivalent.
void main (void) {
puts ("Hi there!");
}
Example
30
int main (int argc, char *argv[]) {
int counter;
for (counter = 0; counter < argc; counter++)
printf ("%s\n", argv[counter]);
return 0;
}
Recursive Functions a function that calls itself
int factorial (int x) {
if (x < 1) return 1;
else return (x * factorial (x - 1));
}
Infinitely Recursive
int watermelon (int x) {
return (watermelon (x));
}
Static Functions
Callable only within the source file where it is defined. Useful for building a reusable library
of functions and need to include some subroutines that should not be callable by the end user.
static int foo (int x) {
return x + 42;
}
Nested Functions can define functions within other functions
int factorial (int x) {
int factorial_helper (int a, int b)
{
if (a < 1) { return b; }
else { return factorial_helper ((a - 1), (a * b)); }
}
return factorial_helper (x, 1);
}
// main.c
#include "add.c"
int main(void) {
int result = add(5,6);
printf("%d\n", result);
}
// add.c
int add(int a, int b) {
return a + b;
}
1 Call by value
This method passes the actual value as an argument to the function. In this case, changes
made inside the function have no effect on the calling function.
2 Call by reference
This method passes the address to the function. Inside the function, the address is used to
access the actual argument used in the call. This effects the variables in the calling function.
31
void myFunction(int *param) {
Example
#include <stdio.h>
void displayNumbers(int num[2][2]);
void main(){
int num[2][2], i, j;
printf("Enter 4 numbers:\n");
for (i = 0; i < 2; ++i)
for (j = 0; j < 2; ++j) scanf("%d", &num[i][j]);
displayNumbers(num);
}
void displayNumbers(int num[2][2])
{
int i, j;
for (i = 0; i < 2; ++i){
for (j = 0; j < 2; ++j) printf("%d\t", num[i][j]);
printf(“\n”);}
}
Storage Class
32
A storage class defines the scope and life-time of variables and/or functions. Four different
storage classes are auto, register, static, extern.
The static storage class instructs the compiler to keep a local variable in existence during the
life-time of the program instead of creating and destroying it each time it comes into and goes
out of scope. Therefore, making local variables static allows them to maintain their values
between function calls. The static modifier may also be applied to global variables. When this
is done, it causes that variable's scope to be restricted to the file in which it is declared.
#include <stdio.h>
void func( void ) {
static int i = 5; /* local static variable */
i++;
printf("i is %d and count is %d\n", i, count);
}
static int count = 5; /* global variable */
void main(){
while(count--)func();
}
The extern storage class is used to give a reference of a global variable or function that is
visible to ALL the program files. When you use 'extern', the variable cannot be initialized
however, it points the variable name at a storage location that has been previously defined.
When you have multiple files and you define a global variable or function, which will also be
used in other files, then extern will be used in another file to provide the reference of defined
variable or function. Just for understanding, extern is used to declare a global variable or
function in another file. The extern modifier is most commonly used when there are two or
more files sharing the same global variables or functions as explained below.
#include <stdio.h>
int count ;
extern void write_extern();
main() {
count = 5;
write_extern();
}
#include <stdio.h>
33
extern int count;
void write_extern(void) {
printf("count is %d\n", count);
}
Unions
• custom data type used for storing several variables in the same memory space
• access any of those variables at any time
• store / read from one of them at a time
Defining Unions
• define a union using the union keyword followed by the declarations of the union’s
members, enclosed in braces
• declare each member of a union as declaring a variable
union numbers {
int i;
float f;
};
union numbers {
int i;
float f;
} first_number, second_number;
union numbers {
int i;
float f;
};
union numbers first_number, second_number;
union numbers {
int i;
float f; };
union numbers first_number = { 5 };
union numbers first_number = { f: 3.14159 };
union numbers first_number = { .f = 3.14159 };
union numbers {
int i;
float f;
};
34
first_number.i = 5; first_number.f = 3.9;
Defining Structures
define a structure using the struct keyword followed by the declarations of the structure’s
members, enclosed in braces.
struct point {
int x, y;
};
struct point {
int x, y;
};
struct point first_point = { 5, 10 };
struct point {
int x, y;
} first_point = { 5, 10 };
35
struct pointy {
int x, y;
char *p;
};
struct pointy first_pointy = { 5 };
struct point {
int x, y;
};
struct rectangle {
struct point top_left, bottom_right;
};
my_rectangle.top_left.x = 0;
my_rectangle.top_left.y = 5;
my_rectangle.bottom_right.x = 10;
my_rectangle.bottom_right.y = 0;
Unions Structures
Common storage space for all members Individual storage space for each members
Occupies lower memory space Occupies higher memory space
Can access only one member of union at a Can access all members of structure at a
time time
Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to
integral constants, the names make a program easy to read and maintain.
36
// Or
enum week{Mon, Tue, Wed}day;
enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};
int main()
{
enum week day;
day = Wed;
printf("%d",day);
}
Output:
2
enum year{Jan, Feb, Mar, Apr, May, Jun, Jul,Aug, Sep, Oct, Nov,
Dec};
int main()
{
int i;
for (i=Jan; i<=Dec; i++)
printf("%d ", i);
}
Output:
0 1 2 3 4 5 6 7 8 9 10 11
If we do not explicitly assign values to enum names, the compiler by default assigns values
starting from 0. We can assign values to some name in any order. All unassigned names get
value as value of previous name plus one.
#include <stdio.h>
enum day {sunday = 1, monday, tuesday = 5,
wednesday, thursday = 10, friday, saturday};
int main()
{
printf("%d %d %d %d %d %d %d", sunday, monday, tuesday,
wednesday, thursday, friday, saturday);
}
Output: 1 2 5 6 10 11 12
Advantages of using enum over macro: Enum variables are automatically assigned values.
Arrays
An array is an identifier that refers to a collection of data items of that have the same name.
They must also have the same data type (i.e. all characters, all integers etc.). Each data item is
represented by its array element. The individual array elements are distinguished from one
another by their subscripts.
Suppose arr is a 5 element integer array which stores the numbers 5, 4, 2, 7, 3 in that order.
The first element is referred to as arr[0]which stores the data value 5, the second element
is arr [1] which stores the value 4 and so on. The last element is arr [4] which stores the
37
value 3. The subscript associated with each element is shown in square braces. For an n-
element array the subscripts will range from 0 to n-1.
In case of a character array of size n, the array will be able to store only n-1 elements as a null
character is automatically stored at the end of the string to terminate it. Therefore, a character
array letter that stores 5 elements must be declared of size 6. The fifth element would be
stored at letter [4] and letter [5] will store the null character.
Can store one or more elements consecutively in memory. Array elements are indexed
beginning at position zero, not one.
Declare an array by specifying the data type for its elements, its name, and the number of
elements it can store
int my_array[10];
Zero-length arrays are useful as the last element of a structure which is really a header for a
variable-length object
struct line{
int length;
char contents[0];
};
{
struct line *this_line = (struct line *)
malloc (sizeof (struct line) + this_length);
this_line -> length = this_length;
}
For example, this code initializes the first three elements as specified, and then initializes the
last two elements to a default value of zero:
38
void main(void)
{
int i, my_array[5] = { 0, 1, 2 };
for(i=0;i<5;i++)
printf("%d\n",my_array[i]);
}
Array elements can be initialized by specifying array indices by including the array index in
brackets, and optionally the assignment operator, before the value.
or,
int my_array[5] = { 0, 0, 5, 0, 9 };
can initialize a range of elements to the same value, by specifying the first and last indices, in
the form [first] ... [last] .
If every element of an array is initialized, then its size is determined by the number of
elements initialized.
int my_array[] = { 0, 1, 2, 3, 4 };
If specified which elements to be initialized, then the size of the array is equal to the highest
element number initialized, plus one.
In that example, only four elements are initialized, but the last one initialized is element
number 9, so there are 10 elements.
Specifying the array name, followed by the element index, enclosed in brackets.
my_array[0] = 5;
That assigns the value 5 to the first element in the array, at position zero.
39
Multidimensional Arrays
Arrays of Arrays - A two-dimensional array that holds five elements in each dimension
two_dimensions[1][3] = 12;
# include <stdio.h>
void main(void){
int i,j, two_dimensions[2][5]= { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10} };
for(i=0;i<2;i++)
for (j=0;j<5;j++)
printf("%d\n",two_dimensions[i][j]);
}
Arrays as Strings
char blue[26];
The string terminator null character \0 is included at the end of the string
char lemon[26] = "custard";
lemon = "steak sauce"; /* Fails! */
name[0] = 'r';
It is possible to initialize an array using a string that has more characters than the specified
size.
This is not a good thing. The larger string will not override the previously specified size of
the array, and you will get a compile-time warning.
Since the original array size remains, any part of the string that exceeds that original size is
being written to a memory location that was not allocated for it.
40
Arrays of Unions
union numbers {
int i;
float f;
};
union numbers number_array [3];
After initialization, the union members are accessed in the array using the member access
operator.
number_array[0].i = 2;
Arrays of Structures
struct point {
int x, y;
};
struct point point_array [3];
The additional braces are used for partially initializing some of the structures in the array, and
fully initialize others:
The value 4 is assigned to the x member of the second array element, not to the y member of
the first element, as would be the case without the grouping braces.
Access the structure members in the array using the member access operator.
41
point_array[0].x = 2;
point_array[0].y = 3;
Typedef
the identifier BYTE can be used as an abbreviation for the type unsigned char
Preprocessors
The C Preprocessor is not a part of the compiler, but is a separate step in the compilation
process. A C Preprocessor is just a text substitution tool and it instructs the compiler to do
required pre-processing before the actual compilation.
All preprocessor commands begin with a hash symbol (#). It must be the first nonblank
character, and for readability, a preprocessor directive should begin in the first column.
Examples
#define MAX_ARRAY_LENGTH 20
#include <stdio.h>
#include "myheader.h"
#undef FILE_SIZE
#define FILE_SIZE 42
#ifndef MESSAGE
#define MESSAGE "You wish!"
#endif
#ifdef DEBUG
/* Your debugging statements here */
#endif
Directive Description
42
#else The alternative for #if.
Preprocessor Operators
#define message_for(a, b) \
printf(#a " and " #b ": Festival Greetings!\n")
#include <stdio.h>
#define message_for(a, b) \
printf(#a " and " #b ": Festival Greetings!\n")
int main(void) {
message_for(Carole, Debra);
return 0;
}
Carole and Debra: Festival Greetings!
#include <stdio.h>
int main(void) {
int token34 = 40;
tokenpaster(34);
return 0;
}
token34 = 40
#include <stdio.h>
int main(void) {
printf("Here is the message: %s\n", MESSAGE);
43
return 0;
}
Here is the message: You wish!
Parameterized Macros
Predefined Macros
Macro Description
__STDC__ Defined as 1 when the compiler complies with the ANSI standard.
#include <stdio.h>
main() {
Pointers
A pointer is a variable whose value is the address of another variable. A pointer can be any
variable type. The unary or monadic operator & gives the ``address of a variable''.
The indirection or dereference operator * gives the ``contents of an object pointed to by a
pointer''.
44
Declaring Pointers
data-type * name;
data-type *name;
data-type* name;
Initializing Pointers
int i;
# include <stdio.h>
45
void main(void){
int i=3, j=4, *ip, *jp;
ip = &i;
jp = &j;
printf("%u\t%u\t%u\t%u",i,j,ip,jp);
printf("%u\t%u\t%u\t%u",i,j,*ip,*jp);
}
int i, j;
int *ip = &i; /* ‘ip’ now holds the address of ‘i’. */
ip = &j; /* ‘ip’ now holds the address of ‘j’. */
*ip = &i; /* ‘j’ now holds the address of ‘i’. */
#include <stdio.h>
int main(){
char charArr[4];
int i;
return 0;
}
int arr[4];
&arr[0] is equivalent to arr
arr[0] is equivalent to *arr
&arr[1] is equivalent to (arr + 1) AND, arr[1] is equivalent to *(arr + 1).
&arr[2] is equivalent to (arr + 2) AND, arr[2] is equivalent to *(arr + 2).
&arr[3] is equivalent to (arr + 3) AND, arr[3] is equivalent to *(arr + 3).
&arr[i] is equivalent to (arr + i) AND, arr[i] is equivalent to *(arr + i).
46
A parameter is passed by reference, the caller and the callee use the same variable for the
parameter. If the callee modifies the parameter variable, the effect is visible to the
caller's variable.
A parameter is passed by value, the caller and callee have two independent variables with
the same value. If the callee modifies the parameter variable, the effect is not visible to
the caller.
47
Pointers to Unions
union numbers {
int i;
float f;
};
union numbers foo = {4};
union numbers *number_ptr = &foo;
Pointers to Structures
struct fish {
float length, weight;
};
struct fish salmon = {4.3, 5.8};
struct fish *fish_ptr = &salmon;
NULL Pointers
It is always a good practice to assign a NULL value to a pointer variable in case you do not
have an exact address to be assigned. This is done at the time of variable declaration. A
pointer that is assigned NULL is called a null pointer.
To check for a null pointer, you can use an 'if' statement as follows
48
if(ptr) /* succeeds if p is not null */
if(!ptr) /* succeeds if p is null */
There are four arithmetic operators that can be used in pointers: ++, --, +, -
ptr++;
ptr--;
ptr=ptr+1;
ptr=ptr-1;
malloc() allocates requested size of bytes and returns a pointer first byte of allocated space
calloc() allocates space for an array elements, initializes to zero and then returns a pointer
free(ptr);
#include <stdio.h>
void swap(int *n1, int *n2);
int main(){
int num1 = 5, num2 = 10;
49
#include <stdio.h>
#include <conio.h>
int* larger(int*, int*);
void main(){
int a=15;
int b=92;
int *p;
p=larger(&a, &b);
printf("%d is larger",*p);
}
int* larger(int *x, int *y){
if(*x > *y)
return x;
else
return y;
}
Multiple indirection
int a = 3;
int *b = &a;
int **c = &b;
int ***d = &c;
***d == **c == *b == a == 3;
Constant Pointers
Benefits(use) of pointers in c:
1. Pointers provide direct access to memory
2. Pointers provide a way to return more than one value to the functions
3. Reduces the storage space and complexity of the program
4. Reduces the execution time of the program
5. Provides an alternate way to access array elements
6. Pointers can be used to pass information back and forth between the calling function and
called function.
7. Pointers allow us to perform dynamic memory allocation and deallocation.
50
8. Pointers helps us to build complex data structures like linked list, stack, queues, trees,
graphs etc.
9. Pointers allow us to resize the dynamically allocated memory block.
10. Addresses of objects can be extracted using pointers
Drawbacks of pointers in c:
Storing in a file will preserve your data even if the program terminates.
Types of Files
1. Text files
Text files are the normal .txt files that can be easily created using Notepad or any text editors.
The contents of the file is plain text and visible. Edit or delete the contents easily. They take
minimum effort to maintain, are easily readable, and provide least security and takes bigger
storage space.
2. Binary files
Binary files are mostly the .bin files in your computer. Instead of storing data in plain text,
they store it in the binary form (0's and 1's). They can hold higher amount of data, are not
readable easily and provides a better security than text files.
File Operations
In C, there are six major operations on the file, either text or binary:
51
Working with files
Declare a pointer of type file; this declaration is needed for communication between the file
and program.
FILE *fptr;
ptr = fopen("fileopen","mode")
For Example:
fopen("E:\\cprogram\\test.dat","w");
fopen("E:\\cprogram\\test.dat","rb");
• Let's suppose the file newprogram.txt doesn't exist in the location E:\cprogram. The first
function creates a new file named newprogram.txt and opens it for writing as per the
mode 'w'. The writing mode allows you to create and edit (overwrite) the contents of the
file.
• Now let's suppose the second binary file oldprogram.bin exists in the location
E:\cprogram. The second function opens the existing file for reading in binary mode 'rb'.
The reading mode only allows you to read the file, you cannot write into the file.
Closing a File
The file (both text and binary) should be closed after reading/writing. Closing a file is
performed using library function fclose().
fclose(fptr);
For reading and writing to a text file, we use the functions fprintf() and fscanf().
#include <stdio.h>
#include <stdlib.h>
void main(){
int num;
FILE *fptr;
fptr = fopen("test.dat","w"); fopen returns
if(fptr == NULL) { a special value
printf("Error!"); NULL to
exit(1); // Program exits if the file pointer returns NULL. indicate that it
} couldnot open
printf("Enter num: "); entering a number into the file the file or
scanf("%d",&num); there is some
fprintf(fptr,"%d",num); error in the file
fclose(fptr); creation.
}
52
File
Meaning of Mode During Inexistence of file
Mode
r Open for reading. If the file does not exist, fopen() returns NULL.
rb Open for reading in binary mode. If the file does not exist, fopen() returns NULL.
a Open for append. If the file does not exists, it will be created.
ab Open for append in binary mode. If the file does not exists, it will be created.
Open for both reading and If the file exists, its contents are overwritten. If
w+
writing. the file does not exist, it will be created.
Open for both reading and If the file exists, its contents are overwritten. If
wb+
writing in binary mode. the file does not exist, it will be created.
53
Read from a text file using fscanf()
#include <stdio.h>
#include <stdlib.h>
int main(){
int num;
FILE *fptr;
printf("Value of n=%d",num);
fclose(fptr);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
struct date{
int n1, n2, n3;
};
int main(){
int n;
struct date num;
FILE *fptr;
if ((fptr = fopen("test.dat","wb")) == NULL){
printf("Error! opening file");
exit(1); // Program exits if the file pointer returns NULL.
}
for(n = 1; n < 5; ++n) {
num.n1 = n;
num.n2 = 5*n;
num.n3 = 5*n + 1;
fwrite(&num, sizeof(struct date), 1, fptr);
}
fclose(fptr);
return 0;
}
REMOVING a FILE
remove("test.dat");
#include <stdio.h>
#include <stdlib.h>
struct date{
int n1, n2, n3;
};
int main(){
54
int n;
struct date num;
FILE *fptr;
if ((fptr = fopen("C:\\program.bin","rb")) == NULL){
printf("Error! opening file");
exit(1); // Program exits if the file pointer returns NULL.
}
for(n = 1; n < 5; ++n) {
fread(&num, sizeof(struct date), 1, fptr);
printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2, num.n3);
}
fclose(fptr);
return 0;
}
Seeking the cursor to the given record in the file
fseek (FILE * stream, long int offset, int whence)
Whence Meaning
SEEK_SET Starts the offset from the beginning of the file.
SEEK_END Starts the offset from the end of the file.
SEEK_CUR Starts the offset from the current location of the cursor in the file.
#include <stdio.h>
#include <stdlib.h>
struct date{
int n1, n2, n3;
};
int main(){
int n;
struct date num;
FILE *fptr;
if ((fptr = fopen("test.dat","rb")) == NULL){
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
ftell() - It tells the byte location of current position of cursor in file pointer.
rewind() - It moves the control to beginning of the file.
printf("n1: %d\tn2: %d\tn3: %d\n%d\t", num.n1, num.n2, num.n3,ftell(fptr));
rewind (fptr);
55
#include<conio.h>
#include<stdlib.h>
void main(void) {
FILE *fp1, *fp2;
char ch;
clrscr();
fp1 = fopen("Sample.txt", "r");
fp2 = fopen("Output.txt", "w");
while (1) {
ch = fgetc(fp1);
if (ch == EOF) break;
else putc(ch, fp2);
}
printf("File copied Successfully!");
fclose(fp1);
fclose(fp2);
}
r+ does not truncate (delete) the content of file as well it doesn’t create a new file if such file
doesn’t exits while in w+ truncate the content of file as well as create a new file if such file doesn’t
exists.
Both of these functions deal with blocks of memories - usually arrays / pointers / structures /
unions
size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE
*a_file);
size_t fwrite(const void *ptr, size_t size_of_elements, size_t number_of_elements,
FILE *a_file);
Example
FILE *fp;
fp=fopen("c:\\test.bin", "wb");
char x[10]="ABCDEFGHIJ";
fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fp);
A system call is just what its name implies—a request for the operating system to do
something on behalf of the user‘s program #include <fcntl.h>
1. open()
2. read()
3. write()
4. close()
1. open()
open is rather like the fopen, except that instead of returning a file pointer, it returns a file
descriptor, which is just an int. open returns -1 if any error occurs.
56
int open( char *filename, int access, int permission );
2. read()
int read( int handle, void *buffer, int nbyte );
The read() function attempts to read nbytes from the file associated with handle, and places
the characters read into buffer. If the file is opened using O_TEXT, it removes carriage
returns and detects the end of the file. The function returns the number of bytes read. On end-
of-file, 0 is returned, on error it returns -1, setting errno to indicate the type of error that
occurred.
3. write()
The write() function attempts to write nbytes from buffer to the file associated with handle.
On text files, it expands each LF to a CR/LF. The function returns the number of bytes
written to the file. A return value of -1 indicates an error, with errno set appropriately.
4. close()
The close() function closes the file associated with handle. The function returns 0 if
successful, -1 to indicate an error, with errno set appropriately.
#include <stdio.h>
#include <fcntl.h>
int main(){
int fd;
char buffer[80];
static char message[]=”Hello, SPCE – Visnagar”;
fd=open(“myfile.txt”,O_RDWR);
if (fd != -1){
printf(“myfile.txt opened with read/write access\n”);
write(fd,message,sizeof(message));
lseek(fd,0,0);
read(fd,buffer,sizeof(message));
printf(“%s — was written to myfile.txt \n”,buffer);
close(fd);
}
}
57
FILE *fp;
int feof(FILE *fp); // returns a non-zero value when End-of-File else zero is returned.
int getch(void); // it won’t echo the input character on to the output screen
int getche(void);
int fseek(FILE *fp, long int offset, int whence); offset – Number of bytes to be moved from whence
int sprintf(char *string, const char *format, variable list); // sprintf ( string, “%d %c %f”, value, c, flt ) ;
int sscanf(const char *string, const char *format, variable list); // sscanf (buffer,”%s
%d”,name,&age);
58
‘C’ Function Exercises:
59
‘C’ Arrays Exercises:
60
Program samples
#include <stdio.h> //swap two numbers without a temporary variable
void main(){
int x = 10, y = 5;
x = x + y; // x now becomes 15 // using + and -
y = x - y; // y becomes 10
x = x - y; // x becomes 5
x = x * y; // x now becomes 50 // using * and /
y = x / y; // y becomes 10
x = x / y; // x becomes 5
x = x ^ y; // x now becomes 15 (1111) //using ^XOR logical addition
y = x ^ y; // y becomes 10 (1010)
x = x ^ y; // x becomes 5 (0101)
printf("After Swapping: x = %d, y = %d", x, y);
}
#include <stdio.h> // print “Hello C” using if-else statement both?
void main(){
if(!printf("Hello ")) ;
else printf("C\n");
}
#include <stdio.h> // find odd or even using bit wise operator
void main(){
int x;
printf("Enter a number: ");
scanf("%d", &x);
if(x&1) printf("%d is ODD\n", x);
else printf("%d is EVEN\n", x);
}
Number is odd or even without any relational and arithmetic operators?
#include <stdio.h>
void main(){
int number;
printf("Please input an integer number: ");
scanf("%d",&number);
(number & 0x01) ? puts("odd") : puts ("even");
printf("\n");
}
#include <stdio.h> // Given number is positive or negative or zero.
void main(){
float n;
printf("Please enter a number\n");
scanf("%f",&n);
if (n==0)printf("\nEntered number is 0. It's neither positive or
negative");
else if (n<0) printf("\nEntered number %.2f is negative.",n);
else printf("\nEntered number %.2f is positive.",n);
}
#include <stdio.h> // factorial
void main(){
int n, i;
unsigned long long factorial = 1;
scanf("%d",&n);
for(i=1; i<=n; ++i) factorial *= i; // factorial = factorial*i;
printf("Factorial of %d = %llu", n, factorial);
}
#include<stdio.h> //Fibonacci
void main(){
int n, first = 0, second = 1, next, c;
scanf("%d",&n);
for ( c = 0 ; c < n ; c++ ){
if ( c <= 1 ) next = c;
61
else{
next = first + second;
first = second;
second = next;
}
printf("%d\n",next);
}
}
#include <stdio.h> // LCM
void main(){
int n1, n2, LCM;
scanf("%d %d", &n1, &n2);
LCM = (n1>n2) ? n1 : n2;
while(1){
if(LCM %n1==0 && LCM %n2==0 ) {
printf("The LCM of %d and %d is %d.",n1, n2, LCM);
break;
}
++ LCM;
}
}
#include <stdio.h> // GCD HCF
void main(){
int n1, n2, i, gcd;
scanf("%d %d", &n1, &n2);
for(i=1; i <= n1 && i <= n2; ++i)
if(n1%i==0 && n2%i==0) gcd = i;
printf("G.C.D of %d and %d is %d", n1, n2, gcd);
}
#include <stdio.h> // gcd hcf using recursion
int hcf(int n1, int n2);
void main(){
int n1, n2;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
printf("G.C.D of %d and %d is %d.", n1, n2, hcf(n1,n2));
}
int hcf(int n1, int n2){
if (n2 != 0) return hcf(n2, n1%n2);
else return n1;
}
#include <stdio.h> // calculate the number of digits
void main(){
long long n; int count = 0;
printf("Enter an integer: ");
scanf("%lld", &n);
while(n != 0){
n /= 10; ++count;
}
printf("Number of digits: %d", count);
}
#include <stdio.h> // palindrome number
void main(){
int n, reversedInteger = 0, remainder, originalInteger;
printf("Enter an integer: ");
scanf("%d", &n);
originalInteger = n;
while( n!=0 ) {
remainder = n%10;
reversedInteger = reversedInteger*10 + remainder;
n /= 10;
62
}
if (originalInteger == reversedInteger)
printf("%d is a palindrome.", originalInteger);
else
printf("%d is not a palindrome.", originalInteger);
}
#include <stdio.h> //palindrome string
#include <string.h>
void main(){
char a[100], b[100];
printf("Enter the string to check if it is a palindrome\n");
gets(a); strcpy(b,a); strrev(b);
if (strcmp(a,b) == 0) printf("Entered string is a palindrome.\n");
else printf("Entered string is not a palindrome.\n");
}
# include <stdio.h> // printing an array in reverse order
void main(void){
int n,i;
int no[n];
scanf("%d",&n);
for(i=0;i<n;i++) scanf("%d",&no[i]);
for(i=n-1;i>=0;i--) printf("%d",no[i]);
}
#include <stdio.h> // sorting an array
void main(){
int array[100], n, c, d, swap;
scanf("%d", &n);
for (c = 0; c < n; c++) scanf("%d", &array[c]);
for (c = 0 ; c < ( n - 1 ); c++)
for (d = 0 ; d < n - c - 1; d++)
if (array[d] < array[d+1]) /* For decreasing order use < */ {
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
printf("Sorted list in ascending order:\n");
for ( c = 0 ; c < n ; c++ ) printf("%d\n", array[c]);
}
#include<stdio.h> //finding duplicates
void main(void){
int arr[] = {4, 2, 4, 5, 2, 3, 1}, i, j;
int size = sizeof(arr)/sizeof(arr[0]);
printf(" Repeating elements are ");
for(i = 0; i < size; i++)
for(j = i+1; j < size; j++)
if(arr[i] == arr[j])printf(" %d ", arr[i]);
}
#include<stdio.h> //matrix addition, subtraction, multiplication
void main() {
int i,j,c,r,k;
int a[20][20],b[20][20],ma[20][20],ms[20][20];
int mm[20][20];
scanf("%d%d",&c,&r);
for(i=0;i<c;i++) {
for(j=0;j<r;j++) scanf("%d",&a[i][j]);
printf("\n");
}
for(i=0;i<c;i++) {
for(j=0;j<r;j++) scanf("%d",&b[i][j]);
printf("\n");
}
63
for(i=0;i<c;i++)
for(j=0;j<r;j++) {
ma[i][j]=a[i][j]+b[i][j];
ms[i][j]=a[i][j]-b[i][j];
}
for(i=0;i<c;i++)
for(j=0;j<r;j++) {
mm[i][j]=0;
for(k=0;k<c;k++) mm[i][j] +=a[i][k]*b[k][j];
}
for(i=0;i<c;i++) {
for(j=0;j<r;j++) printf("\t\t%d",ma[i][j]);
printf("\n");
}
for(i=0;i<c;i++) {
for(j=0;j<r;j++) printf("\t\t%d",ms[i][j]);
printf("\n");
}
for(i=0;i<c;i++) {
for(j=0;j<r;j++) printf("\t\t%d",mm[i][j]);
printf("\n");
}
}
#include<stdio.h> // sorting strings
#include <string.h>
void main(){
int i,j,n;
char str[20][20],temp[20];
scanf("%d",&n);
for(i=0;i<=n;i++) gets(str[i]);
for(i=0;i<=n;i++)
for(j=i+1;j<=n;j++)
if(strcmp(str[i],str[j])>0){
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
printf("The sorted string\n");
for(i=0;i<=n;i++) puts(str[i]);
}
#include <stdio.h> // find number of words in given string
#include <string.h>
void main(){
char s[200]; int count = 0, i;
scanf("%[^\n]s", s);
for (i = 0;s[i] != '\0';i++)
if (s[i] == ' ') count++;
printf("number of words in given string are: %d\n", count + 1);
}
#include<stdio.h> // delete duplicate values from an array.
void main() {
int arr[20], i, j, k, size;
printf("\n Enter array size : "); scanf("%d", &size);
printf("\n Accept Numbers : ");
for (i = 0; i < size; i++) scanf("%d", &arr[i]);
printf("\n Array with Unique list : ");
for (i = 0; i < size; i++) {
for (j = i + 1; j < size;) {
if (arr[j] == arr[i]) {
for (k = j; k < size; k++)
arr[k] = arr[k + 1];
64
size--;
} else j++; } }
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
}
Program to print half pyramid a using numbers
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
#include <stdio.h>
void main(){
int i, j, rows;
printf("Enter number of rows: "); scanf("%d",&rows);
for(i=1; i<=rows; ++i){
for(j=1; j<=i; ++j) printf("%d ",j);
printf("\n");
}
}
Inverted half pyramid using numbers
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
#include <stdio.h>
void main(){
int i, j, rows;
scanf("%d",&rows);
for(i=rows; i>=1; --i){
for(j=1; j<=i; ++j)
printf("%d ",j);
printf("\n");
}
}
Program to print half pyramid a using alphabets
A
B B
C C C
D D D D
E E E E E
#include <stdio.h>
void main(){
int i, j;
char input, alphabet = 'A';
printf("Enter the uppercase character you want to print in last row:
");
scanf("%c",&input);
for(i=1; i <= (input-'A'+1); ++i){
for(j=1;j<=i;++j)
printf("%c", alphabet);
++alphabet;
printf("\n");
}
}
Program to print pyramid using numbers
1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
65
#include <stdio.h>
void main(){
int i, space, rows, k=0, count = 0, count1 = 0;
scanf("%d",&rows);
for(i=1; i<=rows; ++i) {
for(space=1; space <= rows-i; ++space){
printf(" ");
++count;
}
while(k != 2*i-1){
if (count <= rows-1){
printf("%d ", i+k);
++count;
}
else{
++count1;
printf("%d ", (i+k-2*count1));
}
++k;
}
count1 = count = k = 0;
printf("\n");
}
}
Write a C-program to print the following pattern.
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
5 6 7 8 9 8 7 6 5
#include <stdio.h>
void main(){
int i, space, rows, k=0, count = 0, count1 = 0;
scanf("%d",&rows);
for(i=1; i<=rows; ++i){
for(space=1; space <= rows-i; ++space) {
66
printf(" ");
++count;
}
while(k != 2*i-1){
if (count <= rows-1){
printf("%d ", i+k);
++count;
}
else{
++count1;
printf("%d ", (i+k-2*count1));
}
++k;
}
count1 = count = k = 0;
printf("\n");
} }
#include <stdio.h> // Right align half pyramid
void main(){
int i, j, k, l, r=24, c=80, p=c/2, v=1, t=5; // 1
printf("Enter number of rows: "); // 2 1
scanf("%d",&r); // 3 2 1
for(i=1; i<=r; ++i) {
for(j=0; j <= p; j++) printf(" ");
for (k=1;k<=i;k++) printf(" %d ", k);
printf("\n");
p-=4;
} }
A number is considered as perfect number when it satisfies the below
conditions. It should be a positive number When the sum of it's divisors
(excluding that number) are equal to that number Example for perfect
numbers: 6, 28, 496, 8128
Description:
1 + 2 + 3 = 6
1 + 2 + 4 + 7 + 14 = 28
#include<stdio.h>
void main(){
int number, sum=0, i=1;
printf("Please enter a number to check perfect number\n");
scanf("%d",&number);
while(i<number) {
if(number%i==0)
sum=sum+i;
i++;
}
if(sum==number)
printf("\nEntered number %d is a perfect number",i);
else
printf("\nEntered number %d is not a perfect number",i);
}
Pascal Triangle pattern:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
#include <stdio.h> //factorial using recursion
long int multiplyNumbers(int n);
void main(){
int n;
67
printf("Enter a positive integer: ");
scanf("%d", &n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n));
}
long int multiplyNumbers(int n){
if (n >= 1)
return n*multiplyNumbers(n-1);
else
return 1;
}
# include <stdio.h> // matrix multiplication
void main() {
int a[10][10], b[10][10], m[10][10], r1, c1, r2, c2, i, j, k;
scanf("%d %d", &r1, &c1);
scanf("%d %d",&r2, &c2);
for(i=0; i<r1; ++i)
for(j=0; j<c1; ++j)
scanf("%d", &a[i][j]);
for(i=0; i<r2; ++i)
for(j=0; j<c2; ++j)
scanf("%d",&b[i][j]);
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
for(k=0; k<c1; ++k)
m[i][j]+=a[i][k]*b[k][j];
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
printf("%d ", m[i][j]);
printf("\n\n");
}
# include <stdio.h> // switch example
void main() {
char operator;
double firstNumber,secondNumber;
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &operator);
printf("Enter two operands: ");
scanf("%lf %lf",&firstNumber, &secondNumber);
switch(operator)
{
case '+': printf("%.1lf + %.1lf = %.1lf",firstNumber, secondNumber,
firstNumber+secondNumber); break;
case '-': printf("%.1lf - %.1lf = %.1lf",firstNumber, secondNumber,
firstNumber-secondNumber); break;
case '*': printf("%.1lf * %.1lf = %.1lf",firstNumber, secondNumber,
firstNumber*secondNumber); break;
case '/': printf("%.1lf / %.1lf = %.1lf",firstNumber, secondNumber,
firstNumber/firstNumber); break;
default: printf("Error! operator is not correct");
}
}
# include <stdio.h> // enum example
enum suit {
club = 0,
diamonds = 10,
hearts = 20,
spades = 3,
ace = 25,
joker = 50
} card;
void main()
68
{
card = club;
printf("Size of enum variable = %d bytes", sizeof(card));
}
#include<stdio.h> //Fibonacci series using recursion
void printFibonacci(int);
int main(){
int k,n;
long int i=0,j=1,f;
scanf("%d",&n);
printf("%d %d ",0,1);
printFibonacci(n-2);
}
void printFibonacci(int n){
static long int first=0,second=1,sum;
if(n>0){
sum = first + second;
first = second;
second = sum;
printf("%ld ",sum);
printFibonacci(n-1); } }
#include <stdio.h> // lcm using recursion
int lcm(int, int);
void main(){
int a, b, result;
int prime[100];
printf("Enter two numbers: ");
scanf("%d%d", &a, &b);
result = lcm(a, b);
printf("The LCM of %d and %d is %d\n", a, b, result);
}
int lcm(int a, int b){
static int common = 1;
if (common % a == 0 && common % b == 0) return common;
common++;
lcm(a, b);
}
#include <stdio.h> // sorting strings using pointers
void main(){
char *str[10], *t; int i,j,n;
scanf("%d",&n);
for(i=0;i<n;i++) scanf("%s",&str[i]);
for(i=0; i<n; i++)
for(j=i+1; j<n; j++)
if (strcmp(&str[j-1], &str[j]) > 0){
t=str[j]; str[j]=str[j-1]; str[j-1]=t;
}
printf("\n");
for(i=0;i<5;i++) printf("%s\n",&str[i]);
}
#include <stdio.h> // to add two complex numbers:
struct complex {
int real, img;
};
void main(){
struct complex a, b, c;
printf("Please enter first complex number\n");
printf("Enter Real part of the 1st complex number\n");
scanf("%d", &a.real);
printf("Enter Imaginary part of the 1st complex number without i\n");
scanf("%d", &a.img);
69
printf("Please enter second complex number\n");
printf("Enter Real part of the 2nd complex number\n");
scanf("%d", &b.real);
printf("Enter Imaginary part of the 2nd complex number without i\n");
scanf("%d", &b.img);
c.real = a.real + b.real;
c.img = a.img + b.img;
if ( c.img >= 0 ) printf("The sum of two complex numbers =
%d + %di\n",c.real,c.img);
else printf("The sum of two complex numbers = %d
%di\n",c.real,c.img);
}
#include <stdio.h> //swap two numbers with pointer and function
void swap(int *xp, int *yp){
if (xp == yp) return; // Check if the two addresses are same
*xp = *xp + *yp;
*yp = *xp - *yp;
*xp = *xp - *yp;
}
void main(){
int x = 10, y=5; swap(&x, &y);
printf("After swap: x = %d, y=%d", x,y);
}
#include <stdio.h> // incrementing a pointer
const int MAX = 3;
void main () {
int var[] = {10, 100, 200};
int i, *ptr;
ptr = var;
for ( i = 0; i < MAX; i++) {
printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );
ptr++;
}
}
#include <stdio.h> //decrementing a pointer
const int MAX = 3;
void main () {
int var[] = {10, 100, 200};
int i, *ptr;
ptr = &var[MAX-1];
for ( i = MAX; i > 0; i--) {
printf("Address of var[%d] = %x\n", i-1, ptr );
printf("Value of var[%d] = %d\n", i-1, *ptr );
ptr--;
}
}
#include <stdio.h> // comparing pointers
const int MAX = 3;
void main () {
int var[] = {10, 100, 200};
int i, *ptr;
ptr = var;
i = 0;
while ( ptr <= &var[MAX - 1] ) {
printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );
ptr++;
i++;
}
}
70
#include <stdio.h>
void main () {
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} *i;
printf("%d", sizeof(i));
}
#include<stdio.h> //stack implementation using pointers
#include<conio.h>
#include<stdlib.h>
#define MAX 50
int size;
struct stack {
int arr[MAX];
int top;
};
void init_stk(struct stack *st) {
st->top = -1;
}
void push(struct stack *st, int num) {
if (st->top == size - 1) {
printf("\nStack overflow(i.e., stack full).");
return;
}
st->top++;
st->arr[st->top] = num;
}
int pop(struct stack *st) {
int num;
if (st->top == -1) {
printf("\nStack underflow(i.e., stack empty).");
return 0;
}
num = st->arr[st->top];
st->top--;
return num;
}
void display(struct stack *st) {
int i;
for (i = st->top; i >= 0; i--)
printf("\n%d", st->arr[i]);
}
void main() {
int element, opt, val;
struct stack ptr;
init_stk(&ptr);
printf("\nEnter Stack Size :");
scanf("%d", &size);
while (1) {
printf("\n\ntSTACK PRIMITIVE OPERATIONS");
printf("\n1.PUSH");
printf("\n2.POP");
printf("\n3.DISPLAY");
printf("\n4.QUIT");
printf("\n");
printf("\nEnter your option : ");
scanf("%d", &opt);
switch (opt) {
71
case 1:
printf("\nEnter the element into stack:");
scanf("%d", &val);
push(&ptr, val);
break;
case 2:
element = pop(&ptr);
printf("\nThe element popped from stack is : %d", element);
break;
case 3:
printf("\nThe current stack elements are:");
display(&ptr);
break;
case 4:
exit(0);
default:
printf("\nEnter correct option!Try again.");
}
}
}
#include<stdio.h> // length of string using pointer
void main() {
char str[20], *pt;
int i = 0;
gets(str);
pt = str;
while (pt[i++]);
printf("Length of String : %d", i-1);
}
#include<stdio.h> // string reverse using pointer
void main() {
char str[20], *pt;
int i = 0;
gets(str);
pt = str;
while (pt[i++]);
while (i>=0)
putchar(pt[i--]);
}
#include<stdio.h> //palindrome string using pointer
void main(){
char str[30];
char *a,*b;
printf("Enter a string :");
gets(str);
for(a=str ; *a!=NULL ;a++); //here a stores address for ‘str’ //
for(b=str, a-- ; a>=b; ) // b stores address for str//
{
if(*a==*b) //if we put * sign over a and b then it means the value of
str string variable//
{
a--;
b++;
}
else
break;
}
if(b>a)
printf("\nString is palindrome");
else
printf("\nString is Not palindrome");
72
}
#include <stdio.h> // sorting strings without strcmp
#include <string.h>
void main() {
char *a[] = {"NUTS","apple","nuts","APPLE","OOPS","oops"};
const char *s1, *s2;
int compRes,i,j;
int length = 9;
for (i = 0; i < length; i++) {
for (j = i+1; j < length; j++){
s1 = a[i];
s2 = a[j];
compRes = 0;
while(*s1 && *s2){
if(*s1!=*s2){
compRes = *s1 - *s2;
break;
}
++s1;
++s2;
}
if (compRes > 0 || (compRes == 0 && *s1)) {
char* temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
printf("%s ", a[i]);
}
printf("\n");
}
#include <stdio.h>
void main (){
FILE *fp;
fp = fopen("file.txt", "w+");
fputs("This is c programming.", fp);
fputs("This is a system programming language.", fp);
fclose(fp);
}
#include <stdio.h>
void main(){
FILE *fp;
char str[60];
fp = fopen("file.txt" , "r");
if(fp == NULL)
{
perror("Error opening file");
return(-1);
}
if( fgets (str, 60, fp)!=NULL ) puts(str);
fclose(fp);
}
#include <stdio.h>
void main (){
FILE *fp;
int c;
fp = fopen("file.txt","r");
while(!feof(fp))
{
c = fgetc(fp);
73
printf("%c", c);
}
fclose(fp);
}
#include <stdio.h>
void main(){
struct Date{
int d, m, y;
}f1,f2;
int t, td=0, y1,y2, m1,m2, d1,d2,i;
int md[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
scanf("%d%d%d",&f1.d,&f1.m,&f1.y);
scanf("%d%d%d",&f2.d,&f2.m,&f2.y);
if (f1.y < f2.y || f1.m < f2.m || f1.d < f2.d)
{y1=f2.y; y2=f1.y;m1=f2.m;m2=f1.m;d1=f1.d;d2=f2.d;}
else {y1=f1.y;y2=f2.y;m1=f1.m;m2=f2.m;d1=f1.d;d2=f2.d;}
printf("%d-%d-%d\n",y1,m1,d1);
printf("%d-%d-%d\n",y2,m2,d2);
while(y1>y2){
if (y2%4==0){
printf("\n leap year");
td=td+366;
}
else td=td+365;
y2++;
}
for(i=m2;i<m1;i++){
if (y2%4==0 && i==1){
printf("\nlast year is a leap year");
td=td+1;
}
td=td+md[i];
}
td=td+d2-d1+1;
printf("\n%d",td);
}
74
#include <conio.h> // 2 3 2
int main() // 3 4 5 4 3
{
int i,j,r,k=1,l=2,m=1;
scanf ("%d",&r);
for (i=1;i<=r;i++){
for(j=1;j<r+1-i;j++) printf(" ");
for(j=1;j<=l/2;j++) printf("%d ",k++);
getch();
m=k-2;
for(;j<l;j++){printf("%d ",m--);}
printf("\n");
l=l+2;
k=k-1;
}
}
// Conversion of a decimal number to binary, octal
#include <stdio.h>
void main(void){
int n, a[20],i=0;
scanf("%d",&n);
while (n > 0) {
a[i++]=n%2;
n = n / 2;
}
i--;
for(;i>=0;i--)
printf("%d",a[i]);
}
// decimal number to hexa decimal
#include<stdio.h>
void main(){
long int d,r,q; int i=1,j,t; char h[100];
scanf("%ld",&d);
q = d;
while(q>0){
t = q % 16;
if( t < 10) t = t + 48;
else t = t + 55;
h[i++]= t;
q = q / 16;
}
for(j = i -1 ;j> 0;j--) printf("%c",h[j]);
}
// binary number to decimal
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
void main()
{
int b, d = 0, c;
scanf("%d", &b);
for(c = 0; b > 0; c++){
d = d + pow(2, c) * (b % 10);
b = b / 10;
}
printf("\nDecimal Equivalent of Binary Number: \t %d\n", d);
}
#include <stdio.h> // binary number to octal
void main(void){
long int b, o=0;
75
int j=1, r;
scanf("%ld",&b);
printf("Binary = %ld\n", b);
while(b>0){
r = b % 10;
o = o + r * j;
j = j * 2;
b = b / 10;
}
printf("Octal = %lo\n", o);
}
#include<stdio.h> // Octal to Binary Conversion
void main()
{
long int i=0;
char octnum[1000];
gets(octnum);
while(octnum[i]) {
switch(octnum[i])
{
case '0' : printf("000"); break;
case '1' : printf("001"); break;
case '2' : printf("010"); break;
case '3' : printf("011"); break;
case '4' : printf("100"); break;
case '5' : printf("101"); break;
case '6' : printf("110"); break;
case '7' : printf("111"); break;
default : printf("Invalid Octal Digit"); break;
}
i++;
}
}
#include<stdio.h> // convert binary to octal
void main(){
char b[100],o[100];
long int i=0,j=0;
scanf("%s",b);
while(b[i]){
b[i] = b[i] -48;
++i;
}
--i;
while(i-2>=0){
o[j++] = b[i-2] *4 + b[i-1] *2 + b[i];
i=i-3;
}
if(i==1) o[j] = b[i-1] *2 + b[i];
else if(i==0) o[j] = b[i];
else --j;
while(j>=0){
printf("%d",o[j--]);
}}
#include<stdio.h> // convert binary to hexadecimal
void main(){
char b[100],h[100];
int t;
long int i=0,j=0;
scanf("%s",b);
while(b[i]){
b[i] = b[i]-48;
76
++i;
}
--i;
while(i-2>=0){
t = b[i-3] *8 + b[i-2] *4 + b[i-1] *2 + b[i];
if(t > 9) h[j++] = t + 55;
else h[j++] = t + 48;
i=i-4;
}
if(i==1) h[j] = b[i-1] *2 + b[i] + 48;
else if(i==0) h[j] = b[i] + 48;
else --j;
while(j>=0) printf("%c",h[j--]);
}
#include <stdio.h> // array insertion
void main()
{
int array[100], position, c, n, value;
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter %d elements\n", n);
for (c = 0; c < n; c++) scanf("%d", &array[c]);
printf("Enter the location where you wish to insert an element\n");
scanf("%d", &position);
printf("Enter the value to insert\n");
scanf("%d", &value);
for (c = n - 1; c >= position - 1; c--) array[c+1] = array[c];
array[position-1] = value;
printf("Resultant array is\n");
for (c = 0; c <= n; c++) printf("%d\n", array[c]);
}
#include <stdio.h> // array deletion
void main()
{
int array[100], position, c, n;
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter %d elements\n", n);
for (c = 0; c < n; c++) scanf("%d", &array[c]);
printf("Enter the location where you wish to delete element\n");
scanf("%d", &position);
if (position >= n+1) printf("Deletion not possible.\n");
else {
for (c = position - 1; c < n - 1; c++) array[c] = array[c+1];
printf("Resultant array:\n");
for (c = 0; c < n - 1; c++) printf("%d\n", array[c]);
}
}
#include <stdio.h> //bubble sort
void main()
{
int i, j,n,a[5]={10,15,30,45,70};
for (i = 0; i < 5; i++)
for (j = 0; j < 5-i-1; j++)
if (a[j] < a[j+1]){
n=a[j+1];
a[j+1]=a[j];
a[j]=n;
}
for (i = 0; i < 5; i++)
printf("%d\t",a[i]);
77
}
#include <stdio.h> //selection sort
void main()
{
int i, j,n,t,a[5]={10,15,30,45,70};
for (i = 0; i < 5-1; i++) {
n = i;
for (j = i+1; j < 5; j++)
if (a[j] > a[n]) n = j;
t=a[n];
a[n]=a[i];
a[i]=t;
}
for (i = 0; i < 5; i++)printf("%d\t",a[i]);
}
#include <stdio.h> //insertion sort
void main()
{
int i, j,n,t,a[5]={10,15,30,45,70};
for (i = 0; i < 5; i++) {
t = a[i];
j=i-1;
while(j>=0 && a[j] > t){
a[j+1]=a[j];
j=j-1;
}
a[j+1]=t;
}
for (i = 0; i < 5; i++)printf("%d\t",a[i]);
}
#include <stdio.h> //print all unique/frequency elements in array
void main()
{
int a[10], f[10];
int s, i, j, c;
printf("Enter size of array: ");
scanf("%d", &s);
printf("Enter elements in array: ");
for(i=0; i<s; i++)
{
scanf("%d", &a[i]);
f[i] = -1;
}
for(i=0; i<s; i++)
{
c = 1;
for(j=i+1; j<s; j++)
{
if(a[i] == a[j])
{
c++;
f[j] = 0;
}
}
if(f[i] != 0) f[i] = c;
}
printf("\nUnique/frequency/duplicate elements in the array are: ");
for(i=0; i<s; i++)
if(f[i] == 1)// if(f[i]!=0) printf("%d ",f[i]); frequency
printf("%d ", a[i]); //if(f[i]==0) printf("%d ",a[i]); duplicate
}
78
#include <stdio.h> // string length – strlen()
void main()
{
char a[20];
int i=0;
gets(a);
while(a[i++]!=NULL);
printf("%d ",i-1);
}
#include <stdio.h> // string copy – strcpy()
void main()
{
char a[20],b[20];
int i=0;
gets(a);
while(a[i]!=NULL){b[i]=a[i];i++;}
puts(b);
}
#include <stdio.h> // string concatenation - strcat()
void main()
{
char a[20],b[20],c[20];
int len,i=0,j=0;
gets(a);
gets(b);
while(a[i]!=NULL){c[i]=a[i];i++;}
while(b[j]!=NULL) c[i++]=b[j++];
puts(c);
}
#include <stdio.h> // counting alphabets, numbers, special characters
void main()
{
char a[20];
int i=0,alpha=0,digits=0,special=0;
gets(a);
while(a[i]!='\0'){
if((a[i]>='a' && a[i]<='z') || (a[i]>='A' && a[i]<='Z'))
alpha++;
else if (a[i]>='0' && a[i]<='9')
digits++;
else special++;
i++;
}
printf("%d\t%d\t%d",alpha,digits,special);
}
#include <stdio.h> // string comparison - strcmp()
void main()
{
char a[20],b[20]; int i=0; // Hello good - 1
gets(a); gets(b); // Good Hello – (-1)
while(a[i]!='\0' || b[i]!='\0'){ // hello hello - 0
if(a[i]!=b[i]) break;
i++;
}
i=a[i]-b[i];
printf("%d",i);
}
#include<stdio.h> // Delete all occurrences of a character from the string
void main() {
char a[10],b[10], ch;
int i, j = 0, len;
79
gets(a);
ch=getchar();
while(a[i++]!=NULL);
len = i;
for (i = 0; i < len; i++)
if (a[i] != ch)
b[j++] = a[i];
b[j] = '\0';
puts(b);
}
Search occurrence of a character in the string.
Replace a character in the string.
Check whether a character is uppercase. // A=65, Z=90
Check whether a character is lowercase. // a=97, z=122
Count number of uppercase and lowercase letters.
Replace lowercase character with uppercase letter. // difference is 32
Replace uppercase character with lowercase letter.
Encode a string and display encoded string. // char-10
Decode a string and display decoded string. // char+10
#include <stdio.h>//Replace a word in string. Good morning–> Good afternoon
#include <string.h>
void main(){
char s[80];
char w[10],rw[10],t[10][10];
int i=0,j=0,k=0,w,p;
gets(s);
printf("%s\n",s);
printf("\nENTER WORD IS TO BE REPLACED\n");
scanf("%s",w);
printf("\nENTER BY WHICH WORD THE %s IS TO BE REPLACED\n",word);
scanf("%s",rw);
p=strlen(s);
for (k=0; k<p; k++){
if (s[k]!=' '){
t[i][j] = s[k];
j++;
}
else{
t[i][j]='\0';
j=0; i++;
}
}
t[i][j]='\0';
w=i;
for (i=0; i<=w; i++){
if(strcmp(s[i],w)==0)
strcpy(s[i],rw);
printf("%s ",s[i]);
}
}
Reverse letter in each word of the entered string. // Hello students -> olleH stneduts
#include <stdio.h> // transpose matrix
void main(){
int m,n,c,d,matrix[10][10],transpose[10][10];
scanf("%d%d",&m,&n);
for (c=0;c<m;c++)
for(d=0;d<n;d++) scanf("%d",&matrix[c][d]);
for (c=0;c<m;c++)
for(d=0;d<n;d++) transpose[d][c]=matrix[c][d];
80
for (c=0;c<m;c++){
for (d=0;d<n;d++) printf("%d\t",matrix[c][d]);
printf("\n");
}
for (c=0;c<n;c++){
for (d=0;d<m;d++) printf("%d\t",transpose[c][d]);
printf("\n");
}
}
#include<stdio.h> // print Identity Matrix
void main(){
int size,row,col;
scanf("%d",&size);
for (row = 0; row < size; row++){
for (col = 0; col < size; col++)
if (row == col) printf("%d ", 1);
else printf("%d ", 0);
printf("\n");
}
}
#include <stdio.h> // checking whether matrix is an Identity or not
void main(){
int a[10][10], s, r, c, i;
scanf("%d",&s);
for(r=0; r<s; r++)
for(c=0; c<s; c++)scanf("%d", &a[r][c]);
i = 1;
for(r=0; r<s; r++)
for(c=0; c<s; c++)
if(r==c && a[r][c]!=1) i = 0;
else if(r!=c && a[r][c]!=0) i = 0;
for(r=0; r<s; r++){
for(c=0; c<s; c++)printf("%d ", a[r][c]);
printf("\n");
}
if(i==1)printf("\nThe given matrix is an Identity Matrix.\n");
else printf("The given matrix is not Identity Matrix");
}
#include <stdio.h> //determinant of 2x2 matrix
#define s 2 // Matrix size
void main(){
int a[s][s], r, c, d;
for(r=0; r<s; r++)
for(c=0; c<s; c++)
scanf("%d", &a[r][c]);
det = (a[0][0] * a[1][1]) - (a[0][1] * a[1][0]);
printf("Determinant of matrix A = %ld", det);
}
#include <stdio.h> //determinant of 3x3 matrix
#define s 3 // Matrix size
void main(){
int A[s][s], m, n;
int a, b, c, d, e, f, g, h, i;
long det;
for(m=0; m<s; m++)
for(n=0; n<s; n++) scanf("%d", &A[m][n]);
a = A[0][0];b = A[0][1];c = A[0][2];
d = A[1][0];e = A[1][1];f = A[1][2];
g = A[2][0];h = A[2][1];i = A[2][2];
det = (a*(e*i-f*h))-(b*(d*i-f*g))+(c*(d*h-e*g));
printf("Determinant of matrix A = %ld", det); }
81
#include<stdio.h> //puzzle
void main(){
int i = 10;
int c = 10;
switch(c) {
case i: // not a "const int" expression
printf("Value of c = %d", c);
break;
} } // [Error] case label does not reduce to an integer constant
#include<stdio.h> //puzzle
void main(void){
int i = 0;
for(i = 0; i < 3; i++) {
printf("loop ");
continue;
} } // Output: loop loop loop
#include<stdio.h> //puzzle
void main(void){
int i = 0;
while(i < 3){
printf("loop"); /* printed infinite times */
continue;
i++; /*This statement is never executed*/
} } // infinite loop
#include <stdio.h> //puzzle
void main(){
float x = 1.1;
switch (x) {
case 1.1: printf("Choice is 1"); break;
default: printf("Choice other than 1, 2 and 3"); break;
}
} // [Error] switch quantity not an integer
[Error] case label does not reduce to an integer constant
#include <stdio.h> //puzzle
void main(){
int i = 0;
while ( 1 ) {
printf( "%d\n", ++i );
if (i == 5) break; // Used to come out of loop
}
} // Output: 1 \n 2 \n 3 \n 4 \n 5
# include <stdio.h> //puzzle
void main() {
int i = 0;
while ( 0 ) { // This line will never get executed
printf( "%d\n", ++i);
if (i == 5) break;
}
} // Output: Nothing printed
#include <stdio.h> // There is no break in all cases
void main(){
int x = 2;
switch (x) {
case 1: printf("Choice is 1\n");
case 2: printf("Choice is 2\n");
case 3: printf("Choice is 3\n");
default: printf("Choice other than 1, 2 and 3\n");
}
} // Output: case 2, 3, and default are executed
82
#include <stdio.h> // A program with variable expressions in labels
void main(){
int x = 2;
int arr[] = {1, 2, 3};
switch (x) {
case arr[0]: printf("Choice 1\n");
case arr[1]: printf("Choice 2\n");
case arr[2]: printf("Choice 3\n");
}
} // [Error] case label does not reduce to an integer constant
#include <stdio.h> //puzzle
void main(){
int x = 1;
switch (x) {
x = x + 1; // Statements before all cases are never executed
case 1: printf("Choice is 1"); break;
case 2: printf("Choice is 2"); break;
default: printf("Choice other than 1 and 2"); break;
}
} // Output: Choice is 1
#include <stdio.h> //puzzle
void main(){
int x = 1;
switch (x) {
case 2: printf("Choice is 1"); break;
case 1+1: printf("Choice is 2"); break;
}} // [Error] duplicate case value
#include <stdio.h> // C program to illustrate using range in switch void
void main(){
int i, arr[] = { 1, 5, 15, 20 };
for ( i = 0; i < 4; i++) {
switch (arr[i]) {
case 1 ... 6: printf("%d in range 1 to 6\n", arr[i]); break;
case 19 ... 20: printf("%d in range 19 to 20\n", arr[i]); break;
default: printf("%d not in range\n", arr[i]); break;
}
}
} // Output: Prints all 3 case statements
#include<stdio.h> //puzzle
void main() {
if(!printf("Hello"))
printf("Hello");
else
printf("World");
} // Output: HelloWorld
#include <stdio.h> //puzzle
void main(){
int i, n = 20;
for (i = 0; i < n; i-- or n-- or n++ or i++) printf("*");
} // Output: i--, n++ infinite loop, i++, n-- prints 20 times *
#include<stdio.h>
void main() {
int a=1;
switch(a) {
case ‘1’: printf("ONE\n"); break;
case '2': printf("TWO\n"); break;
defau1t: printf("NONE\n");
}
} // No Output - case values are in char, but a is int
83
#include<stdio.h> //puzzle
void main(){
int b=1;
switch(b) {
int b=20; // not executed
case 1: printf("b is %d\n",b); break;
default: printf("b is %d\n",b); break;
}
} // Output: b is 1
void main(){ //puzzle
int x = 2, y = 5;
(x & y)? printf("True ") : printf("False ");
(x && y)? printf("True ") : printf("False ");
} // Output: False True
void main(){ //puzzle
int x = 19;
printf ("x << 1 = %d\n", x << 1);
printf ("x >> 1 = %d\n", x >> 1); } // Output: 38 9
void main(){ //puzzle
int x = 19;
(x & 1)? printf("Odd"): printf("Even"); // Output: Odd
(x & 0)? printf("Odd"): printf("Even"); // Output: Even
} // Output: EvenOdd
void main(){ //puzzle
unsigned int x = 1;
printf("Signed Result %d \n", ~x);
printf("Unsigned Result %ud \n", ~x);
} // Output: Signed Result -2
// Unsigned Result 4294967294d
84
#include <stdio.h> //GCD or HCF using recursion
int hcf(int n1, int n2);
void main(){
int n1, n2;
scanf("%d %d", &n1, &n2);
printf("G.C.D of %d and %d is %d.", n1, n2, hcf(n1,n2));
}
int hcf(int n1, int n2){
if (n2 != 0) return hcf(n2, n1%n2);
else return n1;
}
85
#include<stdio.h> // number writing and reading from file
void main(){
FILE *fp;
int i=10, j=20, k=3, num;
fp = fopen ("test.dat","w");
putw(i,fp);
putw(j,fp);
fclose(fp);
fp = fopen ("test.dat","r");
do {
num= getw(fp);
if(num!=-1) printf("Data in test.dat file is %d \n", num);
}while(num!=-1);
fclose(fp);
}
86
# include <stdio.h> // character reading from file
int main(){
FILE *fp ;
char c ;
fp = fopen ( "test.dat", "r" ) ;
if ( fp == NULL )
{
printf ( "Could not open file test.dat" ) ;
return 1;
}
while ( 1 )
{
c = fgetc ( fp ) ;
if( feof(fp) ) break ;
printf ( "%c", c ) ;
}
fclose ( fp ) ; // Closing the file
}
87
#include <stdio.h> // example for malloc
#include <stdlib.h>
void main(){
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) malloc(n * sizeof(int));
if(ptr == NULL){
printf("Error! memory not allocated."); exit(0);
}
printf("Enter elements: ");
for(i = 0; i < n; ++i) {
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
}
#include <stdio.h> //example for calloc
#include <stdlib.h>
void main(){
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) calloc(n, sizeof(int));
if(ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements: ");
for(i = 0; i < n; ++i) {
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
}
#include <stdio.h> //example for realloc
#include <stdlib.h>
void main(){
int *ptr, i , n1, n2;
printf("Enter size of array: ");
scanf("%d", &n1);
ptr = (int*) malloc(n1 * sizeof(int));
printf("Addresses of previously allocated memory: ");
for(i = 0; i < n1; ++i) printf("%u\n",ptr + i);
printf("\nEnter new size of array: ");
scanf("%d", &n2);
ptr = realloc(ptr, n2 * sizeof(int));
printf("Addresses of newly allocated memory: ");
for(i = 0; i < n2; ++i) printf("%u\n", ptr + i);
free(ptr);}
88