[go: up one dir, main page]

0% found this document useful (0 votes)
4 views20 pages

Introduction to C

The document provides an introduction to the C programming language, covering basic concepts such as output generation using the printf function, program structure with the main function, and variable declaration and assignment. It explains data types, arithmetic operations, and the use of comments, conditionals, and loops in programming. Additionally, it highlights important programming practices and syntax rules essential for writing C code.

Uploaded by

nafiskhan022107
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)
4 views20 pages

Introduction to C

The document provides an introduction to the C programming language, covering basic concepts such as output generation using the printf function, program structure with the main function, and variable declaration and assignment. It explains data types, arithmetic operations, and the use of comments, conditionals, and loops in programming. Additionally, it highlights important programming practices and syntax rules essential for writing C code.

Uploaded by

nafiskhan022107
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/ 20

Introduction to C​

Basic concepts :​

Introducing C:​
C has been used to write everything from operating systems (including Windows and
many others) to complex programs like Python interpreter, Git, Oracle database, and
more.​

Output :​
Most computer programs are designed to produce outputs. Here some examples:​

- “You’ve got a new message” notifications.​
- “Game over” displayed on the screen when playing video games.​
- Your account balance when checking your online banking app.​

The simplest output consists of displaying a message on the screen.​

printf(“Hello’);

Lesson Takeaways :
Important points:​

1.​ You can write code that generates outputs with the printf function.
2.​ printf needs to include the text that you want to output inside parentheses.
3.​ A line of code is called a statement. A statement performs a specific task.
4.​ Each statement in C needs to end with a semicolon (;).
5.​ Text needs to be enclosed in double quotes.

Program Structure :​
The first line of the code adds the <stdio.h> header file to the program.​

#include <sdio.h>


A header is a file that contains functions and commands.​
The <stdio.h> header contains the printf function, that we used for outputting text. This
is why we need to include it in our program, to enable us to use the printf function.

[N.B: The #include command is used to add a header file to the program. # This
symbol is necessary.]

Each C program has an entry point, or starting point, which is a function called main.

Curly brackets {} indicates the beginning and the end of a function, which can also be
called the function’s body. The code inside the brackets indicates what the function
does when executed.​

int main() {
printf(“Hello’);​
return 0;​
}

When we run the code, the printf command will be executed, as it's inside the main()
function.

The last statement of the main() function is return 0; ​


It indicates that our program has successfully completed.

The main() function can contain a lot of statements, doing different things.​
As a example:​

#include <stdio.h>

int main() {
printf(“First”);
printf(“Second”);​
return 0;​
}

Lesson Takeaways :
Important points:​

1.​ The #include statement is used to add a header file to the program.
2.​ To use the printf command, you need to include the <stdio.h> header.
3.​ The starting point of C programs is the function called main, which includes the
code that you want to run inside curly brackets.
4.​ The last statement of the main() function is return 0; , which indicates the
successful completion of the program.

Output Formatting :
Numbers :​
The printf function supports special format specifiers, which allow output numbers and
output formatting.

printf(“%d”, 253);

%d is the format specifier, which denotes that a whole number is expected. The value of
the number is given after a comma in printf .

[N.B: <b>%d</b> is replaced with the given value in the output.]

printf(“%f”, 3.14);

There are a number of format specifiers you can use.

%f is used to output floating point numbers.


%c denotes a single character, while %s is used for strings.

printf(“%c”, ‘X’);

Single characters need to be enclosed in single quotes, while strings use double
quotes.

A great feature of the format specifiers is that you can use a combination of multiple
specifiers and text in the printf() function. Example:​

printf(“Score: %f. Level: %d”,42.8,4);

Each format specifier is replaced by the corresponding value, provided to printf()


separated by commas. This is really handy, as you can format your output anyway you
like.

printf() does not add a new life after output. This means that when you use multiple
printf() statements, they will get printed on the same line.​

The special character \n is used to create a new line in the output. You can use as many
\n characters as you need.

Lesson Takeaways :
Important points :​

1.​ You can use format specifiers in printf(), to insert different values in the given
positions. ​

. %d is for whole numbers


