Programming in C
Programming in C
An Overview of C
Structured language
Why use C?
The text editor and compiler are integrated the aU variables. An identifier, also known as a
in certain systems, such Borland C++. We variable name, is made up of a string of letters,
presume that the reader is able to produce C digits, and underscores but cannot begin with a
code files using a text editor. These files are digit. The selection of identifiers should take into
known as source files, and on the majority of account the program's intended use. They act as
UNIX systems, they are compiled using the cc documentation in this way, improving software
command, which launches the C compiler. The readability.
An Overview of C - Unit 1 2
In file marathon.c of operators with variables and constants is also
an expression, as is the name of a variable by
/*' The distance of a marathon in kilometers. */
itself.
#include <stdio.h>
Conversion rules may be incorporated into the
An Overview of C - Unit 1 3
as preprocessor directives. They do not end constant values or expressions with names
with a semicolon and start with the symbol "#." that can be reused frequently. The defined
Preprocessor directives used frequently in C macros name replaces each time a #define C
include : pre processor directive is encountered with a
specific constant value or expression.
To include header files in a source
code file, use this directive. The Syntax of #define in C
#include header file's location can be
The following is the syntax for the C #define
specified using either double
quotes ("") or angle brackets (<>). preprocessor directive:
An Overview of C - Unit 1 4
Output: • Creating platform-specific code: The
programmer can write platform-specific
Circumference of Circle : 351.68
code for several operating systems or
value can subsequently be used in place programming to include header files in a source
of the value throughout the program. For code file. Function and variable declarations that
instance, one could use a macro called PI, can be utilised in the source code file are found
defined as #define PI 3.14159, instead of in the header file. With the preprocessor directive
using the value 3.14159 throughout the "#include" and the header file's name enclosed in
An Overview of C - Unit 1 5
Example of #include in C • Including standard library headers:
Headers like "stdio.h" and "stdlib.h" include
#include <stdio.h>
declarations for several of the standard C
int main() { library functions, including "printf,""scanf,"
and "malloc." To make the functions they
int a, b, product; contain available to the remainder of the
// we can use printf() and scanf() function program, these headers are normally
// these functions are pre-defined in the • Including user-defined header files: The
stdio.h header file declarations of functions, variables, and
other constructs that a programmer uses
printf("Enter two numbers to find their sum across numerous source files can be found
: ");
in their own header files. Programmers
scanf("%d %d", &a, &b); can reuse declarations that are common
across several source files and lessen
product = a*b; code duplication by including these header
files.
printf("Sum of %d and %d is : %d", a, b,
product); • Including third-party headers: In order to
use the functionality offered by third-party
return 0;
libraries or frameworks in a C program,
} it is frequently essential to include the
appropriate header files.
Output:
• Conditional inclusion of headers: In order
Enter two numbers to find their sum : Sum of
to include or exclude header files depending
3 and 4 is : 12
on specific criteria, preprocessor directives
Explanation: like #ifdef, #ifndef, #if, #else, and #endif
might be used.
The header file "stdio.h," which includes
definitions of functions for taking input and • Creating custom macros: Custom macros
creating output, has been included in the code can be built by the programmer using the
above. Because we included the header file using #define directive and then added to source
the #include keyword, we can utilise the scanf() files using the #include directive.
and printf() functions.
Printf() and scanf()
Uses of #include in C
Both the result and user input are displayed
Using "#include" frequently in C involves:
using the printf() and scanf() functions,
An Overview of C - Unit 1 6
respectively. In the C programming language, Simple Example of printf() Function
the printf() and scanf() methods are often used.
#include<stdio.h>
These functions are built-in library functions
found in C programming header files. int main()
printf() Function {
Syntax
scanf("format specifier",argument_list);
An Overview of C - Unit 1 7
int x; a system development language because
it produces code that runs nearly as fast as
printf("enter the number =");
the code written in assembly language.
scanf("%d",&x);
• The evolution of expressions can involve
An Overview of C - Unit 1 8
UNIT 2
When several variables of the same type are required, arrays are
utilized.
int a[3];
For Example: In C
#include<stdio.h>
#define CLASS_SIZE 5
} Score[4] = 53
for (i 0; i < CLASS_SIZE - 1; ++i) /* bubble sort 378 is the sum of all scores
*/
75.6 is the class average
for (j = CLASS_SIZE - 1; j > i;--j)
The application sorts the scores using a
if (score[j-1J < score[j]) { /* check the order */ bubble sort. This design is commonly carried out
using nested for loops, with a test being made
tmp = score[j-l];
in the inner loop's body to determine whether a
score[j-1] = score[jJ; score[j] = tmp; pair of elements are in the correct order. When
elements are compared that are not in the proper
} sequence, their values are switched. Here, the
code carries out this transaction.
printf("\nOrdered scores:\n\n");
mp = score[j-1];
for (; = 0; i < CLASS_SIZE; ++i)
score[j-1] = score[j];
printf(" score[%d] =%5d\n", i, score[i]);
score[j] =: tmp;
printf("\n%18d%s\n%18.lf%s\n\n",
The variable tmp in the first sentence holds
sum, " the sum of all the scores",
the value of score [j-l]. In the next sentence, the
(double) sum / CLASS_SIZE, " the class value of score [j] is used in place of the value of
average"); score [j-1] that was previously stored in memory.
The final sentence substitutes the value of score
return 0; [j] for the original value of score I, which is now
stored in tmp.
}
By manually executing the program with
The results will appear on the screen if we run
the given data, the reader will be able to see
the application and enter the scores 63, 88, 97,
why this bubble sort construct of two nested
53, and 77 when prompted.
far loops results in an array containing sorted
Input 5 Scores: 63 88 97 53 77 elements. With each iteration of the outer loop,
Variable
operator's precedence is higher than a division H e l l o \0
In addition to demonstrating how to utilise strings char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
in this part, we also want to demonstrate the use
of getchar() and putchar (). These are macros printf("Output message: %s\n", greeting );
Several functions that work with null- /* total lenghth of str1 after concatenation */
terminated strings are available in C:
len = strlen(str1);
strcpys1, s2 Copies string s2 into string s1.
printf("strlen(str1) : %d\n", len );
Concatenates string s2 onto
strcats1, s2;
the end of string s1. return 0;
strlen(str1) : 10
The example below uses a few of the
aforementioned features: Pointers
#include <stdio.h> You must have a solid working understanding
of pointers if you wish to be effective at
#include <string.h>
developing code in the C programming language.
int main () One of those concepts that C beginners find
challenging is the idea of pointers. This unit's
{ goal is to introduce pointers and demonstrate
how to use them effectively in C programming.
char str1[12] = "Hello";
Ironically, the terminology used for pointers in C
char str2[12] = "World"; is more of a challenge than the actual idea itself.
There are three primary uses for pointers in C.
char str3[12];
They are initially employed to create dynamic
int len ; data structures, which are composed of run-
time heap-allocated memory chunks. Second, C
/* copy str1 into str3 */
handles pointers used as variable parameters in
strcpy(str3, str1); functions. Finally, dealing with strings makes use
of pointers in C, which provides an alternative
printf("strcpy( str3, str1) : %s\n", str3 ); method of accessing data kept in arrays. A
typical variable is a location in memory that can
/* concatenates str1 and str2 */
be used to store a value.
strcat( str1, str2);
For instance, four bytes of memory are
• When addresses are used to alter the The programmer must be familiar with the
data directly, the application will run more proper commands for adding and editing text in
quickly. order to use an editor.
• Memory space will be saved. • Compile the program. The command will
enable you to achieve this.
• Memory access will be quick and effective.
cc pgm.c
• Allotted memory is dynamic.
is being run; syntax problems are captured by an array name by itself is a pointer. Because
In file sum.c {
The compiler uses the white space between as a separate token even if they are close to one
another. We had the option to write
int and a to distinguish between the two tokens.
Nobody is a writer. & a, &b, or &a,&b
Absum would be regarded as an identifier by Operators are the letters = and +. White space
the compiler. will not be used in this area, thus we may have
Iamamidentifier2
Figure: Keywords in C
They all employ the character +, although ++ + (unary) - (unary) ++ (prefix) -- (prefix) right to left
Fundamental data types are the data types which are predefined
Define the concepts
declarations, expressions, and in the language and can be directly used to declare a variable in C.
assignment Fundamental data types are the basic data types and all other data
types are made from these basic data types.
Recognize the use of getchar()
and putchar() A program works with things called variables and constants. All
variables in C must be declared before use. This could be how a
Infer mathematical functions
program's introduction would appear.
#include <stdio.h>
int main(void)
int
float
a, b, c;
x, y = 3.3, z -7.7;
a = b + c;
x = y + z;
Each variable that is declared has a type operator in C. An example of an assignment
associated with it, which instructs the compiler expression is as follows:
to reserve the necessary amount of memory
space to retain the values for the variables. It i =7
also enables the compiler to precisely instruct
The expression as a whole is given the
the machine to do the specified tasks. At the
value 7, and the variable i is given the value 7.
machine level, using the operator + to two
An expression becomes a statement, or more
variables of type int in the expression b + c is
specifically, an expression statement, when
different from doing it to variables of type float in
it is followed by a semicolon. These are a few
the equation y + z.
instances of statements:
A block of declarations and statements is but they have no purpose. In contrast to others,
certain compilers will alert users to these
enclosed by the braces { and}. The statements
assertions.
must come before any declarations.
3.777;
Operators, function calls, constants, and
variables are logically combined to form a + b;
expressions. A constant, variable, or function
Let's take a look at a sentence that starts with
call by itself can also constitute an expression.
a basic assignment expression and ends with a
Several examples of phrases are given below:
semicolon. The form will be as follows:
a+b
Variable = expr;
sqrt(7.333)
The right-hand side of the equal sign of the
5.0 * x - tan(9.0 / x) expression's value is computed first. The value is
subsequently assigned to the variable to the left
Phrases frequently contain a value. For
of the equal sign, which acts as the value of the
instance, the expression "a + b" has a clear value assignment expression as a whole. (Statements
dependent on the values of the variables a and b. have no intrinsic value.) The value of the
If a and b both have values of 1, then a + b has a assignment phrase as a whole is not employed
value of 3. in this case, as is to be noted. That is entirely OK.
The value that an expression generates is not
The equal symbol = is the basic assignment
necessary to be used by the programmer.
table. We can offer the basic declaration syntax from the keyboard's standard input stream. The
The putchar macro allows a single character int count =0, i =0;
to be written to the standard output stream
char Str [33] ;
(i.e., display). Putchar (c), where c is an integer
clrscr();
expression denoting the character to be written,
is the syntax for calling this macro. We generally printf("Write a short sentence:\n");
pass a character to this macro even though it //The following code counts number of
needs an argument of type int. The input value characters in string.
(c) is converted to an unsigned char and written
while ( (ch = getchar ()) != '.') {
to the standard output stream.
Str[i] = ch;
The getch and getche Functions
count++;
The getchar macro's use of line buffering i++;
makes it inappropriate for interactive settings.
}
There isn't a facility in the C standard library
that promises to deliver an interactive character Str[i] = '\0';
input. Because of this, the majority of C compilers // append null character at end of string
include substitute functions for usage in these
printf("The number of characters read are=
interactive settings. They consist of the getch
%d\n", count);
and getche functions offered in the console I/O
header file, <conio.h>. Calls to these functions printf("You have written the following
function: getch () and getche (). Both Dev-C++ puts(Str); //display the string on std <a
and Turbo C/C++ include these functions. These href="https://Test.com" data-internallinksma
functions have the names _getch and _getche in nager029f6b8e52c="6" rel="nofollow">output
Visual C++. device</a>.
C Math Example
#include<stdio.h>
According to the while expression, when the
character '.' is encountered, the system stops #include <math.h>
printf("\n%f",floor(3.6));
Mathematical Functions
printf("\n%f",floor(3.2));
Via the functions defined in the <math.
h> header file, we can execute mathematical printf("\n%f",sqrt(16));
operations using the C programming language.
Many methods for carrying out mathematical printf("\n%f",sqrt(7));
operations, including sqrt(), pow(), ceil(), and
printf("\n%f",pow(2,4));
floor(), are included in the header file <math.h>.
printf("\n%f",pow(3,3));
C Math Functions
printf("\n%d",abs(-12));
The header file math.h contains a number of
methods. Here are listed some of the math.h return 0;
header file's frequently used functions.
}
No . Function Description
rounds up the given number. It Output:
returns the integer value which
1) ceil(number)
is greater than or equal to given
number.
rounds down the given number.
It returns the integer value which
2) floor(number)
is less than or equal to given
number.
returns the square root of given
3) sqrt(number)
number.
is a I-byte integral type mostly used for Casts can be used to force explicit
• Three floating types, float, double, and • Suffixes can be used to explicitly specify
the type of a constant. For example, 3U of
long double, are provided to represent real
type unsigned, and 7. 0F is of type float.
numbers. Typically, a float is stored in 4
bytes and a doub1 e in 8 bytes, the number • A character constant such as 1 A I is of
of bytes used to store along double varies type int in C, but it is of type char in C++.
from one compiler to another. However, as This is one of the few places where c++
compilers get updated, the trend is to store differs from C.
Operator In C
In this formula, "c" is equal to "a + b," where "a" and "b" are the
operands and "+" is the addition operator. The compiler is instructed
to add both operands, "a" and "b," by the addition operator.
C can be divided into six kinds and has a large number of built-in
operators:
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators
C Language code for arithmetic operator
#include <stdio.h>
main()
int a = 21;
Arithmetic Operators
int b = 10;
This operator is used to calculate numbers.
They are one of the binary or unary arithmetic int c ;
operators. where the unary arithmetic operator,
such as +,-, ++, --,!, tiled, only required one operand. c = a + b;
Addition, subtraction, multiplication, and division
are among these operators. In contrast, the printf("Line 1 - Value of c is %d\n", c );
binary arithmetic operator has two operands
and has the following operators: + (addition), - c = a - b;
(subtraction), * (multiplication), / (division), and
% (modulus). Yet because there is no exponent printf("Line 2 - Value of c is %d\n", c );
operator in C, modulus cannot be applied with a
c = a * b;
floating point operand.
Addition and subtraction are similar, but unary printf("Line 3 - Value of c is %d\n", c );
(+) and unary (-) are distinct. Integer arithmetic is
used when both operands are integers, and the c = a / b;
outcome is always an integer. Floating arithmetic
printf("Line 4 - Value of c is %d\n", c );
is known when both operands are floating point,
and mixed type or mixed mode arithmetic is
c = a % b;
known when the operands are both integer and
floating point. The outcome is of the float type. printf("Line 5 - Value of c is %d\n", c );
Operator Description Example
Operator In C - Unit 5 31
The following outcome is produced by 3. Greater than operator: Represented
compiling and running the aforementioned as ‘>’, the greater than operator checks
program: whether the first operand is greater than
the second operand or not. If so, it returns
Line 1 - Value of c is 31
true. Otherwise, it returns false. For
Line 6 - Value of c is 21
5. Greater than or equal to
Operator In C - Unit 5 32
if (a > b) // not equal to
if (a >= b) return 0;
else Output:
printf("a is lesser than or equal to b\n"); two or more conditions or constraints, as well
as to improve the analysis of the initial condition
else being looked at. The result of a logical operation
printf("a is greater than b\n"); is a Boolean value that can be either true or false.
Operator In C - Unit 5 33
improve the analysis of the initial condition being printf("a is greater than b AND c is equal
taken into account. These are described below: to d\n");
Operator In C - Unit 5 34
is false. For example, because the first Output: Logical operator
operand of a logical AND is false, Program
• In the case of logical OR, the second
1 below does not output "Logical operator."
operand is not considered if the first
operand is true. For instance, program 1
#include <stdbool.h>
below doesn't print "Operator" because the
#include <stdio.h> first operand of the logical OR is true by
itself.
int main()
#include <stdbool.h>
{
#include <stdio.h>
} return 0;
Output: No Output }
logical AND is true, the program below But, because the first operand of the logical
prints "Logical Operator." OR is false, the following program produces
"GeeksQuiz."
#include <stdbool.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdio.h>
int main()
int main()
{
{
return 0; }
} Output: Operator
Operator In C - Unit 5 35
Bitwise Operators Operator Description Example
Binary AND Operator copies a (A & B) will give
& bit to the result if it exists in both 12, which is
Bit-level operations on the operands are operands. 0000 1100
(A | B) will give
carried out using the Bitwise operators. Prior to |
Binary OR Operator copies a bit if it
61, which is
exists in eigher operand.
performing the calculation on the operands, the 0011 1101
Binary XOR Operator copies the bit (A ^ B) will give
operators are translated to bit-level. For quicker ^ if it is set in one operand but not 49, which is
both. 0011 0001
processing, mathematical operations like Binary Ones Complement Operator (~A) will give
~ is unary and has the effect of -60, which is
addition, subtraction, multiplication, etc. can be
'flipping' bits. 1100 0011
carried out at the bit level. Binary left shift Operator. The left
A << 2 will give
operands value is moved left by
<< 240, which is
the number of bits specified by the
1111 0000
The following are the truth tables for &, |, and right operand.
Binary Right Shift Operator. The left
^: operands value is moved right by
A >> 2 will give
>> 15, which is
the number of bits specified by the
p q p&q p|q p^q 0000 1111
right operand.
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0 Example:
1 0 0 1 1
#include <stdio.h>
Assume if A = 60; and B = 13; now in binary
format they will be as follows: main()
A = 0011 1100
unsigned int b = 13; /* 13 = 0000 1101 */
B = 0000 1101
int c = 0;
-----------------
c = a & b; /* 12 = 0000 1100 */
~A = 1100 0011
c = a ^ b; /* 49 = 0011 0001 */
Operator In C - Unit 5 36
printf("Line 5 - Value of c is %d\n", c ); The simplest assignment operator is this one.
The variable on the left is given the value on the
c = a >> 2; /* 15 = 0000 1111 */
right using this operator.
}
a = 10;
Output:
b = 20;
Line 1 - Value of c is 12
ch = 'y';
Line 2 - Value of c is 61
b) “+=”
Line 3 - Value of c is 49
This operator is created by combining the
Line 4 - Value of c is -61 "+" and "=" operators. This operator assigns the
outcome to the left variable after first adding the
Line 5 - Value of c is 240 left variable's present value to the right variable's
value.
Line 6 - Value of c is 15
Example:
Assignment Operators
(a += b) can be written as (a = a + b)
A variable's value is assigned using assignment
operators. A variable serves as the assignment If initially value stored in a is 5. Then (a += 6)
operator's left side operand, and a value serves = 11.
as its right side operand. The variable on the left
must have the same data type as the value on c) “-=”
A variable's value is assigned using assignment the variable on the left after first subtracting the
operators. A variable serves as the assignment value on the right from the left's current value.
Operator In C - Unit 5 37
left variable, this operator multiplies the value of • Basically, the sizeof the operator is used to
the left variable by the value of the right variable. compute the size of the variable.
This operator is created by combining the '/' • The comma operator has the lowest
and '=' operators. This operator divides the value precedence of any C operator.
• sizeof is much used in the C programming d. dot (.) and arrow (->) Operators
language.
• Member operators are used to reference
• It is a compile-time unary operator which individual members of classes, structures,
can be used to compute the size of its and unions.
operand.
• The dot operator is applied to the actual
• The result of sizeof is of the unsigned object.
integral type which is usually denoted by
size_t. • The arrow operator is used with a pointer
to an object.
Operator In C - Unit 5 38
e. Cast Operator printf("The value of a - b is %d\n", a - b);
• Casting operators convert one data type printf("The value of a * b is %d\n", a * b);
to another. For example, int(2.2000) would
printf("The value of a / b is %d\n", a / b);
return 2.
• The most general cast supported by most a++); // First print (a) and then increment
of the C compilers is as follows − [ (type) it
expression ].
// by 1
f. &,* Operator
printf("The value of a-- is %d\n",
• Pointer operator & returns the address of
a variable. For example &a; will give the a--); // First print (a+1) and then decrease
actual address of the variable. it
Operator In C - Unit 5 39
"\nFollowing are the comparison operators in The value of a + b is 15
C\n");
The value of a - b is 5
printf("The value of a == b is %d\n", (a == b));
The value of a * b is 50
printf("The value of a != b is %d\n", (a != b));
The value of a / b is 2
printf("The value of a >= b is %d\n", (a >= b));
The value of a % b is 0
printf("The value of a <= b is %d\n", (a <= b));
The value of a++ is 10
printf("The value of a > b is %d\n", (a > b));
The value of a-- is 11
printf("The value of a < b is %d\n", (a < b));
The value of ++a is 11
// Logical operators
The value of --a is 10
printf("\nFollowing are the logical operators in
The comparison operators in C are listed
C\n");
below.
printf("The value of this logical and operator
The value of a == b is 0
((a==b) "
The value of a != b is 1
"&& (a<b)) is:%d\n",
printf("The value of this logical not operator " The value of this logical and operator ((a==b)
&& (a<b)) is:0
"(!(a==b)) is:%d\n",
Output: Summary
The C's arithmetic operators are listed here. • Operators are the foundation of any
Operator In C - Unit 5 40
programming language. We can define +(addition), -(subtraction), *(multiplication),
operators as symbols that help us to /(division), %(modulus).
perform specific mathematical and logical
• Logical Operators are used to combine
computations on operands. In other words,
two or more conditions/constraints or to
we can say that an operator operates the
complement the evaluation of the original
operands.
condition in consideration. The result of
• This operator used for numeric calculation. the operation of a logical operator is a
These are of either Unary arithmetic Boolean value either true or false.
operator, Binary arithmetic operator.
• The Bitwise operators are used to perform
• Where Unary arithmetic operator required bit-level operations on the operands. The
only one operand such as +,-, ++, --,!, operators are first converted to bit-level and
tiled. And these operators are addition, then the calculation is performed on the
operands. Mathematical operations such
subtraction, multiplication, division.
as addition, subtraction, multiplication, etc.
Binary arithmetic operator on other hand
can be performed at the bit level for faster
required two operand and its operators are
processing.
Operator In C - Unit 5 41
UNIT 6
Decision Making in C
Syntax
if(boolean_expression)
value of a is : 10
if...else statement
Syntax
Example:
if(boolean_expression)
#include <stdio.h>
{
int main ()
/* statement(s) will execute if the boolean
{
expression is true */
/* local variable definition */
}
int a = 110;
else
/* check the boolean condition using if
statement */ {
return 0;
Output:
else if(boolean_expression 1)
{ {
/* if condition is false then print the following /* Executes when the boolean expression 1
*/ is true */
{
}
} {
{ printf("Value of a is 30\n" );
}
/* executes when the none of the above
condition is true */ else
} {
int main () }
}
int a = 100;
following guidelines:
int main () }
case 'A':
break;
case 100:
• Automatic type conversions can occur
printf("This is part of outer switch\n", a ); when two expressions are compared that
the operands of a relational, equality, or
switch(b) { logical operator.
C Loops
while loop in C
We have learned from studying the for loop that the number of
iterations is known in advance, i.e., how many times the body of
the loop must be executed. While loops are employed when we are
unsure of the precise number of loop iterations in advance. Based on
the results of the test, the loop is stopped.
{ i++;
// statements }
update_expression; return 0;
} }
Output:
Hello India
Hello India
Hello India
Hello India
Hello India
for loop in C
With the use of a for loop, which is a repetition
control structure, we can create a loop that runs
a predetermined number of times. The loop
Figure: Flow Diagram.
permits us to carry out n stages simultaneously
Example: in a single line.
int main() {
int i = 1; }
C Loops - Unit 7 51
is accurate, the loop's body is executed, and the Example:
loop variable is changed. Continue until the exit
condition is met. // C program to illustrate for loop
{
• Test Expression: We must verify the
condition in this expression. If the condition
int i=0;
is true, we will carry out the for loop's body
and move on to the update expression; for (i = 1; i <= 10; i++)
otherwise, we will stop. For instance: i <=
10; {
Output:
Hello India
Hello India
Hello India
Hello India
Hello India
Hello India
Hello India
Hello India
Hello India
C Loops - Unit 7 52
do...while loop in C Example:
Syntax: do
initialization expression; {
do // loop body
update_expression; i++;
Output:
Hello India
nested loops in C
C Loops - Unit 7 53
There is no constraint on the number of loops // outer loop statements.
that can be formed, therefore any number of
}
loops can be defined inside another loop. It is
possible to define the nesting level n times. Any Example to showcase functionality of nested for
type of loop can be defined within of another loop
loop; for instance, a "while" loop can be defined
inside of a "for" loop. #include <stdio.h>
int main()
Syntax of Nested loop
{
Outer_loop
int n;// variable declaration
{
printf("Enter the value of n :");
Inner_loop
// Displaying the n tables.
{
for(int i=1;i<=n;i++) // outer loop
// inner loop statements.
{
}
for(int j=1;j<=10;j++) // inner loop
// outer loop statements.
{
}
printf("%d\t",(i*j)); // printing the value.
The legitimate loops that can be used as
}
"for" loops, "while" loops, or "do-while" loops are
outer_loop and inner_loop. printf("\n");
Every form of loop that is defined inside the Explanation of the above code
"for" loop is referred to as a "nested for loop."
• First, the 'i' variable is initialized to 1 and
for (initialization; condition; update) then program control passes to the i<=n.
C Loops - Unit 7 54
• After the execution of the inner loop, the {
control moves back to the update of the
int rows; // variable declaration
outer loop, i.e., i++.
int i=1;
#include <stdio.h> }
int main() }
C Loops - Unit 7 55
Explanation of the above code. {
******** */
int i=1;
do // outer loop
int j=1;
C Loops - Unit 7 56
}while(j<=8); 1. When a loop encounters the break
statement, the loop is instantly broken, and
printf("\n");
program control moves on to the statement
Syntax
break statement in C
C Loops - Unit 7 57
Example value of a: 13
{ continue statement in C
break;
return 0;
value of a: 10
value of a: 11 Example:
C Loops - Unit 7 58
int main () value of a: 18
{ value of a: 19
C Loops - Unit 7 59
UNIT 8
Functions
Function Definition
for (i = 2; i <= n; ++i) initiates the call to the function. For instance,
we can write to call the method three times.
product *= i;
for (i = 0; i < 3; ++i) wrt_address 0 ;
return product;
In a function definition, the type of the function
}
is listed first. If there is no value returned, the type
The first int instructs the compiler to convert is void. If the type is something other than void,
the function's return value to an int if necessary. the function will transform the value it returns,
The declaration int n is included in the argument if necessary, to this type. A list of parameter
list. This informs the compiler that the function declarations in parentheses is placed after the
only accepts a single int parameter. The function function's name. When the function is called,
is called when an expression like factorial (7) is the parameters serve as placeholders for the
used. The result is that the function definition's values that are supplied. In order to emphasise
code is executed, using the value 7 for n. that these arguments are placeholders, they
Functions thus serve as effective abbreviation are occasionally referred to as the formal
systems. Another illustration of a function parameters of the function. Declarations may
definition is as follows: also be found in the function's body, which is a
block or compound statement. These are some
Void wrt_address(void) illustrations of function definitions:
{ void nothing(void) { }
“ ************************** {
“ **************************) {
) int c;
Functions - Unit 8 61
A function's default type is int if the function It doesn't matter what order the parameters
type is not specified in the definition. The final are declared in. A pair of empty parenthesis
function definition, for instance, might be is used if there are no parameters. Both this
provided by conventional syntax and the more recent syntax
are supported by ANSI C compilers. As a result,
all_add(int a, int b) {
an ANSI C compiler can still build conventional
To clearly state the function type is acceptable code.
programming practice, nevertheless.
Writing programmes as collections of
A variable is said to be "local" to a function if it numerous functions is advantageous for a
is defined in the function's body. Other variables number of reasons. Writing a precise tiny
outside of the function can be defined. They are function that only performs one task is easier.
referred to as "global" variables. One of them is The authoring and debugging processes are
simplified. Also, such a grammar is simpler to
#include <stdio.h>
update or maintain. Just changing the necessary
int a = 33; /* a is external and initialized to 33 set of functions and assuming the rest of the
*/ code will function properly is possible. Little
functions are also frequently highly readable
int main(void)
and self-documenting. A smart programming
return 0;
return_statement ::= return; return expression;
}
Many instances are
In traditional C, the function definition has a
return;
different syntax. The variables in the parameter
list are declared immediately following the return ++a;
parameter list itself and just before the first
brace. One of them is return (a ,/, b);
Functions - Unit 8 62
environment additionally receives the value of getchar(); /* get a char, but do nothing with it
any expressions provided in the return statement. */
Also, based on the function's specification, this
c = getchar 0 ; /* c will be processed */
value will be modified as necessary to reflect the
function's type. ........
{ Function Prototypes
int i; Functions should be declared before use. The
function prototype, a new syntax for function
.........
definition, is provided by ANSI C. A function
return i; /*value returned will be converted to prototype tells the compiler how many and what
a float*/ kind of inputs to pass to the function, as well as
what kind of 0 result the function should return.
}
One of them is
return x;
void f(char c, int i); is equivalent to
Functions - Unit 8 63
When a function takes more than one argument, About the function's parameter list, nothing is
the ellipses (...) are utilised. Have a look at the assumed. Now imagine that the definition of the
printf() function prototype in the standard header following function comes first:
file stdio.h, for instance.
int f(x) /* traditional C style */
The compiler is able to undertake a more
thorough code inspection thanks to function double x;
Argument type lists are not supported in will fail. Now imagine that we use an ANSI C style
Functions - Unit 8 64
lifetime of a program thanks to these properties, that is initialised with a valid value where
which mainly include scope, visibility, and life- it is defined in order to be used elsewhere.
time. It is reachable from any block or function.
A normal global variable can also be
The four storage classes used by the C
made extern by prefixing its declaration
programming language are:
or definition with the term "extern" in any
Storage classes in C function or block. This simply means that
Storage we are only using/accessing the global
Storage Initial value Scope LIfe
Functions - Unit 8 65
the absence of a free registration, they are // printing the auto variable 'a'
just stored in memory. The register keyword
printf("Value of the variable 'a'"
is often used to declare a few variables
that a program will utilise repeatedly, which
" declared as auto: %d\n",
reduces the amount of time the program
will take to run. The fact that we cannot a);
use pointers to get the address of a register
printf("--------------------------------");
variable is both significant and intriguing in
this context.
}
// writing "int a=32;" works as well) // defined elsewhere (above the main
Functions - Unit 8 66
extern int x; " as in the case of variable 'p'\n");
x= 2; int p = 10;
} "iteration is %d\n",
Functions - Unit 8 67
{ Declaring 'y' as static inside the loop.
printf("A program to demonstrate" But this declaration will occur only once as 'y'
is static.
" Storage Classes in C\n\n");
If not, then every time the value of 'y' will be
// To demonstrate auto Storage Class
the declared value 5 as in the case of variable 'p'
autoStorageClass();
Loop started:
registerStorageClass(); iteration is 1
Functions - Unit 8 68
itself, and recursive calls are calls performed int fact(int n)
by recursive functions. Recursion involves a
{
large number of recursive calls. It is essential
to enforce a recursion termination condition as if (n==0)
a result. Recursive code is more cryptic than
{
iterative code, although being shorter.
return 0;
Recursion cannot be used for every problem,
but it is more beneficial for jobs that can be }
broken down into related subtasks. Recursion
else if ( n == 1)
can be used to solve sorting, searching, and
traversal issues, for instance. {
int main()
scanf("%d",&n);
f = fact(n);
printf("factorial = %d",f);
} Figure: Recursion.
Functions - Unit 8 69
Recursive Function int fibonacci(int);
#include<stdio.h>
Functions - Unit 8 70
Memory allocation of Recursive method return 0; // terminating condition
Functions - Unit 8 71
Summary tells the compiler the number and type of
arguments that are to be passed to the
• In C, the function construct is used to function and the type 0 the value that is to
implement this "top-down" method of
be returned by the function.
programming. A program consists of one
or more files, with each file containing zero • Storage Classes are used to describe the
or more functions, one of them being a features of a variable/function. These
main() function. Functions are defined as features basically include the scope,
individual objects that cannot be nested. visibility and life-time which help us to
Program execution begins with main(), trace the existence of a particular variable
which can call other functions, including during the runtime of a program.
library functions such as printf() and sqrt().
• Recursion is the process which comes into
• Functions operate with program variables, existence when a function calls a copy
and which of these variables is available of itself to work on a smaller problem.
at a particular place in a function is Any function which calls itself is called
determined by scope rules. recursive function, and such function
calls are called recursive calls. Recursion
• Functions should be declared before
involves several numbers of recursive
they are used. ANSI C provides for a new
function declaration syntax called the calls. However, it is important to impose a
Functions - Unit 8 72
UNIT 9
Structures
Like with any other data type, we must be able to declare variables
of that data type. Particularly for structures, we must specify the
names and types of all the structure's fields. As a result, we must
define variables of that type and specify the quantity and type of fields
in the form of a template in order to construct a structure.
We provide the following example: a program printf(“Temp in degree F =%3. If\n”,tenp.
that maintains temperatures in both fahrenheit ftemp);”
and celsius. The variable temp, which will be
used to maintain the same temperatures in both printf(“Temp in degree F =%3. If\n”,tenp.
struct trecd {
#include <stdio.h>
float ftemp;
Main()
float ctemp;
{ struct trecd{
} temp;
float ftemp;
struct {
part.id_no = 99;
char f_name[10];
part.cost = .2239;
char m_inits[3];
if (strcmp(person.f_name, "Helen") == 0)
char l_name[20];
printf("Last name is %s\n", person.l_name);
int id_no;
printf("This is the cost %d\n",part.cost);
int b_month;
part.price = part.cost * 2.0;
int b_day;
As long as the variables are of the same
}; int grade;
then declare stdtype structure variables like: the template from the declaration of variables
within the scope of the tag declaration. is that the template only needs to be declared
once and can then be used to declare variables
struct stdtype x, y, z; in several locations. When we pass structures to
function in the paragraphs below, we will realise
The three variables x, y, and z, all of which are
how useful this is.
of type structure stdtype and so fit the earlier
stated template, are allotted memory by this Hence, a structure declaration typically
declaration. Here are some more instances of includes the form shown below:
structure tags and variable declarations:
item struct [<tag_identifier>] {
/* named structure template, no variables
item struct [<tag_identifier>] {
declared */
<type_specifier> <identifier>;
struct date {
<type_specifier> <identifier>;
int month;
} [<identifier>[, <identifier>
int day;
where <tag identifiers> and the variable are both
int year;
optional. Further variables of the structure type
}; may be declared after the definition of a template
by:
/* named structure template and a variable
declared */ <tag_identifier> <identifier>[, <identifier>
} car;
struct inventory part = { 123, 10.00, 13.50 };
The month field of the variable car's ship date char street[30];
field and the month field of the variable car's
char city[15];
buy_date field, respectively, are the subjects of
these assignments. char state[15];
}; item = read_part( )
// gets value 1. The order of declaration is keyword is used to specify the union data type
and the struct keyword to specify a structure.
followed.
The data elements "a" and "b" that make up
struct Point p1 = {0, 1}; the union are identical when we examined the
addresses of the two variables. It suggests that
} each individual in the union has access to the
same region of memory.
Unions
Deciding the size of the union
A user-defined data type called a union is a
grouping of various variables of various data The largest member of the union determines
types stored in the same memory address. The the size of the union as a whole.
union can also be thought of as having numerous
members, but at any given time, only one of those Let's use an illustration to clarify.
members can hold a value.
union abc{
The user-defined data type union shares
int a;
the same memory address with structures, in
contrast. char b;
} int color;
the properties?
book.number_pages = 190;
return 0; };
} int main()
Input/Output
functions and functions prototypes When we say Input, it means to feed some data into a program. An
input can be given in the form of a file or from the command line. C
Discuss the output function
programming provides a set of built-in functions to read the given
printf()
input and feed it to the program as per requirement.
Describe the input function
scanf() 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
Explain the functions fprintf(),
output the data on the computer screen as well as to save it in text or
fscanf(), sprint(), and sscanf()
binary files.
Recognize the functions
fopen() and fclose() When completing calculations, you typically wish to display your
findings (sometimes known as "the answer") on the screen. The printf
function, which enables you to display messages on the computer
screen, is part of the standard input and output library, which is
installed by default on all computers with a C compiler. The line below
must be the first line in your program to access the standard input
and output library:
#include <stdio.h>
conversion character at the end. Your choice specification%f since the second value is of type
of converting character will depend on the kind float. Here is an example of the code's output
of content you want to see on the screen. The after compilation and execution:
Input/Output - Unit 10 86
Escape sequences, the second sort of letters \t and favourite), the result is the same
replacement, are used to display non-printing text with additional horizontal tabs and newlines:
and challenging-to-print characters. Certain
characters, like as newlines and tabs, generally My favorite
determine where text appears on the screen. The
numbers are 2 and 3.140000.
issue with some of these characters is that they
move the editor's cursor when you put them in The Input Function scanf()
your program when what you really want to do
is change how the text will be laid out after the Scan Formatted String is what the function
program is run. The following table lists a number scanf in the C programming language stands
of popular escape sequences together with the for. It receives information from the standard
corresponding special characters:
input stream (stdin), which is often the keyboard,
Special Character Escape Sequence and then writes the outcome into the specified
parameters.
alert (beep) \a
Input/Output - Unit 10 87
%f to accept input of real number. Return Values:
%c to accept input of character types. >0: The number of correctly assigned and
converted values.
%s to accept input of a string.
0: No value was assigned.
Three conversion characters are of a unique kind,
and one of them, [...], isn't even a character but is <0: Read error or end-of-file (EOF) reached
Why &?
scanf() conversion characters
Conversion Scanf has to save the input data somewhere
Remarks
character
while it scans the input. The memory location of
No characters in the input stream a variable must be known for scanf to be able
are matched. The corresponding
to store this input data. And now the ampersand
n argument is a pointer to an integer,
into which gets stored the number steps in to save the day.
of characters read so far.
• The operator's address is also referred to as &.
A single % character in the input
% stream is matched. There is no
• For instance, the address of var is &var.
corresponding argument.
Example: {
scanf(“%d”, &var);
printf("Enter first number: ");
Input/Output - Unit 10 88
scanf("%d", &b); The function prototypes for file handling functions
are given in stdio.h. Here are the prototypes for
printf("A : %d \t B : %d" , fprintf() and fscanf():
Input/Output - Unit 10 89
function writes to its first parameter, a reference input stream to read data from the keyboard and
to char (string). The rest of its arguments line up the standard output stream to display that data
with those for printf (). Instead of reading from on the screen. When a file is opened, a pointer
the keyboard, the function sscanf() reads from to a FILE structure (specified in) containing
its first parameter. The remainder of its inputs information about the file's size, type, current file
support scanf (). Think about the code. pointer location, and other specifics is returned.
This structure also includes a file descriptor, an
char str1[] :=: "1 2 3 go", str2[lee] , tmp[l00]; integer that acts as an index into the open file
table of the operating system. The operating
int a, b, c;
system employs a block in this table called a file
sscanf(str1, "%d%d%d%s", &a, &b, &c, control block (FCB) to handle each particular file.
tmp);
Standard input, standard output, and standard
sprintf(str2, "%s %s %d %d %d\n", tmp, error are controlled by the file pointers stdin,
tmp, a, b, c); stdout, and stderr. The group of operations that
we will now explain fall under the umbrella of the
printf ("%s", str2) buffered file system. Because the procedures
automatically maintain all the disc buffers
Strl is used as the function sscanf(input. )'s It
needed for reading and writing, this file system is
reads a string, three decimal integers, and puts
known as a buffered file system.
them in the appropriate places (a, b, c, and tmp).
The sprint() function writes to str2. To be more We must first declare a pointer to the FILE
explicit, it writes characters starting at address structure and then link it to the specific file in
str2 into memory. Two strings and three decimal order to access any file. The declaration of this
integers make up its output. We use printf() to pointer, which is known as a file pointer, is as
display the contents of str2. The screen displays follows:
the following text:
FILE *fp
go go 1 2 3
fopen()
The Functions fopen() and fclose()
The following action is to open a file after a file
A file is described as a sequence of consecutive pointer variable has been declared. The fopen()
bytes that has an end-of-file marker. When a file function creates a link between a file and a
is opened, the stream is connected to it. When stream and makes it available for use. A file
program execution begins, the standard input, pointer is returned by this function.
standard output, and standard error files and
The following is the syntax:
streams are automatically opened. Streams
provide a means of exchanging data between FILE *fopen(char *filename,*mode);
files and applications.
where mode is the intended open state as a string.
For instance, a program can use the standard The filename must be a string of characters that
Input/Output - Unit 10 90
gives the operating system a valid file name and A file pointer is the value that the fopen() function
may also include a path. The permissible values returns. This pointer's value is NULL, a constant
for the fopen() mode parameter are displayed in defined in, in the event that an error arises while
the table below. opening the file. Always keep an eye out for this
possibility, like in the case above.
Table: Legal values to the fopen() mode
parameter fclose()
"w+t" creates a text file for read and write access, The stream is terminated, any automatically
"a+t" opens or creates a text file and read access allocated buffers are released, any unwritten
"rb" opens a binary file for read only access data for the stream is flushed, any input that
"wb" create a binary file for write only access has been buffered but not yet read is discarded.
"ab" binary file for appending to a file The return value is a constant EOF, a file end-
"r+b" opens a binary or read and write access of-file marker, if an error occurred; otherwise, it
"w+b" creates a binary or read and write access, is 0. Furthermore, specifies this constant in. If
"a+b" open or binary file and read access the function fclose() is not explicitly used, the
operating system will normally close the file
How to open a file for reading is described in the when the program execution is complete.
following bit of code.
How to close a file is demonstrated in the
Code Fragment 1 following section of code.
#include <stdio.h>
# include <stdio.h>
main()
main()
{
{
FILE *fp;
FILE *fp;
if ((fp=fopen(“file1.dat”, “r”))==NULL)
if ((fp=fopen(“file1.dat”, “r”))==NULL)
{
{
printf(“FILE DOES NOT EXIST\n”);
} exit(0);
} }
Input/Output - Unit 10 91
…………….. • To open and close files, we use fopen() and
fclose(), respectively. After a file has been
……………..
opened, the file pointer is used to refer to
Input/Output - Unit 10 92
UNIT 11
FD PURPOSE
0 Standard input
1 Standard output
3 Standard error
In file change_case.c
int in_fd, out_fd, n; The first input to open() is a file name, and the
second one specifies how to open the. If there are
in_fd = open(argv[lJ, O_RDONLY);
no issues, the function returns a file descriptor;
out_fd = open(argv[2] , O_WRONLY I O_ otherwise, it returns the value -1. The mnemonic
EXCL | 0_CREAT, 0600; "in fd" stands for "in file descriptor." The cntl.h
file presents the symbolic constant O RDONL
while ((n = read(in_fd, mybuf, BUFSIZE))
Y, which works with both MS-DOS and UNIX
> 0) {
platforms. As a mnemonic, it denotes "available
for (p = mybuf; p mybuf < n; ++p) for reading only."
body of the loop, the letters in mybuf are changed rwx 111 07
rw------- 0600
The two files are then closed. The system
rw----r-- 0604
will close the files upon program exit if the
rwxr-xr-x 0755
programmer has not expressly instructed it to do rwxrwxrwx 0777
so.
The rights rwxr-xr-x signify that the owner, the
File Access Permissions
group, and others may all read and execute the
In UNIX, a file is created with the appropriate file. They also signify that the owner can read,
access permissions. The permissions govern write, and execute the file. The Is -1 command
who has access to a file, including the owner, the in UNIX displays the mnemonic file access
group, and other users. It is possible to combine permissions. File permissions are available in
read, write, execute, or none of these access MS-DOS, but only for everyone.
capabilities. When a file is created by calling
Executing Commands from Within a C
open 0, the third parameter can be a three-
Program
digit octal integer to set the permissions. Each
octal digit controls the read, write, and execute Access to operating system commands is
permissions. A user's permissions are controlled provided via the library function system(). The
by the first octal digit, a group's permissions are command date causes the current date to be
controlled by the second octal digit, and others' printed on the screen in both MS-DOS and UNIX.
permissions are controlled by the third octal From within a program, we can write code to
digit. (Everyone is included in "others"). print this information on the screen.
return 0; printf("%s%s\n%s%s\n%s%s\n%s%s\n",
SHELL=/bin/csh
The C Compiler
TERM=vt102
There are numerous C compilers, and any number
USER=blufox of them may be offered by an operating system.
Just a few of the options are listed below:
The environment variable is to the left of the
equal sign, and its value, which should be viewed Command The C compiler that gets invoked
as a string, is to the right of the equal sign. This cc The system supplied native C compiler
software prints on our MS-DOS machine. An early version of an ANSI C compiler from Sun
acc
Microsystems
COMSPEC=C:\COMMAND.COM bc Borland C/C++ compiler, integrated environment
Whatever is in a.out will be overwritten by the -I dir Look for #include files in the directory dir.
produce an executable file. Imagine, for instance, is offered by several operating systems. The
program is known as the archiver in UNIX and
that main.c contains a mistake. After fixing the
is accessed using the ar command. This tool,
error in main.c, we may issue the command.
known as the librarian in the Ms-DOS universe,
cc -0 pgm main.c file 7.0 file2.0 is an add-on function. For instance, the Turbo C
librarian is tUb, whereas the Microsoft librarian is
Using .0 files instead of.e files speeds up
lib. By convention, files in a library end in.a in UNIX
compilation,
and.lib in MS-DOS. The topic will be discussed in
The title, or name, of each file in the library is if ((p = calloc(n, sizeof_something))
NULL) {
displayed using the key t. More than you care to
look at exist. You can use the command to count fprintf(stderr, "\nERROR: ca11ocO failed -
them. bye.\n\n");
type& identifier
The default settings for C++ function arguments are also an option.
They are provided in the parameter list by the function declaration.
= expression
In file add3.cpp
#include <iostream.h>
The implementation of a class type may be endl; // Print shorter of one and two.
~ClassName() int a = 1;
{ if(a==1)
//Destructor's Body {
support s;
a/b // divide behavior determined by
students could be included in the student-grad_ a prerequisite for the C method for constructing
{ public:
case CIRCLE: return (PI * s -> radius * s -> rectangle(double h, double w): height(h),
radius); width(w) {}
case RECTANGLE: return (s -> height*S -> double area() { return (height * width);} //
width); overridden
} private: