Prog Lang C
Prog Lang C
Prog Lang C
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
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.
5
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.
6
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)
7
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 −
8
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
9
Octal Number: 258 = Binary Number: 101012
Step 2 101012 28 58
10
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
11
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
12
Low-Level Programming
Object code is small and efficient. Optimize the use of three resources: Execution time,
Memory, Development/maintenance time.
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 func1(void) {
printf("%sn",__func__);
return;
}
int main() {
myfunc();
}
The output would be func1
13
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.
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.
14
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.
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
15
Floating Point Constant:
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.
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.
16
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.
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.
17
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
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 –
18
> 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.
>= 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 –
&& 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
19
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
20
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.
21
?: 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.
22
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
The gets() and puts() Functions
The char *gets(char *s) function reads a line from stdin into the buffer pointed to by s until
either a terminating newline or EOF (End of File).
The int puts(const char *s) function writes the string 's' and 'a' trailing newline to stdout.
#include <stdio.h>
23
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
The scanf() and printf() Functions
The int scanf(const char *format, ...) function reads the input from the standard input
stream stdin and scans that input according to the formatprovided.
The int printf(const char *format, ...) function writes the output to the standard output
stream stdout and produces the output according to the format provided.
The format can be a simple constant string, but you can specify %s, %d, %c, %f, etc., to print
or read strings, integer, character or float respectively. There are many other formatting
options available which can be used based on requirements. Let us now proceed with a
simple example to understand the concepts better −
#include <stdio.h>
int main( ) {
char str[100];
int i;
printf( "Enter a value :");
scanf("%s %d", str, &i);
printf( "\nYou entered: %s %d ", str, i);
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 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
24
string, scanf() stops reading as soon as it encounters a space, so "this is test" are three strings
for scanf().
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;
}
else if(expression) {
Block of statements;
}
else {
Block of statements;
}
25
? : 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)
{
Single statement
or
Block of statements;
}
26
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
27
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
28
int main (int argc, char *argv[]) {
int counter;
for (counter = 0; counter < argc; counter++)
printf ("%s\n", argv[counter]);
return 0;
}
Recursive Functions
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.
Nested Functions
• can define functions within other functions
// add.c
int add(int a, int b) {
return a + b;
}
Storage Class
29
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();
}
30
#include <stdio.h>
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 {
int i;
float f;
31
};
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 };
32
struct point first_point = { y: 10, x: 5 };
struct point {
int x, y;
} first_point = { 5, 10 };
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
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.
33
Syntax for array declaration:
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
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.
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;
}
Initializing Arrays
Array elements can be initialized while declaring it by listing the initializing values, separated
by commas, in a set of braces.
void main(void){
int i, my_array[5] = { 0, 1, 2, 3, 4 };
for(i=0;i<5;i++)
34
printf("%d\n",my_array[i]);
}
For example, this code initializes the first three elements as specified, and then initializes the
last two elements to a default value of zero:
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.
35
my_array[0] = 5;
That assigns the value 5 to the first element in the array, at position zero.
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.
36
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.
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.
37
Access the structure members in the array using the member access operator.
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
38
#undef Undefines a preprocessor macro.
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
39
#include <stdio.h>
int main(void) {
printf("Here is the message: %s\n", MESSAGE);
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''.
40
The indirection or dereference operator * gives the ``contents of an object pointed to by a
pointer''.
Declaring Pointers
data-type * name;
data-type *name;
data-type* name;
Initializing Pointers
41
int i;
# include <stdio.h>
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).
.
.
42
&arr[i] is equivalent to (arr + i) AND, arr[i] is equivalent to *(arr + i).
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.
43
44
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
There are four arithmetic operators that can be used in pointers: ++, --, +, -
ptr++;
ptr--;
ptr=ptr+1;
ptr=ptr-1;
45
Memory allocation – Dynamic – Run time
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;
#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);
}
46
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.
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:
1) Uninitialized pointers might cause segmentation fault.
2) Dynamically allocated block needs to be freed explicitly.Otherwise, lead to memory leak.
3) If pointers are updated with incorrect values, it might lead to memory corruption.
4) Pointer bugs are difficult to debug.
47
Data Files
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:
Declare a pointer of type file; this declaration is needed for communication between the file
and program.
FILE *fptr;
ptr = fopen("fileopen","mode")
48
For Example:
fopen("E:\\cprogram\\newprogram.txt","w");
fopen("E:\\cprogram\\oldprogram.bin","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("C:\\program.txt","w");
if(fptr == NULL) {
printf("Error!");
exit(1); // Program exits if the file pointer returns NULL.
}
fprintf(fptr,"%d",num);
fclose(fptr);
return 0;
}
49
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.
50
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 threeNum{
int n1, n2, n3;
};
int main(){
int n;
struct threeNum num;
FILE *fptr;
if ((fptr = fopen("C:\\program.bin","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 threeNum), 1, fptr);
}
fclose(fptr);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
struct threeNum{
int n1, n2, n3;
};
int main(){
int n;
struct threeNum num;
FILE *fptr;
if ((fptr = fopen("C:\\program.bin","rb")) == NULL){
51
printf("Error! opening file");
exit(1); // Program exits if the file pointer returns NULL.
}
for(n = 1; n < 5; ++n) {
fread(&num, sizeof(struct threeNum), 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
struct threeNum{
int n1, n2, n3;
};
int main(){
int n;
struct threeNum num;
FILE *fptr;
if ((fptr = fopen("C:\\program.bin","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);
void main(void) {
52
FILE *fp1, *fp2;
char ch;
clrscr();
fp1 = fopen("Sample.txt", "r");
fp2 = fopen("Output.txt", "w");
while (1) {
ch = fgetc(fp1);
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.
53
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);
}
}
54
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);
55
‘C’ Function Exercises:
56
‘C’ Arrays Exercises:
57
Program samples
# 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>
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");
}
for(i=0;i<c;i++)
for(j=0;j<r;j++)
58
{
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");
}
}
59
#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);
}
60
#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++;
}
}
#include <stdio.h>
void main () {
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} *i;
printf("%d", sizeof(i));
}
61
void display(struct stack *st) {
int i;
for (i = st->top; i >= 0; i--)
printf("\n%d", st->arr[i]);
}
int 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) {
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.");
}
}
return (0);
}
62
#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;
}
if (originalInteger == reversedInteger)
printf("%d is a palindrome.", originalInteger);
else
printf("%d is not a palindrome.", originalInteger);
}
63
#include <stdio.h> // sorting strings without strcmp
#include <string.h>
int 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");
return 0;
}
int main()
{
int n;
printf("Enter a positive integer: ");
scanf("%d", &n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n));
return 0;
}
long int multiplyNumbers(int n)
{
if (n >= 1)
return n*multiplyNumbers(n-1);
else
return 1;
}
64
#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);
return 0;
}
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> //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;
else{
next = first + second;
first = second;
second = next;
}
printf("%d\n",next);
}
}
65
#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;
}
}
66
#include <stdio.h>
int main ()
{
FILE *fp;
fp = fopen("file.txt", "w+");
fputs("This is c programming.", fp);
fputs("This is a system programming language.", fp);
fclose(fp);
return(0);
}
#include <stdio.h>
int 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);
return(0);
}
#include <stdio.h>
int main ()
{
FILE *fp;
int c;
fp = fopen("file.txt","r");
while(!feof(fp))
{
c = fgetc(fp);
printf("%c", c);
}
fclose(fp);
return(0);
}
67
Write a C-program to print “Hello C” using if-else statement both?
#include <stdio.h>
void main(){
if(!printf("Hello ")) ;
else printf("C\n");
}
#include <stdio.h>
void main(){
int number;
printf("Please input an integer number: ");
scanf("%d",&number);
(number & 0x01) ? puts("odd") : puts ("even");
printf("\n");
}
68
#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");
}
}
#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");
}
}
1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
69
#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");
}
}
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
#include <stdio.h>
void main(){
int i, space, rows, k=0, middle=20;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=1; i<=rows; ++i, k=0) {
for(space=1; space<=middle-i; ++space) printf(" ");
while(k != 2*i-1) {
printf("* "); // printf("%d ",k);
++k;
}
printf("\n");
}
}
70
Program to print pyramid using numbers
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;
printf("Enter number of rows: ");
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");
}
}
71
NATIONAL INSTITUTE OF TECHNOLOGY, DURGAPUR – 713209.
72
NATIONAL INSTITUTE OF TECHNOLOGY, DURGAPUR – 713209.
1. Convert the decimal number 101 to binary, octal, and hexa decimal. (6)
2. Write a C program to generate Fibonacci series. (4)
3. Write a C program for finding factorial using recursion. (6)
4. Explain structure and union with an example and differentiate. (4)
5. Write a C program to find given string is palindrome or not. (4)
6. Write a program in C to count the frequency of each element of an array. (6)
73