. %f is for floating points numbers
. %c is for single characters
. %s is for strings
2.​ You can combine multiple format specifiers in a single printf() statement.
Remember to provide the corresponding values for each specifier, separated by
commas.
3.​ \n is a special character used to insert a new line into the output.

Variables :
Every program works with values.
A variable lets you store a value by assigning it to a name. The name can be used to
refer to the value later in the program.

Every variable has a type, which defines the type of the value it holds. A variable can
hold a text value, a number, a decimal, etc.

int score;

int is the type that stores whole numbers, or as we call them in programming integers.

[ In the programming terms, the process of creating a variable is called


declaration. ]

After declaring our variable, we can assign it a value using the assignment = operator. ​

int score;
score = 253;
Now, the score holds the value 253.

Now, after declaring and assigning a value, we can output the value of our variable

#include <stdio.h>

int main() {
int score;
score = 253;
printf(“%d”, score);​
return 0;​
}
We used the %d format specifier, as score is an integer, and passed score to the printf
function as the value to be inserted.

We can combine the declaration and assignment into one statement, like this:

#include <stdio.h>

int main() {
int score = 253;
printf(“%d”, score);​
return 0;​
}
This is handy when we already know the value for our variable and makes it shorter and
more readable.
A variable can change its value during the program multiple times. For example, the
score can change during a game.

Lesson Takeaways :
Important points:​

1.​ A variable has a name and a type of the value it holds.


2.​ To declare a variable use the type followed by the name of the variable.
3.​ The int type is used to store whole numbers.
4.​ You can assign a value to the declared variable using the = operator.
5.​ A variable can change its value during the program, by being assigned to a new
value.

Data Types :
Variables need to have their data type, which defines the type of the value they store.
We have seen the int data type in the previous examples, used to store whole
numbers.​
#include <stdio.h>

int main() {
int score = 253;
printf(“Score: %d”, score);​
return 0;​
}
Decimals :
To store decimals (or floating point numbers), C provides the float and double data
types.

#include <stdio.h>

int main() {
float height = 61.5;
printf(“%f”,height);​
return 0;​
}
[The format specifier for floats is %f ]

The double data type is also used to store decimals.

#include <stdio.h>

int main() {
double temp = 61.5;
printf(“%lf”,height);​
return 0;​
}

[The format specifier for floats is %lf ]


Float vs Double :
Float uses less storage in the memory, but is not as precise as the double type. This
means that calculations that use floats are faster than the ones that use double,
however the results are less accurate in terms of decimal digits.
Generally, float is sufficient for storing 7 decimal digits, while double can hold 15
decimal digits.

Char :
The char type is used to store a single character. It is similar to declaring a string, but
uses single quotes for the value.

#include <stdio.h>

int main() {
char letter = ‘X’;
printf(“%c”,letter);​
return 0;​
}

[The format specifier for the char type is %c ]

Constants :
Variables can be defined as constants. This means that they cannot be changed. To
define a constant, use the const keyword before the data type of the variable.
# include <stdio.h>
int main() {
const int num = 32;
printf(“%d”, num);​
return 0;​
}

Now, num is a constant, and its value is read-only.


Constant must be assigned a value when declared. Trying to declare it and then assign
a value using a separate statement will result in an error. Example:

const int num;


num = 32;
Lesson Takeaways :
Important points :

1.​ int is used to hold whole numbers


2.​ float and double store decimals.
3.​ float is similar to double, but has less precision and requires less memory.
4.​ char holds a single character.
5.​ The const keyword is used to define a constant, which is a variable that cannot
be changed (is read-only)

Doing Math :
You can use arithmetic operators to perform calculations.

# include <stdio.h>
int main() {
int x = 3;
int y = 6;
printf(“%d”, x+y);​
return 0;​
}

The result of a calculation can be assigned to another variable.

# include <stdio.h>
int main() {
int win = 6;
int lost = 3;
int score = win-lost;
printf(“%d”, score);​
return 0;​
}
Multiplication :
Multiplication is done using the * operator.

#include <stdio.h>
int main()
{
int width = 62;
int height = 53;
int area = width*height;
printf("%d", area);
return 0;
}
Division :
The division / operator performs differently depending on the data type of the operand.
When both operands are integers, integer division, (also called truncated division),
removes any remainder resulting in an integer.

#include <stdio.h>

int main()
{
int kb = 35265;
int mb = kb/5356;
printf("%d", mb);
return 0;
}
In case we want a more precise result, we can use float division.

float kb = 35265;
float mb = kb/5356;
printf("%f", mb);
Remainder :
The % remainder operator (also called the modulo) is used to find the remainder of a
division. Let’s find out how many of 100 items will be left over if we divide them into
boxes of 8.

#include <stdio.h>

int main()
{
int items = 100;
int per_box = 8;
int left_over = items%per_box;
printf("%d", left_over);
return 0;
}

Lesson Takeaways :
Important points :

1.​ + is addition
2.​ - is subtraction
3.​ / is division
4.​ Dividing integers results in an integer, while dividing floats results in a float.
5.​ % finds the remainder of a division.

Comments :
Comments are annotations in the code that explain what the code is doing. Code is for
computers, while comments are for humans who read and work with the code.

A single-line comment starts with two forward slashes and continues until it reaches
the end of the line. Example:

int main() {
// storing the age
int age = 43; // some demo value
printf(“%d”, age);

Adding comments as you write code is good practice, because they provide clarification
and understanding when you need to refer back to it, as well as for others who might
need to read it.
You can also comment out lines of code, in case they work in progress or you don’t
want to delete them yet.​

int main() {
int age = 43;
//age = 9;
printf(“%d”, age);
//printf(“Some demo program”);

The commented lines of code will get ignored when you run the program.
If you need to comment out multiple lines, or write a long, multi-line comment, you can
use the /**/ symbols.

int main() {
/* this is just a
demo program
that outputs a demo value */
int age = 12;
Anything between the /* and */ symbols becomes a comment.
Lesson Takeaways :
Important points :

1.​ Comments are explanatory statements that explain what the code is doing.
2.​ They can contain notes, todos as well as code that is work-in-progress.
3.​ // starts a single line comment.
4.​ /* */ is used for multi-line comments.

Conditionals & Loops :​

Taking Input:
Your programs may take user input. For example, these can be commands in a game,
or values for an app to process and generate the output.

The scanf() function is used to take user input based on the given format specifier. It
works similar to the printf() function.

#include <stdlib.h>

int main()
{
int num;
scanf("%d", &num);

printf("You entered: %d", num);


return 0;
}

We first declare the variable that will hold our input value. Then we use it in the scanf()
function.
[ The & sign before the variable name is the address operator. It gives
the address, or location in memory, of a variable. The scanf() function needs to use the
variable name with the & sign. ]
Multiple Inputs:
You can take multiple inputs throughout your program. For example let’s take two
integers as input and output their sum.​

int x, y;
scanf(“%d%d”, &x, &y);
printf(“%d”, x+y);
Variables:
Also note how we declare the variables: ​

int x, y;
In case the variables have the same type, you can declare them on a single line, by
separating them with commas.

Lesson Takeaways :
Important points :

1.​ First, declare a variable that will store the input. Then, use it in the scanf()
function. scanf() is similar to printf() it uses a format specifier to prompt the user
for the corresponding input.

2.​ Remember, you need to use the & sign before the variable name in the scanf()
function - it is used to get the address of the variable, which tells scanf() where
to store the given value.

3.​ It is important to use the correct type for the variable that will store the input.

Conditionals:

Decision Making:

Conditional statements are used to perform different actions based on different


conditions. For example, a game can choose the opponents based on the level of the
player, or a banking app can provide benefits based on the balance of the client.

The if statement allows you to run a specified code if a given condition holds.​

if(condition) {
//code to run​
}
[ The condition is enclosed in parentheses, and code of the if statement is enclosed in
curly bracket {} ]
If Statement:
The following comparison operators may be used to form the condition:

< less than​


> greater than
!= not equal to
== equal to
<= less than or equal to
>= greater than or equal to
For example:

int score = 142;


if(score >= 100);{
printf(“Level Complete!”);
}

The message will be output only if the condition is satisfied.

Remember that you need to use two equal signs (==) to test for equality, since a single
equal sign is the assignment operator.

int position = 1;
if(position == 1) {
printf("Gold!");
}

Else Statement:

You can use the else statement after an if statement, if you want to run a code in case
the condition is not satisfied.

#include <stdlib.h>

int main() {
int score = 56;
if(score >= 100) {
printf("Completed!");
}
else {
printf("Game Over");
}

return 0;
}
else if Statement:
In case you need to check for multiple different values, you can use else if statements.

int score = 50;


if(score == 100) {
printf("Completed!");
}
else if(score == 50){
printf("Passed");
}
else {
printf("Game Over");
}
You can include as many else if statements as you need.

Lesson Takeaways :
Now you know how to make decisions in your program.
You can check for a condition using the if statement.
In case the condition does not hold, the code in an else statement can be executed.

Switch:
The switch statement can be used to check for equality against a list of values, instead
of multiple else if statements.
int main() {
int position = 6;
switch(position) {
case 1:
printf("Gold");
break;
case 2:
printf("Silver");
break;
case 3:
printf("Bronze");
break;
default:
printf("No medal");
break;
}
return 0;
}
Each case has a value to compare with. When the switch variable’s value is equal to a
case value, the code inside it is executed, until a break statement is reached. Each
case has to have a value and a colon.

The break statement is used to terminate the switch, when the case it matched.
If you forget to add the break after each case, the program will continue to execute the
code in the next case statements, even if their value does not match the variable’s
value.

switch(position) {
case 1:
printf("Gold");
case 2:
printf("Silver");
case 3:
printf("Bronze");
default:
printf("No medal");
}
This type of behaviour is called fall-through. It usually occurs due to errors, when the
programmer forgets to add the break statements for each case.

There is a default case at the end of the switch statement. It is used to run code, when
none of the cases match.
No break is needed in the default case as it is always the last statement in the switch.

Lesson Takeaways:
The switch statement is a handy way to check for multiple values.

1.​ Remember, that each case is followed by a value and a colon.


2.​ Each case needs a break statement, or the code of the other cases will
continue to get executed, even if they do not match.
3.​ The default case can be used to run code if none of the cases match.

Combining Conditions:
In some scenarios we need to combine multiple conditions. Let’s say we want to check
that the age value is between 18 and 45.

int main() {
int age = 24;
if(age >= 18 && age <= 45) {
printf("ok");
}
return 0;
}
The && operator is also referred to as the logical AND operator.
OR:
The logical OR operator, written as || combines conditions. The code will run if any one
of the conditions is satisfied. For example:​

int balance = 24;
int level = 5;
if(balance > 1000 || level > 3) {
printf("Gold Tier");
}
NOT:​
The logical NOT operator ! reverses the condition.​

int balance = 24;


if(!(balance > 1000)){
printf("Very low");
}

!(balance > 1000) reads as “balance is not greater than 1000.”

You can chain multiple conditions using parentheses and the logical operators.
Example:​

int balance = 200;


int level = 8;
char type = 'V';
if(balance>1000 || (level>2 && type==’V' )){
printf("Welcome");
}

Lesson Takeaways:
Logical operators allow you to combine multiple conditions.

1.​ The AND operator && combines two conditions.


2.​ The OR operator || check if any of the conditions hold.
3.​ The NOT operator ! reverses the condition.
4.​ You can combine and chain conditions using parentheses and logical
operators.

Loops:
A Loop allows you to repeat a block of code multiple times. For example, a banking app
can loop through all transactions, or a shopping app can loop through all products in the
shopping cart to calculate the total.​

while Loop:
The while loop takes a condition and repeats its statement while the condition is
satisfied.

int num = 1;

while (num < 5){

printf("%d\n",num);

num = num + 1;

The statement num = num + 1 increases the value of num by 1 each time the loops
run. This is important, as without it the loop would run forever. The loop stops as soon
as the value of num reaches the value 5.

Increment & Decrement:​


As it’s common to increment and decrement a variable’s value by 1 in loops; C provides
special increment and decrement operators. For example num=num+1 can be
shortened to num++.

while (num < 6){

printf("%d\n",num);

num++;

Similarly, num-- will decrease the value of num by 1.​


Sometimes you might need to increase or decrease the value of a variable by a different
value than 1. For these cases, C provides shorthand operators, too! For example,
num=num+3 can be shortened to num+=3.​
Similarly there are shorthand operators for other mathematical operations, such as -=
for subtraction, *= for multiplication, etc.​

do while:
Another variation of the loop is do-while.
int x = 0;

do{

printf("%d\n",x);

x +=3;

}while (x > 10);

The difference with a while loop is that condition is checked after the code, meaning
the in the do is executed at least once, even if the condition is not satisfied. Also note
the semicolon after the while condition.

Lesson Takeaways
Here is a summary about the while loop:

1.​ The code in the while loop runs as long as the condition holds.
2.​ The ++ and -- operators are used to increase and decrease the value of
a variable by one.
3.​ C provides shorthand operators to perform mathematical operations on a
variable, for example num=num * 5 can be written as num *= 5.
4.​ The do-while loop is similar to a while loop, but it is guaranteed to run at
least once.

for loops:
Another loop structure is the for loop. It has the following form.

int main() {

for (int i=1; i<10; i++){

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

return 0;

This will output the numbers 1 to 9, each number on a new line.

The for loop has 3 components in the parentheses:

1.​ The first part runs once when we enter the loop and initializes the variable.
2.​ The second part is the condition of the loop.
3.​ The third part runs every time the loop runs.

Note the semicolon between the components.


You can have any type of condition and any type of increment statements in the for
loop.

for (int i=2; i<=100; i+=2){

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

Remember the break; statement that was used in switch to stop it when a case was
matched. It can also be used to stop a loop.

for (int i=1; i<10; i++){

if(i==5){

break;

printf("%d",i);

The loop will stop when i reaches the value 5.

continue:
The continue statement skips the current loop iteration and continues with the next
one.

for (int i=1; i<10; i++){

if(i==5){

continue;

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

This will skip the number 5 but will run until i reaches 10.

Lesson Takeaways:
Here is a summary:

1.​ The for loop has the following syntax:​


for(init; condition; increment){ //code }
2.​ The break statement can be used to stop a loop.
3.​ The continue statement can be used to skip the current iteration of the loop and
jump to the next one.

Arrays:​
Variables are great for storing and working with values. But what if we need to store
multiple similar values? For example, ages of a group of people. Instead of creating
separate variables for each person, we can use an array to store all values!

An array needs to be declared like a variable, with the type of the items it will hold.

int ages[7];

The name of the array is ages. It is created to hold 7 int values. Note the square
brackets [ ] after the name of the array.

int ages[7];​
ages[2]=24;​
ages[0]=31; ​
printf("%d", ages[2]); ​
return 0;

After declaring the array, we can access the items using their position, also called the
index.

The index is specified in square brackets, next to the array name.​


The item with index 2 is actually the 3rd item of the array. That’s because array indexes
start from 0, meaning that the first element’s index is 0 rather than 1.

The last item of the ages array will have the index 6, as it can hold 7 items.

int ages[7];​
ages[2]=24;​
ages[0]=31; ​
printf("%d", ages[2]); ​
return 0;

This will output the value of the 3rd item, as we used the 2nd index. Also make sure to
use the correct format specifier, when outputting values.

If u already know what values to store in the array, instead of assigning them one by
one, you can use the following syntax:

int ages[]={31,18,24,55,29};​
printf("%d", ages[2]);​
return 0;
Place the values in a comma-separated list, enclosed in curly braces. The code
above automatically creates an array containing 5 items, and stores the provided
values.

Note that in this case we do not need to specify the size of the array in the square
brackets.

Lesson Takeaways:
Arrays allow to store multiple values in a single variable.
To create an array, specify the item type and array size:

int cart[12];

Array items are accessed by their indexes in square brackets. The first item has the
index 0.​
You can also initialize an array with values using this syntax:

int nums[] = {1, 2, 3, 4};

Looping over Arrays:


We can use a loop to iterate over the items of an array. For example, let’s simply output
all the items using a for loop:

int ages[]={31,18,24,55,29};​
int i;​
for(i=0; i<5; i++){​
printf("%d\n", ages[i]);​
}​
return 0;

We used the i variable of the loop as the index for our array. During each iteration of the
loop it is incremented and used to access the corresponding item of the array.​
Note that we need to set the condition based on the size of the array,in out case there
are 5 elements so we used the condition i<5 in the loop, as i start from 0.

You might also like