0% found this document useful (0 votes)
6 views16 pages

CP training notes

The document provides an introductory guide to the C programming language, covering its history, importance, and basic concepts such as variables, data types, operators, and control structures. It explains how to set up a C environment, create a simple program, and utilize comments, conditionals, and loops. Additionally, it discusses variable declaration, type conversion, and the use of constants, along with examples for clarity.

Uploaded by

dheerajnamdev
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)
6 views16 pages

CP training notes

The document provides an introductory guide to the C programming language, covering its history, importance, and basic concepts such as variables, data types, operators, and control structures. It explains how to set up a C environment, create a simple program, and utilize comments, conditionals, and loops. Additionally, it discusses variable declaration, type conversion, and the use of constants, along with examples for clarity.

Uploaded by

dheerajnamdev
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
You are on page 1/ 16

Training content for the first 3 Days…

What is C?
C is a general-purpose programming language created by Dennis Ritchie at the
Bell Laboratories in 1972.

It is a very popular language, despite being old. The main reason for its
popularity is because it is a fundamental language in the field of computer
science.

Why Learn C?
 It is one of the most popular programming languages in the world
 If you know C, you will have no problem learning other popular
programming languages such as Java, Python, C++, C#, etc, as the syntax
is similar
 C is very fast, compared to other programming languages,
like Java and Python
 C is very versatile; it can be used in both 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++ supports classes and
objects, while C does not.

Get Started With C


To start using C, you need two things:

 A text editor, like Notepad, to write C code


 A compiler, like GCC, to translate the C code into a language that the
computer will understand

There are many text editors and compilers to choose from.

C Quickstart
Let's create our first C file.

Open Codeblocks and go to File > New > Empty File.

#INCLUDE <STDIO.H>

INT MAIN() {
PRINTF("HELLO WORLD!");
RETURN 0;
}COMMENTS IN C

Comments can be used to explain code, and to make it more readable. It can
also be used to prevent execution when testing alternative code.

Comments can be singled-lined or multi-lined.

SINGLE-LINE COMMENTS

Single-line comments start with two forward slashes (//).

Any text between // and the end of the line is ignored by the compiler (will not
be executed).

This example uses a single-line comment before a line of code:

C MULTI-LINE COMMENTS

Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by the compiler:

EXAMPLE
/* The code below will print the words Hello World!
to the screen, and it is amazing */
printf("Hello World!");

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'. Characters 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;

// DECLARE A VARIABLE
INT MYNUM;

// ASSIGN A VALUE TO THE VARIABLE


MYNUM = 15;

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

EXAMPLE
// Create variables
int myNum = 15; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
char myLetter = 'D'; // Character

// Print variables
printf("%d\n", myNum);
printf("%f\n", myFloatNum);
printf("%c\n", myLetter);

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);

C VARIABLE NAMES

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:

DATA TYPES

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("%d\n", myNum);
printf("%f\n", myFloatNum);
printf("%c\n", myLetter);

BASIC DATA TYPES

The data type specifies the size and type of information the variable will store.

Data Type Size Description Example

int 2 or 4 bytes Stores whole numbers, 1


without decimals
float 4 bytes Stores fractional 1.99
numbers, containing one
or more decimals.
Sufficient for storing 6-7
decimal digits

double 8 bytes Stores fractional 1.99


numbers, containing one
or more decimals.
Sufficient for storing 15
decimal digits

char 1 byte Stores a single 'A'


character/letter/number,
or ASCII values

In this tutorial, we will focus on the most basic ones:

THE CHAR TYPE

The char data type is used to store a single character.

The character must be surrounded by single quotes, like 'A' or 'c', and we use
the %c format specifier to print it:

EXAMPLE
char myGrade = 'A';
printf("%c", myGrade);
NUMERIC TYPES

Use int when you need to store a whole number without decimals, like 35 or
1000, and float or double when you need a floating point number (with
decimals), like 9.99 or 3.14515.

