KEMBAR78
Introduction to C programming language. Coding | PPTX
UNIT- I
C Variables
๏‚— Variables are containers for storing data values, like
numbers and characters.
๏‚— In C, there are different types of variables (defined with
different keywords), for example:
๏‚— int - stores integers (whole numbers), without decimals,
such as 123 or -123
๏‚— float - stores floating point numbers, with decimals, such
as 19.99 or -19.99
๏‚— char - stores single characters, such as 'a' or 'B'. Char values
are surrounded by single quotes
๏‚—
Declaring (Creating) Variables
๏‚— To create a variable, specify the type and assign it a value:
๏‚— Syntax
๏‚— type variableName = value;
๏‚— Where type is one of C types (such as int), and variableName is the name of the variable
(such as x or myName). The equal sign is used to assign a value to the variable.
๏‚— So, to create a variable that should store a number, look at the following example:
๏‚— Example
๏‚— Create a variable called myNum of type int and assign the value 15 to it:
๏‚— int myNum = 15;
๏‚— You can also declare a variable without assigning the value, and assign the value later:
๏‚— Example
๏‚— // Declare a variable
int myNum;
// Assign a value to the variable
myNum = 15;
C Format Specifiers
๏‚— Format specifiers are used together with
the printf() function to tell the compiler what type of data
the variable is storing. It is basically a placeholder for the
variable value.
๏‚— A format specifier starts with a percentage sign %, followed
by a character.
๏‚— For example, to output the value of an int variable, use the
format specifier %d surrounded by double quotes (""),
inside the printf() function:
๏‚— Example
๏‚— int myNum = 15;
printf("%d", myNum); // Outputs 15
๏‚— To print other types, use %c for char and %f for float:
Example
๏‚— // Create variables
int myNum = 15; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
char myLetter = 'D'; // Character
// Print variables
printf("%dn", myNum);
printf("%fn", myFloatNum);
printf("%cn", myLetter);
๏‚— To combine both text and a variable, separate them with a
comma inside the printf() function:
๏‚— Example
๏‚— int myNum = 15;
printf("My favorite number is: %d", myNum);
๏‚— To print different types in a single printf() function,
you can use the following:
๏‚— Example
๏‚— int myNum = 15;
char myLetter = 'D';
printf("My number is %d and my letter is %c",
myNum, myLetter);
Change Variable Values
๏‚— If you assign a new value to an existing variable, it
will overwrite the previous value:
๏‚— Example
๏‚— int myNum = 15; // myNum is 15
myNum = 10; // Now myNum is 10
You can also assign the value of
one variable to another
๏‚— int myNum = 15;
int myOtherNum = 23;
// Assign the value of myOtherNum (23) to myNum
myNum = myOtherNum;
// myNum is now 23, instead of 15
printf("%d", myNum);
๏‚— Try it Yourself ยป
๏‚—
copy values to empty variables
๏‚— Example
๏‚— // Create a variable and assign the value 15 to it
int myNum = 15;
// Declare a variable without assigning it a value
int myOtherNum;
// Assign the value of myNum to myOtherNum
myOtherNum = myNum;
// myOtherNum now has 15 as a value
printf("%d", myOtherNum);
Add Variables Together
๏‚— To add a variable to another variable, you can use
the + operator:
๏‚— Example
๏‚— int x = 5;
int y = 6;
int sum = x + y;
printf("%d", sum);
Exercise:
๏‚— Display the sum of 5 + 10, using two variables: x and y.
๏‚— --- --- = --- ;
๏‚— int y = 10;
๏‚— printf("%d", x + y);
C Declare Multiple Variables
๏‚— Declare Multiple Variables
๏‚— To declare more than one variable of the same type,
use a comma-separated list:
๏‚— Example
๏‚— int x = 5, y = 6, z = 50;
printf("%d", x + y + z);
๏‚— You can also assign the same value to multiple
variables of the same type:
๏‚— Example
๏‚— int x, y, z;
x = y = z = 50;
printf("%d", x + y + z);
C Variable Names (Identifiers)
๏‚— All C variables must be identified with unique names.
๏‚— These unique names are called identifiers.
๏‚— Identifiers can be short names (like x and y) or more
descriptive names (age, sum, totalVolume).
๏‚— Note: It is recommended to use descriptive names in order
to create understandable and maintainable code:
๏‚— Example
๏‚— // Good variable name
int minutesPerHour = 60;
// OK, but not so easy to understand what m actually is
int m = 60;
The general rules for naming
variables are
๏‚— The general rules for naming variables are:
๏‚— Names can contain letters, digits and underscores
๏‚— Names must begin with a letter or an underscore (_)
๏‚— Names are case sensitive (myVar and myvar are
different variables)
๏‚— Names cannot contain whitespaces or special
characters like !, #, %, etc.
๏‚— Reserved words (such as int) cannot be used as names
๏‚—
Real life example
๏‚— // Create integer variables
int length = 4;
int width = 6;
int area;
// Calculate the area of a rectangle
area = length * width;
// Print the variables
printf("Length is: %dn", length);
printf("Width is: %dn", width);
printf("Area of the rectangle is: %d", area);
๏‚— As explained in the Variables chapter, a variable in C must
be a specified data type, and you must use a format
specifier inside the printf() function to display it:
๏‚— Example
๏‚— // Create variables
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
char myLetter = 'D'; // Character
// Print variables
printf("%dn", myNum);
printf("%fn", myFloatNum);
printf("%cn", myLetter);
C Decimal Precision
๏‚— Set Decimal Precision
๏‚— You have probably already noticed that if you print a
floating point number, the output will show many
digits after the decimal point:
๏‚— Example
๏‚— float myFloatNum = 3.5;
double myDoubleNum = 19.99;
printf("%fn", myFloatNum); // Outputs 3.500000
printf("%lf", myDoubleNum); // Outputs 19.990000
๏‚— If you want to remove the extra zeros (set decimal
precision), you can use a dot (.) followed by a number that
specifies how many digits that should be shown after the
decimal point:
๏‚— Example
๏‚— float myFloatNum = 3.5;
printf("%fn", myFloatNum); // Default will show 6 digits
after the decimal point
printf("%.1fn", myFloatNum); // Only show 1 digit
printf("%.2fn", myFloatNum); // Only show 2 digits
printf("%.4f", myFloatNum); // Only show 4 digits
๏‚— Try it Yourself ยป
๏‚—
C Operators
๏‚— C divides the operators into the following groups:
๏‚— Arithmetic operators
๏‚— Assignment operators
๏‚— Comparison operators
๏‚— Logical operators
๏‚— Bitwise operators
Arithmetic operators
Operato
r
Name Description Example
+ Addition Adds together two values x + y
- Subtraction Subtracts one value from
another
x - y
* Multiplicatio
n
Multiplies two values x * y
/ Division Divides one value by another x / y
% Modulus Returns the division
remainder
x % y
++ Increment Increases the value of a
variable by 1
++x
-- Decrement Decreases the value of a
variable by 1
--x
Assignment Operators
๏‚— Assignment operators are used to assign values to variables.
๏‚— In the example below, we use the assignment operator (=)
to assign the value 10 to a variable called x:
๏‚— Example
๏‚— int x = 10;
๏‚— Assignment operators are used to assign values to variables.
๏‚— In the example below, we use the assignment operator (=)
to assign the value 10 to a variable called x:
๏‚— Example
๏‚— int x = 10;
A list of all assignment operators
Operator Example Same As
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
Comparison Operators
๏‚— Comparison operators are used to compare two values (or
variables). This is important in programming, because it helps us
to find answers and make decisions.
๏‚— The return value of a comparison is either 1 or 0, which
means true (1) or false (0). These values are known as Boolean
values, and you will learn more about them in
the Booleans and If..Else chapter.
๏‚— In the following example, we use the greater than operator (>)
to find out if 5 is greater than 3:
๏‚— Example
๏‚— int x = 5;
int y = 3;
printf("%d", x > y); // returns 1 (true) because 5 is greater than 3
A list of all comparison operators
Operator Name Example Description Try it
== Equal to x == y Returns 1 if the values are
equal
Try it ยป
!= Not equal x != y Returns 1 if the values are
not equal
Try it ยป
> Greater than x > y Returns 1 if the first value is
greater than the second
value
Try it ยป
< Less than x < y Returns 1 if the first value is
less than the second value
Try it ยป
>= Greater than or
equal to
x >= y Returns 1 if the first value is
greater than, or equal to, the
second value
Try it ยป
<= Less than or
equal to
x <= y Returns 1 if the first value is
less than, or equal to, the
second value
Try it ยป
Logical Operators
๏‚— You can also test for true or false values with
logical operators.
๏‚— Logical operators are used to determine the logic
between variables or values:
Operator Name Example Description
&& Logical
and
x < 5 && x < 10 Returns 1 if both
statements are true
|| Logical or x < 5 || x < 4 Returns 1 if one of the
statements is true
! Logical not !(x < 5 && x <
10)
Reverse the result, returns
0 if the result is 1
Sizeof Operator
๏‚— The memory size (in bytes) of a data type or a variable
can be found with the sizeof operator:
๏‚— int myInt;
float myFloat;
double myDouble;
char myChar;
printf("%lun", sizeof(myInt));
printf("%lun", sizeof(myFloat));
printf("%lun", sizeof(myDouble));
printf("%lun", sizeof(myChar));
๏‚— Note that we use the %lu format specifer to print the
result, instead of %d. It is because the compiler
expects the sizeof operator to return a long unsigned
int (%lu), instead of int (%d). On some computers it
might work with %d, but it is safer to use %lu.
๏‚— Why Should I Know the Size of Data Types?
๏‚— Using the right data type for the right purpose will save
memory and improve the performance of your
program.
๏‚— You will learn more about the sizeof operator later in
this tutorial, and how to use it in different scenarios.
Boolean Variables
๏‚— In C, the bool type is not a built-in data type, like int or char.
๏‚— It was introduced in C99, and you must import the following
header file to use it:
๏‚— #include <stdbool.h>
๏‚— A boolean variable is declared with the bool keyword and can
only take the values true or false:
๏‚— bool isProgrammingFun = true;
bool isFishTasty = false;
๏‚— Before trying to print the boolean variables, you should know
that boolean values are returned as integers:
๏‚— 1 (or any other number that is not 0) represents true
๏‚— 0 represents false
๏‚— Therefore, you must use the %d format specifier to print a
boolean value:
Comparing Values and Variables
๏‚— Comparing values are useful in programming, because it helps us
to find answers and make decisions.
๏‚— For example, you can use a comparison operator, such as
the greater than (>) operator, to compare two values:
๏‚— Example
๏‚— printf("%d", 10 > 9); // Returns 1 (true) because 10 is greater
than 9
From the example above, you can see that the return value is a
boolean value (1).
๏‚— You can also compare two variables:
๏‚— Example
๏‚— int x = 10;
int y = 9;
printf("%d", x > y);
๏‚— In the example below, we use the equal to (==) operator to
compare different values:
๏‚— Example
๏‚— printf("%d", 10 == 10); // Returns 1 (true),
๏‚— because 10 is equal to 10
printf("%d", 10 == 15); // Returns 0 (false),
๏‚— because 10 is not equal to 15
printf("%d", 5 == 55); // Returns 0 (false)
๏‚— because 5 is not equal to 55
๏‚— You are not limited to only compare numbers. You can also
compare boolean variables, or even special structures,
like arrays (which you will learn more about in a later chapter):
๏‚— Example
๏‚— bool isHamburgerTasty = true;
bool isPizzaTasty = true;
// Find out if both hamburger and pizza is tasty
printf("%d", isHamburgerTasty == isPizzaTasty);
Real Life Example
๏‚— Let's think of a "real life example" where we
need to find out if a person is old enough to
vote.
๏‚— In the example below, we use
the >= comparison operator to find out if the
age (25) is greater than OR equal to the
voting age limit, which is set to 18:
๏‚— Example
๏‚— int myAge = 25;
int votingAge = 18;
printf("%d", myAge >= votingAge); //
Returns 1 (true), meaning 25 year olds are
allowed to vote!
๏‚— Output "Old enough to vote!" if myAge is greater
than or equal to 18. Otherwise output "Not old
enough to vote.":
๏‚— int myAge = 25;
int votingAge = 18;
if (myAge >= votingAge) {
printf("Old enough to vote!");
} else {
printf("Not old enough to vote.");
Formatted I/O Functions
๏‚— Formatted I/O functions are used to take various
inputs from the user and display multiple outputs to
the user.
๏‚— These types of I/O functions can help to display the
output to the user in different formats using the
format specifiers.
๏‚— These I/O supports all data types like int, float, char,
and many more.
๏‚— Why they are called formatted I/O?
๏‚— These functions are called formatted I/O functions
because we can use format specifiers in these
functions and hence, we can format these functions
according to our needs.
๏‚— printf()
๏‚— scanf()
Example
๏‚— #include <stdio.h>
๏‚—
๏‚— int main()
๏‚— {
๏‚— int num1;
๏‚—
๏‚— // Printing a message on
๏‚— // the output screen
๏‚— printf("Enter a integer number: ");
๏‚—
๏‚— // Taking an integer value
๏‚— // from keyboard
๏‚— scanf("%d", &num1);
๏‚—
๏‚— // Displaying the entered value
๏‚— printf("You have entered %d", num1);
๏‚—
๏‚— return 0;
๏‚— }
Unformatted Input / Output
functions
๏‚— Unformatted I/O functions are used only for character
data type or character array/string and cannot be used
for any other datatype.
๏‚— These functions are used to read single input from the
user at the console and it allows to display the value at
the console.
๏‚— Why they are called unformatted I/O?
๏‚— These functions are called unformatted I/O functions
because we cannot use format specifiers in these
functions and hence, cannot format these functions
according to our needs.
๏‚— The following unformatted I/O functions will be
discussed in this section-
๏‚— getch()
๏‚— getche()
๏‚— getchar()
๏‚— putchar()
๏‚— gets()
๏‚— puts()
๏‚— putch()
๏‚— getch():
๏‚— getch() function reads a single character from the
keyboard by the user but doesnโ€™t display that character
on the console screen and immediately returned
without pressing enter key.
๏‚— This function is declared in conio.h
๏‚— (header file). getch() is also used for hold the screen.
๏‚— Syntax:
๏‚— getch();
๏‚— getche():
๏‚— getche() function reads a single character from the
keyboard by the user and displays it on the console
screen and immediately returns without pressing the
enter key. This function is declared in conio.h(header
file).
๏‚— Syntax:
๏‚— getche();
๏‚— or
๏‚— variable_name = getche();
// C program to implement
// the getchar() function
#include <conio.h>
#include <stdio.h>
// Driver code
int main()
{
// Declaring a char type variable
char ch;
printf("Enter the character: ");
// Taking a character from keyboard
ch = getchar();
// Displays the value of ch
printf("%c", ch);
return 0;
}
๏‚— putchar():
๏‚— The putchar() function is used to display a single
character at a time by passing that character directly to
it or by passing a variable that has already stored a
character. This function is declared in stdio.h(header
file)
๏‚— Syntax:
๏‚— putchar(variable_name);
๏‚— // C program to implement
๏‚— // the putchar() function
๏‚— #include <conio.h>
๏‚— #include <stdio.h>
๏‚—
๏‚— // Driver code
๏‚— int main()
๏‚— {
๏‚— char ch;
๏‚— printf("Enter any character: ");
๏‚—
๏‚— // Reads a character
๏‚— ch = getchar();
๏‚—
๏‚— // Displays that character
๏‚— putchar(ch);
๏‚— return 0;
๏‚— }
gets():
๏‚— gets() function reads a group of characters or strings
from the keyboard by the user and these characters get
stored in a character array. This function allows us to
write space-separated texts or strings. This function is
declared in stdio.h(header file).
๏‚— / C program to implement
๏‚— // the gets() function
๏‚— #include <conio.h>
๏‚— #include <stdio.h>
๏‚—
๏‚— // Driver code
๏‚— int main()
๏‚— {
๏‚— // Declaring a char type array
๏‚— // of length 50 characters
๏‚— char name[50];
๏‚—
๏‚— printf("Please enter some texts: ");
๏‚—
๏‚— // Reading a line of character or
๏‚— // a string
๏‚— gets(name);
๏‚—
๏‚— // Displaying this line of character
๏‚— // or a string
๏‚— printf("You have entered: %s", name);
๏‚— return 0;
๏‚— }
puts():
๏‚— In C programming puts() function is used to display a
group of characters or strings which is already stored
in a character array. This function is declared in
stdio.h(header file).
๏‚— // C program to implement
๏‚— // the puts() function
๏‚— #include <stdio.h>
๏‚—
๏‚— // Driver code
๏‚— int main()
๏‚— {
๏‚— char name[50];
๏‚— printf("Enter your text: ");
๏‚—
๏‚— // Reads string from user
๏‚— gets(name);
๏‚—
๏‚— printf("Your text is: ");
๏‚—
๏‚— // Displays string
๏‚— puts(name);
๏‚—
๏‚— return 0;
๏‚— }
putch():
๏‚— putch() function is used to display a single character
which is given by the user and that character prints at
the current cursor location.
๏‚— This function is declared in conio.h(header file)
๏‚— Syntax:
๏‚— putch(variable_name);
๏‚— // C program to implement
๏‚— // the putch() functions
๏‚— #include <conio.h>
๏‚— #include <stdio.h>
๏‚—
๏‚— // Driver code
๏‚— int main()
๏‚— {
๏‚— char ch;
๏‚— printf("Enter any character: n ");
๏‚—
๏‚— // Reads a character from the keyboard
๏‚— ch = getch();
๏‚—
๏‚— printf("nEntered character is: ");
๏‚—
๏‚— // Displays that character on the console
๏‚— putch(ch);
๏‚— return 0;
๏‚— }
S No.
Formatted I/O
functions
Unformatted I/O
functions
1
These functions allow us to
take input or display output in
the userโ€™s desired format.
These functions do not allow to take
input or display output in user desired
format.
2
These functions support
format specifiers.
These functions do not support
format specifiers.
3
These are used for storing
data more user friendly
These functions are not more user-
friendly.
4
Here, we can use all data
types.
Here, we can use only character and
string data types.
5
printf(), scanf, sprintf() and
sscanf() are examples of these
functions.
getch(), getche(), gets() and puts(),
are some examples of these functions.
Algorithm
๏‚— A set of instructions for resolving an issue or carrying
out a certain activity.
๏‚— In computer science, algorithms are used for a wide
range of operations, from fundamental math to
intricate data processing.
๏‚— It defines several important features of the algorithm,
including:
๏‚—
important features
๏‚— Inputs: Algorithms must receive inputs that can be represented as values or
data.
๏‚— Output: The algorithm should produce some output. It can be a consequence
of a problem or a solution designed to solve it.
๏‚— Clarity: Algorithms must be precisely defined, using unambiguous
instructions that a computer or other system can follow unambiguously.
๏‚— Finiteness: The algorithm requires a limited steps. It means that it should be
exited after executing a certain number of commands.
๏‚— Validity: The algorithm must be valid. In other words, it should be able to
produce a solution to the problem that the algorithm is designed to solve in a
reasonable amount of time.
๏‚— Effectiveness: An algorithm must be effective, meaning that it must be able to
produce a solution to the problem it is designed to solve in a reasonable
amount of time.
๏‚— Generality: An algorithm must be general, meaning that it can be applied to a
wide range of problems rather than being specific to a single problem.
C - Type Casting
๏‚— Converting one datatype into another is known as type
casting or, type-conversion.
๏‚— For example, if you want to store a 'long' value into a
simple integer then you can type cast 'long' to 'int'. You
can convert the values from one type to another
explicitly using the cast operator as follows โˆ’
๏‚— (type_name) expression
๏‚— Consider the following example where the cast
operator causes the division of one integer variable by
another to be performed as a floating-point operation
โˆ’
๏‚— #include <stdio.h>
๏‚— Int main()
๏‚— {
๏‚— int sum = 17, count = 5;
๏‚— double mean;
๏‚— mean = (double) sum / count;
๏‚— printf("Value of mean : %fn", mean );
๏‚— }
Usual Arithmetic Conversion
Introduction to C programming language. Coding

Introduction to C programming language. Coding

  • 1.
  • 2.
    C Variables ๏‚— Variablesare containers for storing data values, like numbers and characters. ๏‚— In C, there are different types of variables (defined with different keywords), for example: ๏‚— int - stores integers (whole numbers), without decimals, such as 123 or -123 ๏‚— float - stores floating point numbers, with decimals, such as 19.99 or -19.99 ๏‚— char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes ๏‚—
  • 3.
    Declaring (Creating) Variables ๏‚—To create a variable, specify the type and assign it a value: ๏‚— Syntax ๏‚— type variableName = value; ๏‚— Where type is one of C types (such as int), and variableName is the name of the variable (such as x or myName). The equal sign is used to assign a value to the variable. ๏‚— So, to create a variable that should store a number, look at the following example: ๏‚— Example ๏‚— Create a variable called myNum of type int and assign the value 15 to it: ๏‚— int myNum = 15; ๏‚— You can also declare a variable without assigning the value, and assign the value later: ๏‚— Example ๏‚— // Declare a variable int myNum; // Assign a value to the variable myNum = 15;
  • 4.
    C Format Specifiers ๏‚—Format specifiers are used together with the printf() function to tell the compiler what type of data the variable is storing. It is basically a placeholder for the variable value. ๏‚— A format specifier starts with a percentage sign %, followed by a character. ๏‚— For example, to output the value of an int variable, use the format specifier %d surrounded by double quotes (""), inside the printf() function: ๏‚— Example ๏‚— int myNum = 15; printf("%d", myNum); // Outputs 15 ๏‚— To print other types, use %c for char and %f for float:
  • 5.
    Example ๏‚— // Createvariables int myNum = 15; // Integer (whole number) float myFloatNum = 5.99; // Floating point number char myLetter = 'D'; // Character // Print variables printf("%dn", myNum); printf("%fn", myFloatNum); printf("%cn", myLetter); ๏‚— To combine both text and a variable, separate them with a comma inside the printf() function: ๏‚— Example ๏‚— int myNum = 15; printf("My favorite number is: %d", myNum);
  • 6.
    ๏‚— To printdifferent types in a single printf() function, you can use the following: ๏‚— Example ๏‚— int myNum = 15; char myLetter = 'D'; printf("My number is %d and my letter is %c", myNum, myLetter);
  • 7.
    Change Variable Values ๏‚—If you assign a new value to an existing variable, it will overwrite the previous value: ๏‚— Example ๏‚— int myNum = 15; // myNum is 15 myNum = 10; // Now myNum is 10
  • 8.
    You can alsoassign the value of one variable to another ๏‚— int myNum = 15; int myOtherNum = 23; // Assign the value of myOtherNum (23) to myNum myNum = myOtherNum; // myNum is now 23, instead of 15 printf("%d", myNum); ๏‚— Try it Yourself ยป ๏‚—
  • 9.
    copy values toempty variables ๏‚— Example ๏‚— // Create a variable and assign the value 15 to it int myNum = 15; // Declare a variable without assigning it a value int myOtherNum; // Assign the value of myNum to myOtherNum myOtherNum = myNum; // myOtherNum now has 15 as a value printf("%d", myOtherNum);
  • 10.
    Add Variables Together ๏‚—To add a variable to another variable, you can use the + operator: ๏‚— Example ๏‚— int x = 5; int y = 6; int sum = x + y; printf("%d", sum);
  • 11.
    Exercise: ๏‚— Display thesum of 5 + 10, using two variables: x and y. ๏‚— --- --- = --- ; ๏‚— int y = 10; ๏‚— printf("%d", x + y);
  • 12.
    C Declare MultipleVariables ๏‚— Declare Multiple Variables ๏‚— To declare more than one variable of the same type, use a comma-separated list: ๏‚— Example ๏‚— int x = 5, y = 6, z = 50; printf("%d", x + y + z); ๏‚— You can also assign the same value to multiple variables of the same type: ๏‚— Example ๏‚— int x, y, z; x = y = z = 50; printf("%d", x + y + z);
  • 13.
    C Variable Names(Identifiers) ๏‚— All C variables must be identified with unique names. ๏‚— These unique names are called identifiers. ๏‚— Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume). ๏‚— Note: It is recommended to use descriptive names in order to create understandable and maintainable code: ๏‚— Example ๏‚— // Good variable name int minutesPerHour = 60; // OK, but not so easy to understand what m actually is int m = 60;
  • 14.
    The general rulesfor naming variables are ๏‚— The general rules for naming variables are: ๏‚— Names can contain letters, digits and underscores ๏‚— Names must begin with a letter or an underscore (_) ๏‚— Names are case sensitive (myVar and myvar are different variables) ๏‚— Names cannot contain whitespaces or special characters like !, #, %, etc. ๏‚— Reserved words (such as int) cannot be used as names ๏‚—
  • 15.
    Real life example ๏‚—// Create integer variables int length = 4; int width = 6; int area; // Calculate the area of a rectangle area = length * width; // Print the variables printf("Length is: %dn", length); printf("Width is: %dn", width); printf("Area of the rectangle is: %d", area);
  • 16.
    ๏‚— As explainedin the Variables chapter, a variable in C must be a specified data type, and you must use a format specifier inside the printf() function to display it: ๏‚— Example ๏‚— // Create variables int myNum = 5; // Integer (whole number) float myFloatNum = 5.99; // Floating point number char myLetter = 'D'; // Character // Print variables printf("%dn", myNum); printf("%fn", myFloatNum); printf("%cn", myLetter);
  • 17.
    C Decimal Precision ๏‚—Set Decimal Precision ๏‚— You have probably already noticed that if you print a floating point number, the output will show many digits after the decimal point: ๏‚— Example ๏‚— float myFloatNum = 3.5; double myDoubleNum = 19.99; printf("%fn", myFloatNum); // Outputs 3.500000 printf("%lf", myDoubleNum); // Outputs 19.990000
  • 18.
    ๏‚— If youwant to remove the extra zeros (set decimal precision), you can use a dot (.) followed by a number that specifies how many digits that should be shown after the decimal point: ๏‚— Example ๏‚— float myFloatNum = 3.5; printf("%fn", myFloatNum); // Default will show 6 digits after the decimal point printf("%.1fn", myFloatNum); // Only show 1 digit printf("%.2fn", myFloatNum); // Only show 2 digits printf("%.4f", myFloatNum); // Only show 4 digits ๏‚— Try it Yourself ยป ๏‚—
  • 19.
    C Operators ๏‚— Cdivides the operators into the following groups: ๏‚— Arithmetic operators ๏‚— Assignment operators ๏‚— Comparison operators ๏‚— Logical operators ๏‚— Bitwise operators
  • 20.
    Arithmetic operators Operato r Name DescriptionExample + Addition Adds together two values x + y - Subtraction Subtracts one value from another x - y * Multiplicatio n Multiplies two values x * y / Division Divides one value by another x / y % Modulus Returns the division remainder x % y ++ Increment Increases the value of a variable by 1 ++x -- Decrement Decreases the value of a variable by 1 --x
  • 21.
    Assignment Operators ๏‚— Assignmentoperators are used to assign values to variables. ๏‚— In the example below, we use the assignment operator (=) to assign the value 10 to a variable called x: ๏‚— Example ๏‚— int x = 10; ๏‚— Assignment operators are used to assign values to variables. ๏‚— In the example below, we use the assignment operator (=) to assign the value 10 to a variable called x: ๏‚— Example ๏‚— int x = 10;
  • 22.
    A list ofall assignment operators Operator Example Same As = x = 5 x = 5 += x += 3 x = x + 3 -= x -= 3 x = x - 3 *= x *= 3 x = x * 3 /= x /= 3 x = x / 3 %= x %= 3 x = x % 3 &= x &= 3 x = x & 3 |= x |= 3 x = x | 3 ^= x ^= 3 x = x ^ 3 >>= x >>= 3 x = x >> 3 <<= x <<= 3 x = x << 3
  • 23.
    Comparison Operators ๏‚— Comparisonoperators are used to compare two values (or variables). This is important in programming, because it helps us to find answers and make decisions. ๏‚— The return value of a comparison is either 1 or 0, which means true (1) or false (0). These values are known as Boolean values, and you will learn more about them in the Booleans and If..Else chapter. ๏‚— In the following example, we use the greater than operator (>) to find out if 5 is greater than 3: ๏‚— Example ๏‚— int x = 5; int y = 3; printf("%d", x > y); // returns 1 (true) because 5 is greater than 3
  • 24.
    A list ofall comparison operators Operator Name Example Description Try it == Equal to x == y Returns 1 if the values are equal Try it ยป != Not equal x != y Returns 1 if the values are not equal Try it ยป > Greater than x > y Returns 1 if the first value is greater than the second value Try it ยป < Less than x < y Returns 1 if the first value is less than the second value Try it ยป >= Greater than or equal to x >= y Returns 1 if the first value is greater than, or equal to, the second value Try it ยป <= Less than or equal to x <= y Returns 1 if the first value is less than, or equal to, the second value Try it ยป
  • 25.
    Logical Operators ๏‚— Youcan also test for true or false values with logical operators. ๏‚— Logical operators are used to determine the logic between variables or values: Operator Name Example Description && Logical and x < 5 && x < 10 Returns 1 if both statements are true || Logical or x < 5 || x < 4 Returns 1 if one of the statements is true ! Logical not !(x < 5 && x < 10) Reverse the result, returns 0 if the result is 1
  • 26.
    Sizeof Operator ๏‚— Thememory size (in bytes) of a data type or a variable can be found with the sizeof operator: ๏‚— int myInt; float myFloat; double myDouble; char myChar; printf("%lun", sizeof(myInt)); printf("%lun", sizeof(myFloat)); printf("%lun", sizeof(myDouble)); printf("%lun", sizeof(myChar));
  • 27.
    ๏‚— Note thatwe use the %lu format specifer to print the result, instead of %d. It is because the compiler expects the sizeof operator to return a long unsigned int (%lu), instead of int (%d). On some computers it might work with %d, but it is safer to use %lu. ๏‚— Why Should I Know the Size of Data Types? ๏‚— Using the right data type for the right purpose will save memory and improve the performance of your program. ๏‚— You will learn more about the sizeof operator later in this tutorial, and how to use it in different scenarios.
  • 28.
    Boolean Variables ๏‚— InC, the bool type is not a built-in data type, like int or char. ๏‚— It was introduced in C99, and you must import the following header file to use it: ๏‚— #include <stdbool.h> ๏‚— A boolean variable is declared with the bool keyword and can only take the values true or false: ๏‚— bool isProgrammingFun = true; bool isFishTasty = false; ๏‚— Before trying to print the boolean variables, you should know that boolean values are returned as integers: ๏‚— 1 (or any other number that is not 0) represents true ๏‚— 0 represents false ๏‚— Therefore, you must use the %d format specifier to print a boolean value:
  • 29.
    Comparing Values andVariables ๏‚— Comparing values are useful in programming, because it helps us to find answers and make decisions. ๏‚— For example, you can use a comparison operator, such as the greater than (>) operator, to compare two values: ๏‚— Example ๏‚— printf("%d", 10 > 9); // Returns 1 (true) because 10 is greater than 9 From the example above, you can see that the return value is a boolean value (1). ๏‚— You can also compare two variables: ๏‚— Example ๏‚— int x = 10; int y = 9; printf("%d", x > y);
  • 30.
    ๏‚— In theexample below, we use the equal to (==) operator to compare different values: ๏‚— Example ๏‚— printf("%d", 10 == 10); // Returns 1 (true), ๏‚— because 10 is equal to 10 printf("%d", 10 == 15); // Returns 0 (false), ๏‚— because 10 is not equal to 15 printf("%d", 5 == 55); // Returns 0 (false) ๏‚— because 5 is not equal to 55 ๏‚— You are not limited to only compare numbers. You can also compare boolean variables, or even special structures, like arrays (which you will learn more about in a later chapter): ๏‚— Example ๏‚— bool isHamburgerTasty = true; bool isPizzaTasty = true; // Find out if both hamburger and pizza is tasty printf("%d", isHamburgerTasty == isPizzaTasty);
  • 31.
    Real Life Example ๏‚—Let's think of a "real life example" where we need to find out if a person is old enough to vote. ๏‚— In the example below, we use the >= comparison operator to find out if the age (25) is greater than OR equal to the voting age limit, which is set to 18: ๏‚— Example ๏‚— int myAge = 25; int votingAge = 18; printf("%d", myAge >= votingAge); // Returns 1 (true), meaning 25 year olds are allowed to vote!
  • 32.
    ๏‚— Output "Oldenough to vote!" if myAge is greater than or equal to 18. Otherwise output "Not old enough to vote.": ๏‚— int myAge = 25; int votingAge = 18; if (myAge >= votingAge) { printf("Old enough to vote!"); } else { printf("Not old enough to vote.");
  • 33.
    Formatted I/O Functions ๏‚—Formatted I/O functions are used to take various inputs from the user and display multiple outputs to the user. ๏‚— These types of I/O functions can help to display the output to the user in different formats using the format specifiers. ๏‚— These I/O supports all data types like int, float, char, and many more.
  • 34.
    ๏‚— Why theyare called formatted I/O? ๏‚— These functions are called formatted I/O functions because we can use format specifiers in these functions and hence, we can format these functions according to our needs. ๏‚— printf() ๏‚— scanf()
  • 35.
    Example ๏‚— #include <stdio.h> ๏‚— ๏‚—int main() ๏‚— { ๏‚— int num1; ๏‚— ๏‚— // Printing a message on ๏‚— // the output screen ๏‚— printf("Enter a integer number: "); ๏‚— ๏‚— // Taking an integer value ๏‚— // from keyboard ๏‚— scanf("%d", &num1); ๏‚— ๏‚— // Displaying the entered value ๏‚— printf("You have entered %d", num1); ๏‚— ๏‚— return 0; ๏‚— }
  • 36.
    Unformatted Input /Output functions ๏‚— Unformatted I/O functions are used only for character data type or character array/string and cannot be used for any other datatype. ๏‚— These functions are used to read single input from the user at the console and it allows to display the value at the console. ๏‚— Why they are called unformatted I/O? ๏‚— These functions are called unformatted I/O functions because we cannot use format specifiers in these functions and hence, cannot format these functions according to our needs.
  • 37.
    ๏‚— The followingunformatted I/O functions will be discussed in this section- ๏‚— getch() ๏‚— getche() ๏‚— getchar() ๏‚— putchar() ๏‚— gets() ๏‚— puts() ๏‚— putch()
  • 38.
    ๏‚— getch(): ๏‚— getch()function reads a single character from the keyboard by the user but doesnโ€™t display that character on the console screen and immediately returned without pressing enter key. ๏‚— This function is declared in conio.h ๏‚— (header file). getch() is also used for hold the screen. ๏‚— Syntax: ๏‚— getch();
  • 39.
    ๏‚— getche(): ๏‚— getche()function reads a single character from the keyboard by the user and displays it on the console screen and immediately returns without pressing the enter key. This function is declared in conio.h(header file). ๏‚— Syntax: ๏‚— getche(); ๏‚— or ๏‚— variable_name = getche();
  • 40.
    // C programto implement // the getchar() function #include <conio.h> #include <stdio.h> // Driver code int main() { // Declaring a char type variable char ch; printf("Enter the character: "); // Taking a character from keyboard ch = getchar(); // Displays the value of ch printf("%c", ch); return 0; }
  • 41.
    ๏‚— putchar(): ๏‚— Theputchar() function is used to display a single character at a time by passing that character directly to it or by passing a variable that has already stored a character. This function is declared in stdio.h(header file) ๏‚— Syntax: ๏‚— putchar(variable_name);
  • 42.
    ๏‚— // Cprogram to implement ๏‚— // the putchar() function ๏‚— #include <conio.h> ๏‚— #include <stdio.h> ๏‚— ๏‚— // Driver code ๏‚— int main() ๏‚— { ๏‚— char ch; ๏‚— printf("Enter any character: "); ๏‚— ๏‚— // Reads a character ๏‚— ch = getchar(); ๏‚— ๏‚— // Displays that character ๏‚— putchar(ch); ๏‚— return 0; ๏‚— }
  • 43.
    gets(): ๏‚— gets() functionreads a group of characters or strings from the keyboard by the user and these characters get stored in a character array. This function allows us to write space-separated texts or strings. This function is declared in stdio.h(header file).
  • 44.
    ๏‚— / Cprogram to implement ๏‚— // the gets() function ๏‚— #include <conio.h> ๏‚— #include <stdio.h> ๏‚— ๏‚— // Driver code ๏‚— int main() ๏‚— { ๏‚— // Declaring a char type array ๏‚— // of length 50 characters ๏‚— char name[50]; ๏‚— ๏‚— printf("Please enter some texts: "); ๏‚— ๏‚— // Reading a line of character or ๏‚— // a string ๏‚— gets(name); ๏‚— ๏‚— // Displaying this line of character ๏‚— // or a string ๏‚— printf("You have entered: %s", name); ๏‚— return 0; ๏‚— }
  • 45.
    puts(): ๏‚— In Cprogramming puts() function is used to display a group of characters or strings which is already stored in a character array. This function is declared in stdio.h(header file).
  • 46.
    ๏‚— // Cprogram to implement ๏‚— // the puts() function ๏‚— #include <stdio.h> ๏‚— ๏‚— // Driver code ๏‚— int main() ๏‚— { ๏‚— char name[50]; ๏‚— printf("Enter your text: "); ๏‚— ๏‚— // Reads string from user ๏‚— gets(name); ๏‚— ๏‚— printf("Your text is: "); ๏‚— ๏‚— // Displays string ๏‚— puts(name); ๏‚— ๏‚— return 0; ๏‚— }
  • 47.
    putch(): ๏‚— putch() functionis used to display a single character which is given by the user and that character prints at the current cursor location. ๏‚— This function is declared in conio.h(header file) ๏‚— Syntax: ๏‚— putch(variable_name);
  • 48.
    ๏‚— // Cprogram to implement ๏‚— // the putch() functions ๏‚— #include <conio.h> ๏‚— #include <stdio.h> ๏‚— ๏‚— // Driver code ๏‚— int main() ๏‚— { ๏‚— char ch; ๏‚— printf("Enter any character: n "); ๏‚— ๏‚— // Reads a character from the keyboard ๏‚— ch = getch(); ๏‚— ๏‚— printf("nEntered character is: "); ๏‚— ๏‚— // Displays that character on the console ๏‚— putch(ch); ๏‚— return 0; ๏‚— }
  • 49.
    S No. Formatted I/O functions UnformattedI/O functions 1 These functions allow us to take input or display output in the userโ€™s desired format. These functions do not allow to take input or display output in user desired format. 2 These functions support format specifiers. These functions do not support format specifiers. 3 These are used for storing data more user friendly These functions are not more user- friendly. 4 Here, we can use all data types. Here, we can use only character and string data types. 5 printf(), scanf, sprintf() and sscanf() are examples of these functions. getch(), getche(), gets() and puts(), are some examples of these functions.
  • 50.
    Algorithm ๏‚— A setof instructions for resolving an issue or carrying out a certain activity. ๏‚— In computer science, algorithms are used for a wide range of operations, from fundamental math to intricate data processing. ๏‚— It defines several important features of the algorithm, including: ๏‚—
  • 51.
    important features ๏‚— Inputs:Algorithms must receive inputs that can be represented as values or data. ๏‚— Output: The algorithm should produce some output. It can be a consequence of a problem or a solution designed to solve it. ๏‚— Clarity: Algorithms must be precisely defined, using unambiguous instructions that a computer or other system can follow unambiguously. ๏‚— Finiteness: The algorithm requires a limited steps. It means that it should be exited after executing a certain number of commands. ๏‚— Validity: The algorithm must be valid. In other words, it should be able to produce a solution to the problem that the algorithm is designed to solve in a reasonable amount of time. ๏‚— Effectiveness: An algorithm must be effective, meaning that it must be able to produce a solution to the problem it is designed to solve in a reasonable amount of time. ๏‚— Generality: An algorithm must be general, meaning that it can be applied to a wide range of problems rather than being specific to a single problem.
  • 52.
    C - TypeCasting ๏‚— Converting one datatype into another is known as type casting or, type-conversion. ๏‚— For example, if you want to store a 'long' value into a simple integer then you can type cast 'long' to 'int'. You can convert the values from one type to another explicitly using the cast operator as follows โˆ’ ๏‚— (type_name) expression ๏‚— Consider the following example where the cast operator causes the division of one integer variable by another to be performed as a floating-point operation โˆ’
  • 53.
    ๏‚— #include <stdio.h> ๏‚—Int main() ๏‚— { ๏‚— int sum = 17, count = 5; ๏‚— double mean; ๏‚— mean = (double) sum / count; ๏‚— printf("Value of mean : %fn", mean ); ๏‚— }
  • 54.