You are on page 1of 50

Embedded system

Dr: sahar kamal


Basic c programming

Lecture 3
General Aspect of ‘C’
C was originally developed in the 1970s, by Dennis Ritchie at Bell
Telephone Laboratories, Inc.
C is a High level , general –purpose structured programming
language. Instructions of C consists of terms that are very closely
same to algebraic expressions, consisting of certain English
keywords such as if, else, for ,do and while
C contains certain additional features that allows it to be used at
a lower level , acting as bridge between machine language and
the high level languages.
This allows C to be used for system programming as well as for
applications programming
The Character set of ‘C’
C language consist of some characters set, numbers and
some special symbols. The character set of C consist of all the
alphabets of English language. C consist of
Alphabets a to z, A to Z
Numeric 0,1 to 9
Special Symbols {,},[,],?,+,-,*,/,%,!,;,and more
The words formed from the character set are building
blocks of C and are sometimes known as tokens. These
tokens represent the individual entity of language. The
following different types of token are used in C
1) Identifiers 2)Keywords 3)Constants
4) Operators 5)Punctuation Symbols
#include <stdio.h>

int main() {
printf("Hello World!");
return 0; #include <stdio.h>
}
int main() {
printf("Hello World!\n");
printf("I am learning C.");
return 0;
}
Try it Yourself

#include <stdio.h>

int main() {
printf("Hello World!");
printf("I am learning C.");
return 0;
}
Basic Data Types
The data type specifies the size and type of information the variable will store.
In this tutorial, we will focus on the most basic ones:

Data Type Size Description


int 2 or 4 bytes Stores whole numbers, without decimals
float 4 bytes Stores fractional numbers, containing one or more
decimals. Sufficient for storing 6-7 decimal digits
double 8 bytes Stores fractional numbers, containing one or more
decimals. Sufficient for storing 15 decimal digits
char 1 byte Stores a single character/letter/number, or ASCII values

const int BIRTHYEAR = 1980;


Basic Format Specifiers

There are different format specifiers for each data type. Here are
some of them

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
float myFloatNum = 3.5;
double myDoubleNum = 19.99;

printf("%f\n", myFloatNum); // Outputs 3.500000


printf("%lf", myDoubleNum); // Outputs 19.990000

float myFloatNum = 3.5;

printf("%f\n", myFloatNum); // Default will show 6 digits


after the decimal point
printf("%.1f\n", myFloatNum); // Only show 1 digit
printf("%.2f\n", myFloatNum); // Only show 2 digits
printf("%.4f", myFloatNum); // Only show 4 digits

\\ casting
int num1 = 5;
int num2 = 2;
float sum = (float) num1 / num2;

printf("%f", sum); // 2.500000


Operators in C:An operator is a symbol which operates on a value or a
variable. For example: + is an operator to perform addition.

C programming has wide range of operators to perform various


operations. For better understanding of operators, these
operators can be classified as:
• Arithmetic Operators
• Increment and Decrement Operators
• Assignment Operators
• Relational Operators
• Logical Operators
• Conditional Operators
• Bitwise Operators
• Special Operators
Arithmetic Operators
Arithmetic operators are used to perform common mathematical
operations.

Operator Name Description Example

+ Addition Adds together two values x+y

- Subtraction Subtracts one value from another x-y

* Multiplication 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


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
:

A list of all 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


Logical Operators

You can also test for true or false values with logical operators.
Logical operators are used to determine the logic between variables
or values:

Operator Name Description Example


&& Logical and Returns true if both x < 5 && x < 10
statements are true
|| Logical or Returns true if one of the x < 5 || x < 4
statements is true
! Logical not Reverse the result, returns !(x < 5 && x < 10)
false if the result is true
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("%lu\n", sizeof(myInt));
printf("%lu\n", sizeof(myFloat));
printf("%lu\n", sizeof(myDouble));
printf("%lu\n", sizeof(myChar));
int x = 10;
int y = 9;
printf("%d", x > y);

printf("%d", 10 == 10); // Returns 1 (true), because 10 is equal to


10
printf("%d", 10 == 15); // Returns 0 (false), because 10 is not
equal to 15
printf("%d", 5 == 55); // Returns 0 (false) because 5 is not equal
to 55
Identifiers

• A 'C' program consist of two types of elements , user defined


and system defined. Idetifiers is nothing but a name given to
these eleme
• nts.
• An identifier is a word used by a programmer to name a
variable , function, or label.
• identifiers consist of letters and digits, in any order, except that
the first charecter or lable.
• Identifiers consist of letters and digits if any order,except that
the first charecter must be letter.
• Both Upper and lowercase letters can be used
Keywords
• Keywords are nothing but auto double int struct
system defined identifiers.
• Keywords are reserved words break else long switch
of the language.
case enum register typedef
• They have specific meaning in
the language and cannot be
char extern return union
used by the programmer as
variable or constant names
const float short unsigned
• C is case senitive, it means these
must be used as it is continue for signed void
• 32 Keywords in C Programming
default goto sizeof volatile

do if static while
Variables

• A variable is nothing but a name given to a storage area that our programs can
manipulate. Each variable in C has a specific type, which determines the size and
layout of the variable's memory; the range of values that can be stored within that
memory; and the set of operations that can be applied to the variable.
• The name of a variable can be composed of letters, digits, and the underscore
character. It must begin with either a letter or an underscore. Upper and lowercase
letters are distinct because C is case-sensitive. There are following basic variable
types −
Type Description
• char Typically a single octet(one byte). This is an integer type.
• int The most natural size of integer for the machine.
• float A single-precision floating point value.
• double A double-precision floating point value.
• void Represents the absence of type.
Constants

• A constant is a value or an identifier whose value cannot be altered


in a program. For example: 1, 2.5,
• As mentioned, an identifier also can be defined as a constant. eg.
const double PI = 3.14
• Here, PI is a constant. Basically what it means is that, PI and 3.14 is
same for this program.

Integer constants
• A integer constant is a numeric constant (associated with number)
without any fractional or exponential part. There are three types of
integer constants in C programming:

• decimal constant(base 10)


• octal constant(base 8)
• hexadecimal constant(base 16)
Constants

Floating-point constants
• A floating point constant is a numeric constant that has either a
fractional form or an exponent form. For example:
2.0,0.0000234,-0.22E-5

Character constants
• A character constant is a constant which uses single quotation
around characters. For example: 'a', 'l', 'm', 'F'

String constants
• String constants are the constants which are enclosed in a pair
of double-quote marks. For example: "good" ,"x","Earth is
round\n"
Escape Sequences

Sometimes, it is necessary to use characters which cannot be typed or has special


meaning in C programming. For example: newline(enter), tab, question mark etc. In
order to use these characters, escape sequence is used.
• For example: \n is used for newline. The backslash ( \ ) causes "escape" from the
normal way the characters are interpreted by the compiler.Escape
Sequences Character
• \b Backspace
• \f Form feed
• \n Newline
• \r Return
• \t Horizontal tab
• \v Vertical tab
• \\ Backslash
• \' Single quotation mark
• \" Double quotation mark
• \? Question mark
• \0 Null character
Rules for defining variables
• A variable can have alphabets, digits,
and underscore.
• A variable name must start with
analphabet, and underscore only. It can't start with a
digit.
• No whitespace is allowed within
the variable name.
• A variable name must not be any reserved word or
keyword, e.g. int, float, etc.
• Valid variable names:
int a; int _ab; int a30;
• Invalid variable names:
int 2; int a b; int long; 12
C-language program a
general structure

1 Calling header file #include <stdio.h>


s2Main function main()
3Starting brace {
4Variable(s) declaration int a;
5Executable statement printf () etc
(s) }
6 Closing brace
23
/* To Print a message */ #include
<stdio.h> main()
{

printf ("Hello C Programming\


n");
}
Output

Hello C Programming 24
printf() functio
n
• The printf() function is used for output. It
prints the given statement to the console, defined
in stdio.h (header file).. The syntax of printf()
function is given below:
printf("format string", argument_list);
• The format string can be
%d for integer, %f for floating point number,
%c for single character, %s for a string etc.
25
scanf() functio
n
• The scanf() function is used for input ,
defined in stdio.h (header file). It reads the input
data from the console.
scanf("format string", &argument_list);
• The format string can b
%d for integer, %f for floating point number,
%c for single character, %s for a string etc.
26
/* Program to print cube of given number
*/
#include<stdio.h> main()
{
int number, cube; printf("enter a number:");
scanf("%d",&number);
cube=number*number*number; printf(“ cube
of number is:%d “ cube,);
}

Output
enter a number:5 cube of number is:125

27
• The scanf("%d",&number) statement reads integer
number from the console and stores the given value in
number variable.

• The printf("cube of number is : %d", cube)


statement prints the cube of number on the console.

28
/* Program to print sum of 2 integer numbers
*/
#include<stdio.h> main()
{
int x=0,y=0,result;
printf("enter first number:");
scanf("%d",&x);
printf("enter second number:");
scanf("%d",&y);
result=x+y;
printf("sum of 2 numbers:%d ",result);
}
29
Output
enter first number:19 enter second number:11 sum of 2 numbers:30
If-else Statemen
t

• The if-else statement in C is used to perform th


e
operations based on some specific condition. The operations
specified in if block are executed if and only if the given
condition is true.
•There are the following variants of if statement in C
language.
 if statement
 if-else statement
 If-else-if ladder
 Nested if
30
if Statement
The if statement is used to check some given condition and
perform some operations depending upon the correctness
of that condition. It is mostly used in the scenario where
we need to perform the different operations for the
different conditions. The syntax of the if statement is
given below.
if(expression) if (a>b)
{ {
executable statement printf (“a is larg
(s); e”);
} }
31
#include<stdio.h> main()
{
int a, b; printf("enter a:");
scanf("%d",&a);
printf("enter b:");
scanf("%d",&b);
if(a>b)
{
printf(“a is large”);
}
}
-------
Output
•enter a:14 enter b: 12 a is large
•enter a:19 enter b: 25

32
if-else Statemen
• t is used to perform two
The if-else statement operations for a
single condition. The if-else statement is an extension to the if
statement using which, we can perform two different
operations, i.e., one is for the correctness of that condition, and
the other is for the incorrectness of the condition. The syntax
of the if-else statement is given below.
• if(expression)
{ executable statement 1;
}
Else
{ executable statement 2;
}

23
#include<stdio.h>
main()
{ int a, b;
printf("enter a:"); scanf("%d",&a);
printf("enter b:"); scanf("%d",&b);
if(a>b)
{
printf(“a is larg
e”);
}
else
{
printf(“b is larg
e”);
}
}
enter a:14 enter b: 1 a is large
--------- 2
34
---- enter a:19 enter b: 2 b is large
Outpu 5
t
#include <stdio.h> main()
{ int age;
printf("Enter your age?");
if(age>=18) scanf("%d",&ag
e);
{ printf("You are eligible to vot
e..."); }
else
{ printf(“You are not eligible t
o vote..."); }
}
-----
Output 35

•Enter your age?28 You are eligible to vote...


•Enter your age?13 You are not eligible to vo
te....
if-else-if ladder Stateme
nt
The if-else-if statement is an extension to the if-else
statement. It is used in the scenario where there are
multiple cases to be performed for different conditions. In
if-else-if ladder statement, if a condition is true then the
statements defined in the if block will be executed,
otherwise if some other condition is true then the
statements defined in the else-if block will be executed,
at the last if none of the condition is true then the
statements defined in the else block will be executed.

36
Syntax of if-else-if statemen
t
if(condition1)
{
executable statements 1;
}
else if(condition2)
{
executable statements 2;
}
else if(condition3)
{
executable statements 3 ;
}
...
else
{
executable statements last;
37
}
Program to prepare the result of the stude
nt
#include <stdio.h>
main()
{ int marks;
printf("Enter your marks?"); scanf("%d",&marks);
if(marks >=600)
{ printf("Congrats ! you are place in the FIRST CLASS"); }
else if (marks >=500)
{ printf("You are placed in the SECOND CLASS"); }
else if (marks >= 400 )
{ printf("You are placed in the THIRD CLASS"); else }

{ printf("Sorry you FAILED"); }


}
Output
Enter your marks?31 Sorry You FAILED
Enter your marks?478 You are placed in THIRD CLASS
Enter your marks?545 You are placed in SECOND CLASS 38
Enter your marks?726 Congrats ! you are place in the FIRST CLASS
Switch

• switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
int day = 4;

switch (day) {
case 6:
printf("Today is Saturday");
break;
case 7:
printf("Today is Sunday");
break;
default:
printf("Looking forward to the Weekend");
}

// Outputs "Looking forward to the Weekend"


Loop

• while (condition) {
// code block to be executed
}
• int i = 0;

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

• do {
// code block to be executed
}
while (condition);

• int i = 0;

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

• for (statement 1; statement 2; statement 3) {


// code block to be executed
}

• int i;

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


printf("%d\n", i);
}
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)
}
}
Break& continue

• int i; • int i;

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


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

Example Explained
•myFunction() is the name of the function
•void means that the function does not have a return value. You will learn
more about return values later in the next chapter
•Inside the function (the body), add code that defines what the function
should do
• void myFunction() {
// code to be executed
}
• // Create a function
void myFunction() {
printf("I just got executed!");
}
int main() {
myFunction(); // call the function
return 0;
}
void myFunction() {
printf("I just got executed!");
}

int main() {
myFunction();
myFunction();
myFunction();
return 0;
}

// I just got executed!


// I just got executed!
// I just got executed!
void myFunction(char name[]) {
printf("Hello %s\n", name);
}

int main() {
myFunction("Liam");
myFunction("Jenny");
myFunction("Anja");
return 0;
}

// Hello Liam
// Hello Jenny
// Hello Anja
void myFunction(char name[], int age) {
printf("Hello %s. You are %d years old.\n", name, age);
}

int main() {
myFunction("Liam", 3);
myFunction("Jenny", 14);
myFunction("Anja", 30);
return 0;
}

// Hello Liam. You are 3 years old.


// Hello Jenny. You are 14 years old.
// Hello Anja. You are 30 years old.
void myFunction();

// The main method


int main() {
myFunction(); // call the function
return 0;
}

// Function definition
void myFunction() {
printf("I just got executed!");
}

int myFunction(int x, int y) {


return x + y;
}

int main() {
int result = myFunction(5, 3);
printf("Result is = %d", result);
return 0;
}
// Outputs 8 (5 + 3)

You might also like