INT
int myNum = 1000;
printf("%d", myNum);

TYPE CONVERSION

Sometimes, you have to convert the value of one data type to another type. This
is known as type conversion.

For example, if you try to divide two integers, 5 by 2, you would expect the
result to be 2.5. But since we are working with integers (and not floating-point
values), the following example will just output 2:

EXAMPLE
int x = 5;
int y = 2;
int sum = 5 / 2;
printf("%d", sum); // Outputs 2

There are two types of conversion in C:

 Implicit Conversion (automatically)


 Explicit Conversion (manually

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 type:

EXAMPLE
// Automatic conversion: int to float
float myFloat = 9;

printf("%f", myFloat); // 9.000000

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:

EXAMPLE
// Manual conversion: int to float
float sum = (float) 5 / 2;

printf("%f", sum); // 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
const int myNum = 15; // myNum will always be 15
myNum = 10; // error: assignment of read-only variable 'myNum'

C divides the operators into the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Bitwise operators

Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations.

Operator Name Description Example

+ Addition Adds x+y


together
two values

- Subtraction Subtracts x-y


one value
from
another

* Multiplication Multiplies x*y


two values

/ Division Divides one x / y


value by
another

% Modulus Returns the x%y


division
remainder

++ Increment Increases ++x


the value of
a variable
by 1

-- Decrement Decreases --x


the value of
a variable
by 1

CONDITIONS AND IF STATEMENTS

You have already learned that C supports the usual logical conditions from
mathematics:

 Less than: a < b


 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b
 Equal to a == b
 Not Equal to: a != b

You can use these conditions to perform different actions for different
decisions.

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 code to be executed if a condition


is true.

SYNTAX
if (CONDITION) {
// block of code to be executed if the condition is true
}
In the example below, we test two values to find out if 20 is greater than 18. If
the condition is true, print some text:

EXAMPLE
if (20 > 18) {
printf("20 is greater than 18");
}

SWITCH STATEMENT

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
The example below uses the weekday number to calculate the weekday name:

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;
}

// Outputs "Thursday" (day 4)

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:

LOOPS

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 LOOP

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
}

In the example below, the code in the loop will run, over and over again, as long
as a variable (i) is less than 5:

EXAMPLE
int i = 0;

while (i < 5) {
printf("%d\n", i);
i++;
}

THE DO/WHILE LOOP


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);

The example below uses a do/while loop. The loop will always be executed at
least once, even if the condition is false, because the code block is executed
before the condition is tested:

EXAMPLE
int i = 0;

do {
printf("%d\n", i);
i++;
}
while (i < 5);

FOR LOOP

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 (expression 1; expression 2; expression 3) {
// code block to be executed
}

Expression 1 is executed (one time) before the execution of the code block.

Expression 2 defines the condition for executing the code block.


Expression 3 is executed (every time) after the code block has been executed.

The example below will print the numbers 0 to 4:

EXAMPLE
int i;

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


printf("%d\n", i);
}

NESTED LOOPS

It is also possible to place a loop inside another loop. This is called a nested
loop.

The "inner loop" will be executed one time for each iteration of the "outer
loop":

EXAMPLE
int i, j;

// Outer loop
for (i = 1; i <= 2; ++i) {
printf("Outer: %d\n", i); // Executes 2 times

// Inner loop
for (j = 1; j <= 3; ++j) {
printf(" Inner: %d\n", j); // Executes 6 times (2 * 3)
}
}

C BREAK AND CONTINUE

BREAK

You have already seen the break statement used in an earlier chapter of this
tutorial. It was used to "jump out" of a switch statement.
The break statement can also be used to jump out of a loop.

This example jumps out of the for loop when i is equal to 4:

EXAMPLE
int i;

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


if (i == 4) {
break;
}
printf("%d\n", i);
}

CONTINUE

The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.

This example skips the value of 4:

EXAMPLE
int i;

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


if (i == 4) {
continue;
}
printf("%d\n", i);
}

Happy Coding

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy