0% found this document useful (0 votes)
3 views59 pages

C Programing Notes

The document provides an overview of the C programming language, including its history, significance, and basic concepts such as variables, data types, operators, and user input. It highlights the differences between C and C++, the importance of learning C for understanding other programming languages, and includes examples of code snippets. Additionally, it covers fundamental programming principles like type conversion, constants, and comparison operators.

Uploaded by

thanosrahate
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views59 pages

C Programing Notes

The document provides an overview of the C programming language, including its history, significance, and basic concepts such as variables, data types, operators, and user input. It highlights the differences between C and C++, the importance of learning C for understanding other programming languages, and includes examples of code snippets. Additionally, it covers fundamental programming principles like type conversion, constants, and comparison operators.

Uploaded by

thanosrahate
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

C

PROGRAMING
History of C
• C Programming Language created by Dennis
Ritchie at Bell Telephone Laboratories (now
Nokia Bell Labs) in 1972. It is an outgrowth of
two earlier languages, called BCPL and B,
which were also developed at bell
Laboratories.
What is C?

• C is a general-purpose programming language


and it is a very popular language in
programming field.
• C is strongly associated with UNIX, as it was
developed to write the UNIX operating
system.
Why Learn C?

• It is one of the most popular programming


language in the world
• If you know C, you can learn easily other
popular languages like C++, C#, Java, python,
etc. because of syntax is similar.
• C is very fast, compared to other programming
languages such as Java and Python
• C can used in applications and technologies.
Difference between C and C++
• C++ was developed as an extension of C, and
both languages have almost the same syntax
• The main difference between C and C++ is that
C++ support classes and objects, while C does
not
Get Started With C
When you start with C Programming language
you need two things:
1) Text editor: To write a c code
2) Compiler: Translate the C code into a
language that the computer will understand
Some of compiler: BDS, Clang, GCC,
Interactive C, Lattice, Portable C Compiler,
Visual Express, etc.
First code
Code:- 1
______________________________________
#include <stdio.h>
int main()
{
printf("This is my First Code in C \n”);
return 0;
}
_____________________________________
Code:- 2
_____________________________________
#include <stdio.h>
int main(){ printf("This is my First Code in C \n”); return 0;}
Details Of The Above Code
• In above code we use #include <stdio.h> for Library
file access
• Next code is int main(). This is called a function and
inside its curly brackets {} will be executed.
• printf(); is also function used to print text(output) to
the screen.
• return 0; used to inform the operating system that the
program has completed its task without any errors.
• Semicolon ( ; ) is used for declare the statement ends.
• (\n) is used to change its position to the newline, It is
called an Escape Sequence.
Escape Sequence
Escape Sequence Description

\n Newline (line feed)

\t Creates a horizontal tab

\\ Inserts a backslash character (\)

\" Inserts a double quote character


What is Variables?
• A variable is the name of a memory location
which stores some data.
Rules
1. Variables are case sensitive. (a & A are different)
2. Variable names can only consist of letters,
digits, and underscores ( _ ), and they must
start with a letter or an underscore.
3. Blank space is also not allowed in variable
names.
Code:3 (Variables)
#include <stdio.h>
int main()
{
int age=40;
printf("my age is %d", age);
return 0;
}
Basic Data Types
• The data type specifies the size and type of
information the variable will store.
Data Size Description
Type
int 2 or 4 Stores whole numbers, without decimals
bytes

float 4 Stores fractional numbers, containing one or more


bytes decimals. Sufficient for storing 6-7 decimal digits

double 8 Stores fractional numbers, containing one or more


bytes decimals. Sufficient for storing 15 decimal digits

char 1 byte Stores a single character/letter/number, or ASCII


values
Basic Format Specifiers
• There are different format specifiers for each
data type.
Format Specifier Data Type

%d or %i int

%f float

%lf double

%c char

%s Used for strings (text), which you will learn


more about in a later chapter
Example Of int
#include <stdio.h>

int main() {
int myNum = 5; // integer

printf("%d\n", myNum);
printf("%i\n", myNum);
return 0;
}
Example Of float
#include <stdio.h>

int main() {
float myFloatNum = 5.99; // Floating point number

printf("%f", myFloatNum);
return 0;
}
Example Of double
#include <stdio.h>

int main() {
double myDoubleNum = 19.99; // Double (floating
point number)

printf("%lf", myDoubleNum);
return 0;
}
Example Of char
#include <stdio.h>

int main() {
char myLetter = ‘&'; // Character

printf("%c", myLetter);
return 0;
}
Example Of Strings
#include <stdio.h>

int main() {
char About_string[] = “This is an example of strings";
printf("%s", About_string);

return 0;
}
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 output
3.400000
18.890000
• If you want to remove the extra zeros of decimal you can.
use a dot (.) as follows:
• %.1f // Show only 1 decimal digit
• %.2f // Show only 2 decimal digit
• %.4f // Show only 4 decimal digit
Example of Decimal
#include <stdio.h>

int main() {
float myFloatNum = 3.5;

printf("%f\n", myFloatNum); // Default decimal


printf("%.1f\n", myFloatNum); // Show only 1 decimal digit
printf("%.2f\n", myFloatNum); // Show only 1 decimal digit
printf("%.4f", myFloatNum); // Show only 1 decimal digit
return 0;
}
Type Conversion
• In C programming, when you divide two whole numbers (integers), you don't get
decimal answers like you do in regular math. Instead, C cuts off the decimal part,
giving you a whole number answer.
• To get the right result, you need to know how type conversion works.
• There are two types of conversion in C:

• Implicit Conversion (automatically)

• Explicit Conversion (manually)


• Example: Consider the expression: 5 ÷ 2
• Expected Result: In mathematics, we would expect this to be equal to 2.5,
with a decimal component.
• Actual Result in C: However, in C programming, the result is different. The
division operator / when used with integers will give you an integer
quotient. Therefore, 5 ÷ 2 in C will result in 2. The decimal part (0.5) is
discarded.
• Explanation: C performs integer division by neglecting the remainder. It
effectively rounds down to the nearest integer value. This behavior can be
surprising if you're not familiar with it.
Implicit Conversion
• Implicit conversion is done automatically by the compiler when you
assign a value of one type to another.
For example, if you assign an int value to a float & float value to a int :

#include <stdio.h> #include <stdio.h>

int main() { int main() {


// Automatic conversion: int to float // Automatic conversion: float to int
float myFloat = 8; int myInt = 8.89;

printf("%f", myFloat); printf("%d", myInt);


return 0; return 0;
} }

Output Output
8.000000 8
Explicit Conversion
• Explicit conversion is done manually by placing the type in
parentheses () in front of the value.
• Considering our problem from the example above, we can now get the
right result:
#include <stdio.h> #include <stdio.h>

int main() { int main() {


// Manual conversion: int to float int num1 = 5;
float sum = (float) 5 / 2; int num2 = 2;
float sum = (float) num1 / num2;
printf("%f", sum);
return 0; printf("%f", sum);
} return 0;
}
Output Output
2.500000 2.500000
Constants
• If you don't want others (or yourself) to change existing variable values, you can use the
const keyword.
• This will declare the variable as "constant", which means unchangeable and read-only.
• Example

#include <stdio.h> #include <stdio.h> #include <stdio.h>

int main() { int main() { int main() {


const int myNum = const int const int
15; minutesPerHour = 60; minutesPerHour;
myNum = 10; minutesPerHour = 60;

printf("%d", myNum); printf("%d", printf("%d",


return 0; minutesPerHour); minutesPerHour);
} return 0; return 0;
} }
Output Output Output
4 | minutesPerHour = 60 4 | minutesPerHour =
60; 60;
error error
Operators
• Operators are used to perform operations on variables and
In the example below, we use the + operator to add together two
values:values.:
#include <stdio.h> Output
150
int main() {
int myNum = 100 + 50;
printf("%d", myNum);
return 0;
}

C divides the operators into the following groups:


Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators
Arithmetic Operators
Operator Name Description Example
+ Addition Adds together two x+y
values
- Subtraction Subtracts one value x-y
from another
* Multiplication Multiplies two x*y
values
/ Division Divides one value x/y
by another
% Modulus Returns the division x%y
remainder
++ Increment Increases the value ++x
of a variable by 1
-- Decrement Decreases the value --x
of a variable by 1
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:
• #include <stdio.h>

• int main() {
• int x = 10;
• printf("%d", x);
• return 0;
• }

• The addition assignment operator (+=) adds a value to a variable:


• #include <stdio.h>

• int main() {
• int x = 10;
• x += 5;
• printf("%d", x);
• return 0;
• }
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


Operator Description Example

= Simple assignment operator. Assigns values from right side C = A + B will assign the value of A
operands to left side operand + B to C

+= Add AND assignment operator. It adds the right operand to C += A is equivalent to C = C + A


the left operand and assign the result to the left operand.

-= Subtract AND assignment operator. It subtracts the right C -= A is equivalent to C = C - A


operand from the left operand and assigns the result to
the left operand.

*= Multiply AND assignment operator. It multiplies the right C *= A is equivalent to C = C * A


operand with the left operand and assigns the result to the
left operand.

/= Divide AND assignment operator. It divides the left C /= A is equivalent to C = C / A


operand with the right operand and assigns the result to
the left operand.

%= Modulus AND assignment operator. It takes modulus using C %= A is equivalent to C = C % A


two operands and assigns the result to the left operand.

<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2

^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2

|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2


User Input
• You have already learned that printf() is used to output values in C.
To get user input, you can use the scanf() function:
#include <stdio.h>

int main() {
// Create an integer variable that will store the number we get from the user
int myNum;

// Ask the user to type a number


printf("Type a number and press enter: \n");

// Get and save the number the user types


scanf("%d", &myNum);

// Print the number the user typed


printf("Your number is: %d", myNum);

return 0;
}
• The scanf() function takes two arguments: the
format specifier of the variable (%d in the
example above) and the reference operator
(&myNum), which stores the memory address
of the variable.

• Multiple Inputs
The scanf() function also allow multiple inputs
(an integer and a character)
Multiple Inputs example
• #include <stdio.h>

• int main() {
• // Create an int and a char variable
• int myNum;
• char myChar;

• // Ask the user to type a number AND a character


• printf("Type a number AND a character and press enter: \n");

• // Get and save the number AND character the user types
• scanf("%d %c", &myNum, &myChar);

• // Print the number


• printf("Your number is: %d\n", myNum);

• // Print the character


• printf("Your character is: %c\n", myChar);

• return 0;
• }
Take String Input
• You can also get a string entered by the user:
#include <stdio.h>

int main() {
// Create a string
char firstName[30];

// Ask the user to input some text (name)


printf("Enter your first name and press enter: \n");

// Get and save the text


scanf("%s", firstName);

// Output the text


printf("Hello %s", firstName);

return 0;
}
Comparison Operators
• Comparison operators are a fundamental part of
programming and are used to compare two values or
variables. They allow programmers to perform
various tasks such as making decisions, controlling
program flow, and evaluating conditions. Comparison
operators return a Boolean value (either True (1) or
False (0)) based on the comparison result, which is
essential for creating conditional statements and
controlling the logic of a program.
Example
#include <stdio.h> #include <stdio.h>

int main() int main()


{ {
int x = 6; int x = 4;
int y = 4; int y = 6;
printf("%d true", x > y); printf("%d false", x > y);
/* returns 1 (true) because 6is /* returns 0 (false) because 6
greater than 4*/ is not less than 4*/
return 0; return 0;
} }

1 true 0 false
Operator Name
== Equal to Checks if two values are
equal
!= Not equal to Checks if two values are
not equal.
> Greater than Checks if the left operand
is greater than the right
operand.
< Less than Checks if the left operand
is less than the right
operand.
>= Greater than or equal to Checks if the left operand
is greater than or equal to
the right operand.
<= Less than or equal to Checks if the left operand
is less than or equal to the
right operand.
These comparison operators allow programmers to compare values or variables in
various ways, and the results can be used to make decisions in conditional statements.
If Statements
• In C programming, an "if statement" is a
conditional control structure that allows you
to execute a block of code if a specified
condition is true. If the condition is false, the
code block associated with the if statement is
skipped.
Example

#include <stdio.h>

int main() {
int x = 5;
int y = 10;

// Using comparison operators in if statements


if (x > y) {
printf("x is greater than y\n");
}

if (x == y) {
printf("x is equal to y\n");
}

if (x < y) {
printf("y is greater than x\n");
}

return 0;
}
Logical Operators
In C programming, logical operators are used to
perform logical operations on Boolean values
(true or false) or expressions that evaluate to
true or false. There are three main logical
operators in C:
Operator Name Description
&& Logical and Returns true if both statements are true
|| Logical or Returns true if one of the statements is true
! Logical not Reverse the result, returns false if the result is true
Logical AND (&&): logical AND operator (&&) is used to perform a logical AND
operation between two or more conditions or expressions. It returns true if all of its
operands are true, and false if at least one of its operands is false.

#include <stdio.h> #include <stdio.h>


int main() { int main() {
int age = 25; int age = 25;
int height = 155; int height = 155;
if (age >= 18 && height >= 160) { if (age >= 18 && height >= 160) {
printf("You are eligible to ride printf("You are eligible to ride
the roller coaster.\n"); the roller coaster.\n");
} }
else { else {
printf("Sorry, you are not printf("Sorry, you are not
eligible to ride the roller eligible to ride the roller
coaster.\n"); coaster.\n");
} }
return 0; return 0;
} }
• Logical OR (||): logical OR operator (||) is used to
perform a logical OR operation between two or more
conditions or expressions. It returns true if at least
one of its operands is true, and false if all of its
operands are false. Here's the basic syntax of the
logical OR operator
int temperature = 28; int temperature = 28;
int humidity = 80; int humidity = 95;

if (temperature > 30 || humidity > 90) { if (temperature > 30 || humidity > 90) {
printf("It's a hot day or a humid day printf("It's a hot day or a humid day
(or both).\n"); (or both).\n");
} else { } else {
printf("The weather is printf("The weather is
comfortable.\n"); comfortable.\n");
} }
• Logical NOT (!): In C programming, the logical NOT
operator (!) is a unary operator used to negate the
value of a Boolean expression or condition. It returns
true if the operand is false, and it returns false if the
operand is true. Here's the basic syntax of the logical
NOT operator:
int isSunny = 0; // 0 represents false int isSunny = 1; // 1 represents true
int isRainy = 1; // 1 represents true int isRainy = 0; // 0 represents false

if (!isSunny) { if (!isSunny) {
printf("It's not sunny today.\n"); printf("It's not sunny today.\n");
} }

if (!isRainy) { if (!isRainy) {
printf("It's not rainy today.\n"); printf("It's not rainy today.\n");
} }
Sizeof Operator
• In C programming, the sizeof the operator is used to
determine the size in bytes of a data type or an object. It
can be used with various data types, including primitive
data types (e.g., int, char, float) and user-defined data types
(e.g., structures and arrays). The result of the sizeof the
operator is a constant value, typically of type size_t, which
represents the size in bytes.
#include <stdio.h> #include <stdio.h>

int main() { int main() {


int myInt; int myInt[23];
float myFloat; float myFloat[25];
double myDouble; double myDouble[20];
char myChar; char myChar[40];

printf("%lu\n", sizeof(myInt)); printf("%lu\n", sizeof(myInt));


printf("%lu\n", sizeof(myFloat)); printf("%lu\n", sizeof(myFloat));
printf("%lu\n", sizeof(myDouble)); printf("%lu\n", sizeof(myDouble));
printf("%lu\n", sizeof(myChar)); printf("%lu\n", sizeof(myChar));

return 0; return 0;
} }
Memory
In computer memory, every piece of data is
encoded using a distinct combination of binary
digits, commonly referred to as "bits." These binary
digits are represented by electronic devices, and
they have two fundamental states: "off" (0) and
"on" (1). The state of each bit is determined by the
electronic device, signifying either a zero or a one.

This binary representation forms the basis of all


digital information storage and processing within a
computer. It is a fundamental language that
enables computers to work with a wide range of
data types, from numbers and text to multimedia
content.
Bitwise operators
• In the C programming language, you can use bitwise operators to perform bit-
level operations on integer types. C provides the following bitwise operators
Operator Name Description

& Bitwise AND This operator performs a bitwise AND operation between
corresponding bits of two integers
| Bitwise OR The bitwise OR operator compares each bit of two integers
and returns a new integer where each bit position is set to 1
if at least one of the corresponding bits in both operands is 1.

~ Bitwise NOT This operator performs a bitwise NOT operation on an


integer, inverting all its bits.
<< Left Shift This operator shifts the bits of an integer to the left by a
specified number of positions.
>> Right Shift This operator shifts the bits of an integer to the right by a
specified number of positions.
^ Bitwise XOR The bitwise XOR (exclusive OR) operator compares each bit
of two integers and returns a new integer where each bit
position is set to 1 if the corresponding bits in the operands
are different (one is 0 and the other is 1).
& int a = 5; // binary: 0101
int b = 3; // binary: 0011
int result = a & b; // result: 1 (binary: 0001)
| int a = 5; // binary: 0101
int b = 3; // binary: 0011
int result = a | b; // result: 7 (binary: 0111)
^ int a = 5; // binary: 0101
int b = 3; // binary: 0011
int result = a ^ b; // result: 6 (binary: 0110)

~ int a = 5; // binary: 0101


int result = ~a; // result: -6 (binary: 1010)

<< int a = 5; // binary: 0101


int result = a << 2; // result: 20 (binary: 10100)

>> int a = 20; // binary: 10100 int result = a >> 2; // result: 5 (binary:
0101)
Conditions and If Statements
In the C programming language, you have several
conditional statements that allow you to control the flow of
your program based on certain conditions. The primary
conditional statements in C include:
• Use if to specify a block of code to be executed, if a
specified condition is true

• Use else to specify a block of code to be executed, if the


same condition is false

• Use else if to specify a new condition to test, if the first


condition is false

• Use switch to specify many alternative blocks of code to be


executed
The else Statement
• The else statement in C is used to specify a block
of code that should be executed when the
condition specified in the preceding if statement
is false. Here's an example that demonstrates
how to use the else statement:
#include <stdio.h> #include <stdio.h>

int main() { int main() {


int age = 25; int age = 17;

if (age >= 18) { if (age >= 18) {


printf("You are an adult.\n"); printf("You are an adult.\n");
} else { } else {
printf("You are not an adult.\n"); printf("You are not an adult.\n");
} }

return 0; return 0;
} }
The else if Statement
• The else if statement in C allows you to specify a new
condition to be checked if the previous condition (in the if
statement or another else if block) is false. This allows you
to create a series of conditional checks. Here's an example:
#include <stdio.h> #include <stdio.h>

int main() { int main() {


int score = 75; int score = 62;

if (score >= 90) { if (score >= 90) {


printf("A grade\n"); printf("A grade\n");
} else if (score >= 80) { } else if (score >= 80) {
printf("B grade\n"); printf("B grade\n");
} else if (score >= 70) { } else if (score >= 70) {
printf("C grade\n"); printf("C grade\n");
} else if (score >= 60) { } else if (score >= 60) {
printf("D grade\n"); printf("D grade\n");
} else { } else {
printf("F grade\n"); printf("F grade\n");
} }

return 0; return 0;
} }
Switch Statement
A switch statement in C programming is a control structure that allows you to
execute different code blocks based on the value of a specified expression. It is
commonly used when you have a single expression that can have multiple
possible values, and you want to perform different actions based on those
values. The switch statement provides a more efficient and structured way to
handle multiple conditional cases compared to a series of if-else statements.

1. The expression is evaluated, and its value is compared to the values specified in the case
labels.

2. If a match is found between the expression and one of the case constants, the code block
following that case label is executed.

3. The break statement is used to exit the switch statement and prevent execution from falling
through to subsequent cases. If no break is encountered, the code will continue executing
the statements in subsequent cases until a break is encountered or the end of the switch
statement is reached.

4. The default case is optional, and it is executed when none of the case constants match the
value of the expression. You can think of it as the "catch-all" case.
Basic syntax of a switch statement in C
switch (expression) {
case constant1:
// Code to execute if expression == constant1
break;

case constant2:
// Code to execute if expression == constant2
break;

// Add more cases as needed

default:
// Code to execute if expression doesn't match any case
}
switch-case statements if-else statements
int main() { int main() {
int day = 4; int day = 4;

switch (day) { if (day == 1) {


case 1: printf("Monday");
printf("Monday"); } else if (day == 2) {
break; printf("Tuesday");
case 2: } else if (day == 3) {
printf("Tuesday"); printf("Wednesday");
break; } else if (day == 4) {
case 3: printf("Thursday");
printf("Wednesday"); } else if (day == 5) {
break; printf("Friday");
case 4: } else if (day == 6) {
printf("Thursday"); printf("Saturday");
break; } else if (day == 7) {
case 5: printf("Sunday");
printf("Friday"); } else {
break; printf("Invalid day");
case 6: }
printf("Saturday");
break; return 0;
case 7: }
printf("Sunday");
break;
}

return 0;
}
LOOP
• In C programming, loops are control structures
that allow you to execute a block of code
repeatedly based on a specified condition. There
are three main types of loops in C:
• for Loop
for (statement 1; statement 2; statement 3) { // code block to be executed}

• while Loop
while (condition) { // Code to be executed repeatedly }

do-while Loop
do { // Code to be executed repeatedly } while (condition);
for Loop
• The for loop is typically used when you know how many times you
want to repeat a block of code. It consists of three parts:
initialization, condition, and increment/decrement.
Example:

#include <stdio.h>
int main() {
int i;

for (i = 0; i < 5; i++) {


printf("%d\n", i);
}
return 0;
}
while Loop
• The while loop is used when you want to repeat a
block of code as long as a certain condition is
true. It checks the condition before each
iteration.
Example:
#include <stdio.h>
int main() {
int i = 0;
while (i < 5) {
printf("%d\n", i);
i++;
}
return 0;
}
do-while Loop
• The do-while loop is similar to the while loop, but
it always executes the code block at least once
because it checks the condition after the code
block is executed.
• Example:
#include <stdio.h>

int main() {
int count = 1;
do {
printf("%d\n", count);
count++;
}
while (count <= 5);

return 0;
}

You might also like