SlideShare a Scribd company logo
C Programming
Program Structure
• The first line of the program #include
<stdio.h> is a preprocessor command, which
tells a C compiler to include stdio.h file
before going to actual compilation.
• The next line int main() is the main function
where the program execution begins.
• The next line /*...*/ will be ignored by the
compiler and it has been put to add additional
comments in the program. So such lines are
called comments in the program.
• The next line printf(...) is another function
available in C which causes the message
"Hello, World!" to be displayed on the screen.
• The next line return 0; terminates the main()
function and returns the value 0.
#include <stdio.h>
int main() {
/* my first program in C */
printf("Hello, World! n");
return 0;
}
VARIABLES
Variables
Variables are containers for storing data values.
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;
• Example
• int a = 10;
• float b = 10.5;
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, you must use the
format specifier %d or %i surrounded by double quotes, inside
the printf() function:
•Example
• int myNum = 15;
printf("%d", myNum); // Outputs 15
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
DATA TYPES
Data Types
Data Type Size Description Format
Specifier
int 2 or 4 bytes Stores whole numbers, without decimals %d
float 4 bytes Stores fractional numbers, containing one or
more decimals. Sufficient for storing 7
decimal digits
%f
double 8 bytes Stores fractional numbers, containing one or
more decimals. Sufficient for storing 15
decimal digits
%lf
char 1 byte Stores a single character/letter/number, or
ASCII values
%c
CONSTANTS
Constants
• When you don't want others (or yourself) to override existing variable
values, use the const keyword (this will declare the variable as "constant",
which means unchangeable and read-only)
• const int myNum = 15; // myNum will always be 15
myNum = 10; // error: assignment of read-only variable 'myNum’
• Notes On Constants
• When you declare a constant variable, it must be assigned with a value:
• Example
• Like this:
• const int minutesPerHour = 60;
• This however, will not work:
• const int minutesPerHour;
minutesPerHour = 60; // error
OPERATORS
Operators
• Operators are used to perform operations on variables and values.
• In the example below, we use the + operator to add together two values:
• Example
• int myNum = 100 + 50;
• 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 values x + y
- Subtraction Subtracts one value from another x - y
* Multiplicati
on
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.
Example
int x = 10; 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
Comparison Operators
Operator Name Example
== Equal to x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
• Comparison operators are used to compare two values.
• Note: The return value of a comparison is either true (1) or false (0).
Logical Operators
• Logical operators are used to determine the logic
between variables or values:
Operator Name Description Example
&& Logical and Returns true if both statements are
true
x < 5 && x < 10
|| Logical or Returns true if one of the
statements is true
x < 5 || x < 4
! Logical not Reverse the result, returns false if
the result is true
!(x < 5 && x < 10)
Sizeof Operator
• The memory size (in bytes) of a data type or a variable can be found with
the sizeof operator:
•Example
int myInt;
float myFloat;
double myDouble;
char myChar;
printf("%lun", sizeof(myInt));
printf("%lun", sizeof(myFloat));
printf("%lun", sizeof(myDouble));
printf("%lun", sizeof(myChar));
DECISION MAKING
Decision Making
C has the following conditional statements:
•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 if Statement
• Use the if statement to specify a block of C code to be executed if a
condition is true.
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
• Example
• if (20 > 18) {
printf("20 is greater than 18");
}
Output:
20 is greater than 18
The else Statement
Use the else statement to specify a block of code to be executed if the condition
is false.
Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
• Example
• if (20 > 18) {
printf(“It is true");
}
else{
printf(“It is false”);
}
Output:
It is true
The else if Statement
Use the else if statement to specify a new condition if the first condition
is false.
Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false
and condition2 is true
} else {
// block of code to be executed if the condition1 is false
and condition2 is false
}
• Example
• int time = 22;
if (time < 10) {
printf("Good morning.");
} else if (time < 20) {
printf("Good day.");
} else {
printf("Good evening.");
}
Switch
Instead of writing many if..else statements, you can use
the switch statement.
The switch statement selects one of many code blocks to be executed:
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
This is how it works:
•The switch expression is evaluated once
•The value of the expression is compared with the values of
each case
•If there is a match, the associated block of code is executed
•The break statement breaks out of the switch block and
stops the execution
•The default statement is optional, and specifies some code
to run if there is no case match
• Example
• int day = 4;
switch (day) {
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday")
;
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
case 7:
printf("Sunday");
break;
}
The break Keyword
When C reaches a break keyword, it breaks out of the switch block.
This will stop the execution of more code and case testing inside the
block.
When a match is found, and the job is done, it's time for a break.
There is no need for more testing.
The default Keyword
The default keyword specifies some code to run if there is no case match
LOOPING STATEMENT
Looping Statement
• Loops can execute a block of code as long as a specified
condition is reached.
• Loops are handy because they save time, reduce errors,
and they make code more readable.
• While
• Do While
• For
While
The while loop loops through a block of code as long as a
specified condition is true:
Syntax
while (condition) {
// code block to be executed
}
• Example
• int i = 0;
while (i < 5) {
printf("%dn", i);
i++;
}
Do While
The do/while loop is a variant of the while loop. This loop will execute the code block
once, before checking if the condition is true, then it will repeat the loop as long as the
condition is true.
• Syntax
• do {
// code block to be executed
}
while (condition);
• Example
• int i = 0;
do {
printf("%dn", i);
i++;
}
while (i < 5);
For
When you know exactly how many times you want to loop through a block
of code, use the for loop instead of a while loop
• Syntax
• for (statement 1; statement 2; statement 3) {
// code block to be executed
}
• Statement 1 is executed (one time) before the execution of the code
block.
• Statement 2 defines the condition for executing the code block.
• Statement 3 is executed (every time) after the code block has been
executed.
• Example
• int i;
for (i = 0; i < 5; i++) {
printf("%dn", i);
}
ARRAYS
Arrays
• Arrays are used to store multiple values in a single variable,
instead of declaring separate variables for each value.
• To create an array, define the data type (like int) and specify
the name of the array followed by square brackets [].
• To insert values to it, use a comma-separated list, inside curly
braces:
• int myNumbers[] = {25, 50, 75, 100};
• We have now created a variable that holds an array of four
integers.
Access the Elements of an Array
• To access an array element, refer to its index number.
• Array indexes start with 0: [0] is the first element. [1] is the
second element, etc.
• This statement accesses the value of the first element
[0] in myNumbers:
• Example
• int myNumbers[] = {25, 50, 75, 100};
printf("%d", myNumbers[0]);
Change an Array Element
• To change the value of a specific element, refer to the
index number:
• Example
• myNumbers[0] = 33;
• Example
• int myNumbers[] = {25, 50, 75, 100};
myNumbers[0] = 33;
printf("%d", myNumbers[0]);
Loop Through an Array
• You can loop through the array elements with the for loop.
• The following example outputs all elements in
the myNumbers array:
• Example
• int myNumbers[] = {25, 50, 75, 100};
int i;
for (i = 0; i < 4; i++) {
printf("%dn", myNumbers[i]);
}
Set Array Size
• Another common way to create arrays, is to specify the
size of the array, and add elements later:
• Example
• // Declare an array of four integers:
int myNumbers[4];
// Add elements
myNumbers[0] = 25;
myNumbers[1] = 50;
myNumbers[2] = 75;
myNumbers[3] = 100;
Multi-dimensional array
• A multi-dimensional array can be termed as an array of arrays
that stores homogeneous data in tabular form. Data in
multidimensional arrays are stored in row-major order.
• The general form of declaring N-dimensional arrays is:
• data_type array_name[size1][size2]....[sizeN];
•data_type: Type of data to be stored in the array.
•array_name: Name of the array
•size1, size2,… ,sizeN: Sizes of the dimension
• Examples:
• Two dimensional array: int two_d[10][20]; Three
dimensional array: int three_d[10][20][30];
2-D Array
• Initializing Two – Dimensional Arrays: There are various ways in
which a Two-Dimensional array can be initialized.
• First Method:
• int x[3][4] = {0, 1 ,2 ,3 ,4 , 5 , 6 , 7 , 8 , 9 ,
10 , 11}
• The above array has 3 rows and 4 columns. The elements in the
braces from left to right are stored in the table also from left to
right. The elements will be filled in the array in order, the first 4
elements from the left in the first row, the next 4 elements in the
second row, and so on.
• Second Method:
• int x[3][4] = {{0,1,2,3}, {4,5,6,7},
{8,9,10,11}};
• Third Method:
int x[3][4];
for(int i = 0; i < 3; i++){
for(int j = 0; j < 4; j++){
scanf(“%d”, x[i][j]);
}
}
STRUCTURE
Structures (structs)
• Structures (also called structs) are a way to group
several related variables into one place. Each variable in
the structure is known as a member of the structure.
• Unlike an array, a structure can contain many different
data types (int, float, char, etc.).
Create a Structure
• You can create a structure by using the struct keyword and declare each of its members
inside curly braces:
• struct MyStructure { // Structure declaration
int myNum; // Member (int variable)
char myLetter; // Member (char variable)
}; // End the structure with a semicolon
• To access the structure, you must create a variable of it.
• Use the struct keyword inside the main() method, followed by the name of the structure
and then the name of the structure variable:
• Create a struct variable with the name "s1":
• struct myStructure {
int myNum;
char myLetter;
};
int main() {
struct myStructure s1;
return 0;
}
Access Structure Members
To access members of a structure, use the dot syntax (.):
Example
// Create a structure called myStructure
struct myStructure {
int myNum;
char myLetter;
};
int main() {
// Create a structure variable of myStructure called s1
struct myStructure s1;
// Assign values to members of s1
s1.myNum = 13;
s1.myLetter = 'B';
// Print values
printf("My number: %dn", s1.myNum);
printf("My letter: %cn", s1.myLetter);
return 0;
}
What About Strings in Structures?
• Remember that strings in C are actually an array of characters, and unfortunately, you can't
assign a value to an array like this:
• Example
• struct myStructure {
int myNum;
char myLetter;
char myString[30]; // String
};
int main() {
struct myStructure s1;
// Trying to assign a value to the string
s1.myString = "Some text";
// Trying to print the value
printf("My string: %s", s1.myString);
return 0;
}
Solution
• However, there is a solution for this! You can use the strcpy() function and assign the value
to s1.myString, like this:
• Example
• struct myStructure {
int myNum;
char myLetter;
char myString[30]; // String
};
int main() {
struct myStructure s1;
// Assign a value to the string using the strcpy function
strcpy(s1.myString, "Some text");
// Print the value
printf("My string: %s", s1.myString);
return 0;
}
Simpler Syntax
• You can also assign values to members of a structure variable at declaration time, in a single line.
• Just insert the values in a comma-separated list inside curly braces {}. Note that you don't have to
use the strcpy() function for string values with this technique:
• Example
• // Create a structure
struct myStructure {
int myNum;
char myLetter;
char myString[30];
};
int main() {
// Create a structure variable and assign values to it
struct myStructure s1 = {13, 'B', "Some text"};
// Print values
printf("%d %c %s", s1.myNum, s1.myLetter, s1.myString);
return 0;
}
Copy Structures
• You can also assign one structure to another.
• In the following example, the values of s1 are copied to
s2:
• Example
• struct myStructure s1 = {13, 'B', "Some text"};
struct myStructure s2;
s2 = s1;
Modify Values
• If you want to change/modify a value, you can use the dot syntax (.).
• And to modify a string value, the strcpy() function is useful again:
• Example
• struct myStructure {
int myNum;
char myLetter;
char myString[30];
};
int main() {
// Create a structure variable and assign values to it
struct myStructure s1 = {13, 'B', "Some text"};
// Modify values
s1.myNum = 30;
s1.myLetter = 'C';
strcpy(s1.myString, "Something else");
// Print values
printf("%d %c %s", s1.myNum, s1.myLetter, s1.myString);
return 0;
}
• Example
• struct Car {
char brand[50];
char model[50];
int year;
};
int main() {
struct Car car1 = {"BMW", "X5", 1999};
struct Car car2 = {"Ford", "Mustang", 1969};
struct Car car3 = {"Toyota", "Corolla", 2011};
printf("%s %s %dn", car1.brand, car1.model,
car1.year);
printf("%s %s %dn", car2.brand, car2.model,
car2.year);
printf("%s %s %dn", car3.brand,
car3.model, car3.year);
C Programming with oops Concept and Pointer

More Related Content

Similar to C Programming with oops Concept and Pointer (20)

PPT
c-programming
Zulhazmi Harith
 
PPTX
BCP_u2.pptxBCP_u2.pptxBCP_u2.pptxBCP_u2.pptx
RutviBaraiya
 
PPTX
Introduction to Programming c language.pptx
meesalasrinuvasuraon
 
PPT
Introduction to c
sunila tharagaturi
 
ODP
Programming basics
Bipin Adhikari
 
PPTX
the refernce of programming C notes ppt.pptx
AnkitaVerma776806
 
PPSX
Esoft Metro Campus - Certificate in c / c++ programming
Rasan Samarasinghe
 
PPT
slidenotesece246jun2012-140803084954-phpapp01 (1).ppt
yatakonakiran2
 
PPTX
Programming Fundamentals
umar78600
 
PPTX
What is c
Nitesh Saitwal
 
PPT
C tutorial
Anurag Sukhija
 
PPTX
PHP slides
Farzad Wadia
 
PDF
C language concept with code apna college.pdf
mhande899
 
PPTX
basic C PROGRAMMING for first years .pptx
divyasindhu040
 
PPTX
C Programming Unit-1
Vikram Nandini
 
PPTX
presentation_c_basics_1589366177_381682.pptx
KrishanPalSingh39
 
PPTX
Introduction to C programming language. Coding
TanishqGosavi
 
PPTX
C programming language
Abin Rimal
 
PDF
2 EPT 162 Lecture 2
Don Dooley
 
c-programming
Zulhazmi Harith
 
BCP_u2.pptxBCP_u2.pptxBCP_u2.pptxBCP_u2.pptx
RutviBaraiya
 
Introduction to Programming c language.pptx
meesalasrinuvasuraon
 
Introduction to c
sunila tharagaturi
 
Programming basics
Bipin Adhikari
 
the refernce of programming C notes ppt.pptx
AnkitaVerma776806
 
Esoft Metro Campus - Certificate in c / c++ programming
Rasan Samarasinghe
 
slidenotesece246jun2012-140803084954-phpapp01 (1).ppt
yatakonakiran2
 
Programming Fundamentals
umar78600
 
What is c
Nitesh Saitwal
 
C tutorial
Anurag Sukhija
 
PHP slides
Farzad Wadia
 
C language concept with code apna college.pdf
mhande899
 
basic C PROGRAMMING for first years .pptx
divyasindhu040
 
C Programming Unit-1
Vikram Nandini
 
presentation_c_basics_1589366177_381682.pptx
KrishanPalSingh39
 
Introduction to C programming language. Coding
TanishqGosavi
 
C programming language
Abin Rimal
 
2 EPT 162 Lecture 2
Don Dooley
 

More from Jeyarajs7 (15)

PPTX
Python Using Face Detection Coding Session
Jeyarajs7
 
PPTX
Python Using Face Detection Coding Session
Jeyarajs7
 
PPTX
Full Stack_HTML- Hypertext Markup Language
Jeyarajs7
 
PPTX
Full Stack_Reac web Development and Application
Jeyarajs7
 
PPTX
AI PPT 2023 for College Students and Arts
Jeyarajs7
 
PPTX
AI PPT 2023 for College Students and Arts
Jeyarajs7
 
PPTX
Technology Readiness Level in Computer Sci
Jeyarajs7
 
PPTX
Technology Readiness Level in Computer Sci
Jeyarajs7
 
PPTX
DIGITAL MARKETING UPDATE VERSION NEW ONE
Jeyarajs7
 
PPTX
IT Related file Hardware and Software SPec
Jeyarajs7
 
PPTX
Cream & Pastel Palette Healthcare Center Characters By Slidesgos.pptx
Jeyarajs7
 
PPTX
Math Subject for Elementary - 5th Grade_ Fractions I _ by Slidesgo.pptx
Jeyarajs7
 
PPTX
About Mental Health - Mrs.Sivakakthi.pptx
Jeyarajs7
 
PPTX
Machine Coding , Machine Language and AI
Jeyarajs7
 
PPTX
Basics of Fullstack like Web Development
Jeyarajs7
 
Python Using Face Detection Coding Session
Jeyarajs7
 
Python Using Face Detection Coding Session
Jeyarajs7
 
Full Stack_HTML- Hypertext Markup Language
Jeyarajs7
 
Full Stack_Reac web Development and Application
Jeyarajs7
 
AI PPT 2023 for College Students and Arts
Jeyarajs7
 
AI PPT 2023 for College Students and Arts
Jeyarajs7
 
Technology Readiness Level in Computer Sci
Jeyarajs7
 
Technology Readiness Level in Computer Sci
Jeyarajs7
 
DIGITAL MARKETING UPDATE VERSION NEW ONE
Jeyarajs7
 
IT Related file Hardware and Software SPec
Jeyarajs7
 
Cream & Pastel Palette Healthcare Center Characters By Slidesgos.pptx
Jeyarajs7
 
Math Subject for Elementary - 5th Grade_ Fractions I _ by Slidesgo.pptx
Jeyarajs7
 
About Mental Health - Mrs.Sivakakthi.pptx
Jeyarajs7
 
Machine Coding , Machine Language and AI
Jeyarajs7
 
Basics of Fullstack like Web Development
Jeyarajs7
 
Ad

Recently uploaded (20)

PPTX
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
PDF
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PDF
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
PDF
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
PPTX
How Cloud Computing is Reinventing Financial Services
Isla Pandora
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PPTX
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
 
PDF
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
DOCX
Import Data Form Excel to Tally Services
Tally xperts
 
PPTX
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
PDF
Online Queue Management System for Public Service Offices in Nepal [Focused i...
Rishab Acharya
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PPTX
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
How Cloud Computing is Reinventing Financial Services
Isla Pandora
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
 
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
Import Data Form Excel to Tally Services
Tally xperts
 
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
Online Queue Management System for Public Service Offices in Nepal [Focused i...
Rishab Acharya
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
Tally software_Introduction_Presentation
AditiBansal54083
 
Ad

C Programming with oops Concept and Pointer

  • 2. Program Structure • The first line of the program #include <stdio.h> is a preprocessor command, which tells a C compiler to include stdio.h file before going to actual compilation. • The next line int main() is the main function where the program execution begins. • The next line /*...*/ will be ignored by the compiler and it has been put to add additional comments in the program. So such lines are called comments in the program. • The next line printf(...) is another function available in C which causes the message "Hello, World!" to be displayed on the screen. • The next line return 0; terminates the main() function and returns the value 0. #include <stdio.h> int main() { /* my first program in C */ printf("Hello, World! n"); return 0; }
  • 4. Variables Variables are containers for storing data values. 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
  • 5. Declaring (Creating) Variables • To create a variable, specify the type and assign it a value: • Syntax • type variableName = value; • Example • int a = 10; • float b = 10.5;
  • 6. 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, you must use the format specifier %d or %i surrounded by double quotes, inside the printf() function: •Example • int myNum = 15; printf("%d", myNum); // Outputs 15
  • 7. 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
  • 9. Data Types Data Type Size Description Format Specifier int 2 or 4 bytes Stores whole numbers, without decimals %d float 4 bytes Stores fractional numbers, containing one or more decimals. Sufficient for storing 7 decimal digits %f double 8 bytes Stores fractional numbers, containing one or more decimals. Sufficient for storing 15 decimal digits %lf char 1 byte Stores a single character/letter/number, or ASCII values %c
  • 11. Constants • When you don't want others (or yourself) to override existing variable values, use the const keyword (this will declare the variable as "constant", which means unchangeable and read-only) • const int myNum = 15; // myNum will always be 15 myNum = 10; // error: assignment of read-only variable 'myNum’ • Notes On Constants • When you declare a constant variable, it must be assigned with a value: • Example • Like this: • const int minutesPerHour = 60; • This however, will not work: • const int minutesPerHour; minutesPerHour = 60; // error
  • 13. Operators • Operators are used to perform operations on variables and values. • In the example below, we use the + operator to add together two values: • Example • int myNum = 100 + 50; • C divides the operators into the following groups: • Arithmetic operators • Assignment operators • Comparison operators • Logical operators • Bitwise operators
  • 14. Arithmetic Operators Operator Name Description Example + Addition Adds together two values x + y - Subtraction Subtracts one value from another x - y * Multiplicati on 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
  • 15. Assignment Operators Assignment operators are used to assign values to variables. Example int x = 10; 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
  • 16. Comparison Operators Operator Name Example == Equal to x == y != Not equal x != y > Greater than x > y < Less than x < y >= Greater than or equal to x >= y <= Less than or equal to x <= y • Comparison operators are used to compare two values. • Note: The return value of a comparison is either true (1) or false (0).
  • 17. Logical Operators • Logical operators are used to determine the logic between variables or values: Operator Name Description Example && Logical and Returns true if both statements are true x < 5 && x < 10 || Logical or Returns true if one of the statements is true x < 5 || x < 4 ! Logical not Reverse the result, returns false if the result is true !(x < 5 && x < 10)
  • 18. Sizeof Operator • The memory size (in bytes) of a data type or a variable can be found with the sizeof operator: •Example int myInt; float myFloat; double myDouble; char myChar; printf("%lun", sizeof(myInt)); printf("%lun", sizeof(myFloat)); printf("%lun", sizeof(myDouble)); printf("%lun", sizeof(myChar));
  • 20. Decision Making C has the following conditional statements: •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
  • 21. The if Statement • Use the if statement to specify a block of C code to be executed if a condition is true. Syntax if (condition) { // block of code to be executed if the condition is true } • Example • if (20 > 18) { printf("20 is greater than 18"); } Output: 20 is greater than 18
  • 22. The else Statement Use the else statement to specify a block of code to be executed if the condition is false. Syntax if (condition) { // block of code to be executed if the condition is true } else { // block of code to be executed if the condition is false } • Example • if (20 > 18) { printf(“It is true"); } else{ printf(“It is false”); } Output: It is true
  • 23. The else if Statement Use the else if statement to specify a new condition if the first condition is false. Syntax if (condition1) { // block of code to be executed if condition1 is true } else if (condition2) { // block of code to be executed if the condition1 is false and condition2 is true } else { // block of code to be executed if the condition1 is false and condition2 is false }
  • 24. • Example • int time = 22; if (time < 10) { printf("Good morning."); } else if (time < 20) { printf("Good day."); } else { printf("Good evening."); }
  • 25. Switch Instead of writing many if..else statements, you can use the switch statement. The switch statement selects one of many code blocks to be executed: Syntax switch(expression) { case x: // code block break; case y: // code block break; default: // code block } This is how it works: •The switch expression is evaluated once •The value of the expression is compared with the values of each case •If there is a match, the associated block of code is executed •The break statement breaks out of the switch block and stops the execution •The default statement is optional, and specifies some code to run if there is no case match
  • 26. • Example • int day = 4; switch (day) { case 1: printf("Monday"); break; case 2: printf("Tuesday"); break; case 3: printf("Wednesday") ; break; case 4: printf("Thursday"); break; case 5: printf("Friday"); break; case 6: printf("Saturday"); break; case 7: printf("Sunday"); break; }
  • 27. The break Keyword When C reaches a break keyword, it breaks out of the switch block. This will stop the execution of more code and case testing inside the block. When a match is found, and the job is done, it's time for a break. There is no need for more testing. The default Keyword The default keyword specifies some code to run if there is no case match
  • 29. Looping Statement • Loops can execute a block of code as long as a specified condition is reached. • Loops are handy because they save time, reduce errors, and they make code more readable. • While • Do While • For
  • 30. While The while loop loops through a block of code as long as a specified condition is true: Syntax while (condition) { // code block to be executed } • Example • int i = 0; while (i < 5) { printf("%dn", i); i++; }
  • 31. Do While The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true. • Syntax • do { // code block to be executed } while (condition); • Example • int i = 0; do { printf("%dn", i); i++; } while (i < 5);
  • 32. For When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop • Syntax • for (statement 1; statement 2; statement 3) { // code block to be executed } • Statement 1 is executed (one time) before the execution of the code block. • Statement 2 defines the condition for executing the code block. • Statement 3 is executed (every time) after the code block has been executed. • Example • int i; for (i = 0; i < 5; i++) { printf("%dn", i); }
  • 34. Arrays • Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. • To create an array, define the data type (like int) and specify the name of the array followed by square brackets []. • To insert values to it, use a comma-separated list, inside curly braces: • int myNumbers[] = {25, 50, 75, 100}; • We have now created a variable that holds an array of four integers.
  • 35. Access the Elements of an Array • To access an array element, refer to its index number. • Array indexes start with 0: [0] is the first element. [1] is the second element, etc. • This statement accesses the value of the first element [0] in myNumbers: • Example • int myNumbers[] = {25, 50, 75, 100}; printf("%d", myNumbers[0]);
  • 36. Change an Array Element • To change the value of a specific element, refer to the index number: • Example • myNumbers[0] = 33; • Example • int myNumbers[] = {25, 50, 75, 100}; myNumbers[0] = 33; printf("%d", myNumbers[0]);
  • 37. Loop Through an Array • You can loop through the array elements with the for loop. • The following example outputs all elements in the myNumbers array: • Example • int myNumbers[] = {25, 50, 75, 100}; int i; for (i = 0; i < 4; i++) { printf("%dn", myNumbers[i]); }
  • 38. Set Array Size • Another common way to create arrays, is to specify the size of the array, and add elements later: • Example • // Declare an array of four integers: int myNumbers[4]; // Add elements myNumbers[0] = 25; myNumbers[1] = 50; myNumbers[2] = 75; myNumbers[3] = 100;
  • 39. Multi-dimensional array • A multi-dimensional array can be termed as an array of arrays that stores homogeneous data in tabular form. Data in multidimensional arrays are stored in row-major order. • The general form of declaring N-dimensional arrays is: • data_type array_name[size1][size2]....[sizeN]; •data_type: Type of data to be stored in the array. •array_name: Name of the array •size1, size2,… ,sizeN: Sizes of the dimension • Examples: • Two dimensional array: int two_d[10][20]; Three dimensional array: int three_d[10][20][30];
  • 40. 2-D Array • Initializing Two – Dimensional Arrays: There are various ways in which a Two-Dimensional array can be initialized. • First Method: • int x[3][4] = {0, 1 ,2 ,3 ,4 , 5 , 6 , 7 , 8 , 9 , 10 , 11} • The above array has 3 rows and 4 columns. The elements in the braces from left to right are stored in the table also from left to right. The elements will be filled in the array in order, the first 4 elements from the left in the first row, the next 4 elements in the second row, and so on.
  • 41. • Second Method: • int x[3][4] = {{0,1,2,3}, {4,5,6,7}, {8,9,10,11}}; • Third Method: int x[3][4]; for(int i = 0; i < 3; i++){ for(int j = 0; j < 4; j++){ scanf(“%d”, x[i][j]); } }
  • 43. Structures (structs) • Structures (also called structs) are a way to group several related variables into one place. Each variable in the structure is known as a member of the structure. • Unlike an array, a structure can contain many different data types (int, float, char, etc.).
  • 44. Create a Structure • You can create a structure by using the struct keyword and declare each of its members inside curly braces: • struct MyStructure { // Structure declaration int myNum; // Member (int variable) char myLetter; // Member (char variable) }; // End the structure with a semicolon • To access the structure, you must create a variable of it. • Use the struct keyword inside the main() method, followed by the name of the structure and then the name of the structure variable: • Create a struct variable with the name "s1": • struct myStructure { int myNum; char myLetter; }; int main() { struct myStructure s1; return 0; }
  • 45. Access Structure Members To access members of a structure, use the dot syntax (.): Example // Create a structure called myStructure struct myStructure { int myNum; char myLetter; }; int main() { // Create a structure variable of myStructure called s1 struct myStructure s1; // Assign values to members of s1 s1.myNum = 13; s1.myLetter = 'B'; // Print values printf("My number: %dn", s1.myNum); printf("My letter: %cn", s1.myLetter); return 0; }
  • 46. What About Strings in Structures? • Remember that strings in C are actually an array of characters, and unfortunately, you can't assign a value to an array like this: • Example • struct myStructure { int myNum; char myLetter; char myString[30]; // String }; int main() { struct myStructure s1; // Trying to assign a value to the string s1.myString = "Some text"; // Trying to print the value printf("My string: %s", s1.myString); return 0; }
  • 47. Solution • However, there is a solution for this! You can use the strcpy() function and assign the value to s1.myString, like this: • Example • struct myStructure { int myNum; char myLetter; char myString[30]; // String }; int main() { struct myStructure s1; // Assign a value to the string using the strcpy function strcpy(s1.myString, "Some text"); // Print the value printf("My string: %s", s1.myString); return 0; }
  • 48. Simpler Syntax • You can also assign values to members of a structure variable at declaration time, in a single line. • Just insert the values in a comma-separated list inside curly braces {}. Note that you don't have to use the strcpy() function for string values with this technique: • Example • // Create a structure struct myStructure { int myNum; char myLetter; char myString[30]; }; int main() { // Create a structure variable and assign values to it struct myStructure s1 = {13, 'B', "Some text"}; // Print values printf("%d %c %s", s1.myNum, s1.myLetter, s1.myString); return 0; }
  • 49. Copy Structures • You can also assign one structure to another. • In the following example, the values of s1 are copied to s2: • Example • struct myStructure s1 = {13, 'B', "Some text"}; struct myStructure s2; s2 = s1;
  • 50. Modify Values • If you want to change/modify a value, you can use the dot syntax (.). • And to modify a string value, the strcpy() function is useful again: • Example • struct myStructure { int myNum; char myLetter; char myString[30]; }; int main() { // Create a structure variable and assign values to it struct myStructure s1 = {13, 'B', "Some text"}; // Modify values s1.myNum = 30; s1.myLetter = 'C'; strcpy(s1.myString, "Something else"); // Print values printf("%d %c %s", s1.myNum, s1.myLetter, s1.myString); return 0; }
  • 51. • Example • struct Car { char brand[50]; char model[50]; int year; }; int main() { struct Car car1 = {"BMW", "X5", 1999}; struct Car car2 = {"Ford", "Mustang", 1969}; struct Car car3 = {"Toyota", "Corolla", 2011}; printf("%s %s %dn", car1.brand, car1.model, car1.year); printf("%s %s %dn", car2.brand, car2.model, car2.year); printf("%s %s %dn", car3.brand, car3.model, car3.year);