c programming. history c is a high-level programming language developed by dennis ritchie in 1972. c...

54
C programming C programming

Post on 20-Dec-2015

219 views

Category:

Documents


1 download

TRANSCRIPT

C programmingC programming

HistoryHistory

C is a high-level programming C is a high-level programming language developed by language developed by Dennis Dennis RitchieRitchie in 1972. in 1972.

He named it C because there was an He named it C because there was an existing programming language existing programming language called B. called B.

Learning CLearning C

C programs need to be C programs need to be compiledcompiled and turned into machine (binary) and turned into machine (binary) code before the program can be code before the program can be executed .executed .

To learn C you must To learn C you must PRACTICEPRACTICE!!!! !!!! Find a C compiler.Find a C compiler.

Stages of compilationStages of compilation

Source code

Lexical analysis

Preprocessing

Parsing Code generation

Object code

LinkingExecutable file

Why C ?Why C ?

One of the most popular One of the most popular programming languages.programming languages.

One of the most powerful One of the most powerful proproggramming languages.ramming languages.

Other languages like C++, Java, Perl Other languages like C++, Java, Perl and even JavaScript and Flash and even JavaScript and Flash ActionScript are all based on C in ActionScript are all based on C in terms of the way we write the code. terms of the way we write the code.

SyntaxSyntax The C code you write is called the The C code you write is called the SOURCE CODESOURCE CODE

or the or the SYNTAXSYNTAX. . Syntax is a mixture of: Syntax is a mixture of:

C keywords like int, for and return. •C keywords like int, for and return. • Constants and variables.•Constants and variables.• Operators like + (addition), || (or), etc. Operators like + (addition), || (or), etc.

Note that C is Note that C is CASE SENSITIVECASE SENSITIVE! For example, ! For example, words like cat, Cat, cAt and CAT arewords like cat, Cat, cAt and CAT are all considered all considered different from one another. different from one another.

Also, the amount of Also, the amount of WHITE SPACEWHITE SPACE you use in a C you use in a C program does not affect the way it's compiled. Use program does not affect the way it's compiled. Use extra spaces and line breaks to make your programs extra spaces and line breaks to make your programs more readable - indentation of code is very common. more readable - indentation of code is very common. Obviously, you can NOT put spaces or line breaks in Obviously, you can NOT put spaces or line breaks in the middle of keywords like this: str uct !! the middle of keywords like this: str uct !!

Creating Executable Creating Executable ProgramsPrograms

There are several tasks that need to be performed There are several tasks that need to be performed before you can run a program: before you can run a program: coding, coding, compiling compiling linking. linking.

You have to write the You have to write the SOURCE CODESOURCE CODE in C. You in C. You declare which header files you want to include within declare which header files you want to include within the source code. The source code must be saved with the source code. The source code must be saved with the extension .c. the extension .c.

Then you run the Then you run the COMPILERCOMPILER, which translates the , which translates the source code into machine code. This produces output source code into machine code. This produces output in a format that the computer can understand. in a format that the computer can understand.

LINKER LINKER basically "links" the source code to other basically "links" the source code to other library or object files so that the final program is library or object files so that the final program is produced. produced.

Your First ProgramYour First Program

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

int main() { int main() {

printf("Hello World!\n"); printf("Hello World!\n");

return (0); return (0);

}}

#include#include When the preprocessor finds #include it When the preprocessor finds #include it

looks for the file specified and replaces looks for the file specified and replaces #include with the contents of that file. #include with the contents of that file. This makes the code more readable and This makes the code more readable and easier to maintain if you needed to use easier to maintain if you needed to use common library functions. common library functions.

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

““stdio.h” is the file name. stdio.h” is the file name. This type of files This type of files are called are called header file.header file.

The main FunctionThe main Function

All C programs must have a main function. All C programs must have a main function. You can only have one, but you can place it You can only have one, but you can place it anywhere within the code. anywhere within the code.

The program always start with the main The program always start with the main function and ends when the end of main is function and ends when the end of main is reached. reached.

The main function is special, as it returns an The main function is special, as it returns an integer by default, which is why you'll see integer by default, which is why you'll see return 0; at the end of the program. Zero is return 0; at the end of the program. Zero is usually returned to indicate error-free usually returned to indicate error-free function termination. function termination.

The main FunctionThe main Function

int main() { int main() { printf("Hello World!\n"); printf("Hello World!\n");

return 0; return 0;

} }

StatementStatement

The entire line including keywords, The entire line including keywords, arguments, parentheses, and a arguments, parentheses, and a semicolon (;) is called a statement.semicolon (;) is called a statement.

Each statement must end with a Each statement must end with a semicolon.semicolon.

printfprintf

It prints the given arguments to the It prints the given arguments to the screen.screen.

It is not It is not PrintfPrintf It is It is printfprintf

printf(“Hello world”);printf(“Hello world”);

printf(“COMPE 111 Introduction to printf(“COMPE 111 Introduction to Computer Computer Engineering”);Engineering”);

Special CharactersSpecial Characters

\n \n newline. Cursor goes to next line. newline. Cursor goes to next line. \t \t horizontal tab. Cursor moves to the horizontal tab. Cursor moves to the

next tab.next tab. \r \r carriage return. Cursor moves to carriage return. Cursor moves to

thethe beginning of the same line. beginning of the same line.

\a\a alert. It produces a sound.alert. It produces a sound. \\\\ write backslash.write backslash. \”\” write double quote.write double quote.

Write programWrite program

WelcomeWelcome

To To

CC

1.1. Write a program to write the text Write a program to write the text given above using 3 printf statement.given above using 3 printf statement.

2.2. Write a program to write the text Write a program to write the text given above using 1 printf statement.given above using 1 printf statement.

VariablesVariables

Variables are like containers in your Variables are like containers in your computer's memory - you can store computer's memory - you can store values in them and retrieve or values in them and retrieve or modify them when necessary. modify them when necessary.

To To INITIALIZEINITIALIZE a variable means to a variable means to store a value in it store a value in it for the first timefor the first time, , which is done using the which is done using the ASSIGNMENT OPEARTORASSIGNMENT OPEARTOR, like , like this: x = 2this: x = 2

VariablesVariables

number1

RAM

number2

sum

5

10

15

AssignmentAssignment

Putting a value to a variable.Putting a value to a variable.

number = 25;number = 25;

sum = 23 + 56;sum = 23 + 56;

number = number + 1;number = number + 1;

Naming Constants and Naming Constants and Variables Variables

Names... Example

CANNOT start with a number 2i

CAN contain a number elsewhere h2o

CANNOT contain any arithmetic operators...

r*s+t

CANNOT contain any other punctuation marks...

#@x%£!!a

CAN contain or begin with an underscore

_height_

CANNOT be a C keyword struct

CANNOT contain a space im stupid

CAN be of mixed cases XSquared

An Introduction to the 4 An Introduction to the 4 Data TypesData Types

In C, there are four basic In C, there are four basic DATA TYPESDATA TYPES: : int, int, char,char, float, float, double. double.

Each one has its own properties. For Each one has its own properties. For instance, they all have different sizes. instance, they all have different sizes.

We must give each variable a data type We must give each variable a data type to allow and restrict the type of data we to allow and restrict the type of data we can assign to it. can assign to it.

printf (some more)printf (some more)

Printing constant and variables:Printing constant and variables:

int number;int number;number = 5;number = 5;Printf(“Number is %d \n”, number);Printf(“Number is %d \n”, number);Argument 1: Argument 1: “Number is %d \n”,“Number is %d \n”, format format

control stringcontrol stringArgument 2: Argument 2: numbernumber, the value to be printed, the value to be printed%d indicates that an integer will be printed.%d indicates that an integer will be printed.

printf (some more)printf (some more)

What is the output of the following What is the output of the following statement?statement?

int number1, number2;int number1, number2;

number1=5;number1=5;

number2=8;number2=8;

printf(“number 1 : %d \n number 2 : printf(“number 1 : %d \n number 2 : %d \n”, number1, number2); %d \n”, number1, number2);

The The intint Data Type Data Type #include <stdio.h> #include <stdio.h> int main() { int main() {

int a,b,c,d,e; int a,b,c,d,e; a = 10; a = 10; b = 4.3; b = 4.3; c = 4.8; c = 4.8; d = 'A'; d = 'A'; e = 4.3 + 4.8; e = 4.3 + 4.8; printf("a = %d\n", a); printf("a = %d\n", a); printf("b = %d\n", b); printf("b = %d\n", b); printf("c = %d\n", c); printf("c = %d\n", c); printf("d = %d\n", d); printf("d = %d\n", d); printf("e = %d\n", e); printf("e = %d\n", e); printf("b+c = %d\n", b+c); printf("b+c = %d\n", b+c); return 0; return 0;

} }

The The intint Data Type Data Type

The output of the example is: The output of the example is:

a = 10a = 10b = 4b = 4c = 4c = 4d = 65d = 65e = 9e = 9b+c = 8b+c = 8

scanfscanf It is used to get a value from user It is used to get a value from user

(keyboard). (keyboard).

scanf(“%d”, &number1);scanf(“%d”, &number1); Argument 1: format control string (an Argument 1: format control string (an

integer number will be read).integer number will be read). Argument 2: address of a variableArgument 2: address of a variable Result of the scanf statement:Result of the scanf statement:

number1 = 3;number1 = 3;& is the address operator. &number1 means & is the address operator. &number1 means

the address of the variable number1.the address of the variable number1.

scanfscanf

Input more than one variableInput more than one variablescanf(“%d %d”, &number1, scanf(“%d %d”, &number1, &number2);&number2);

Use scanf together with Use scanf together with printf to printf to make your program more user fiendly.make your program more user fiendly. printf(“Enter a number : ”);printf(“Enter a number : ”); scanf(“%d”, &number);scanf(“%d”, &number);

PracticePractice

Write a program whichWrite a program which1.1. Inputs two integer numbersInputs two integer numbers

2.2. Adds these two numbersAdds these two numbers

3.3. Writes the result to the screenWrites the result to the screen

practicepractice/* Addition program *//* Addition program */

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

Main()Main(){{

int number1, number2, sum;int number1, number2, sum;printf(“Enter first integer : ”);printf(“Enter first integer : ”);scanf(“%d”, &number1);scanf(“%d”, &number1);printf(“Enter second integer : ”);printf(“Enter second integer : ”);scanf(“%d”, &number2);scanf(“%d”, &number2);sum = number1 + number2;sum = number1 + number2;printf(“Sum is %d \n”, sum);printf(“Sum is %d \n”, sum);

return 0;return 0;}}

Programming guidelinesProgramming guidelines Use newline (\n) when necessary.Use newline (\n) when necessary.

Not goodNot good printf(“First number : %d”, number1);printf(“First number : %d”, number1); printf(“Second number : %d”, number2);printf(“Second number : %d”, number2);

GoodGood printf(“First number : %d \n”, number1);printf(“First number : %d \n”, number1); printf(“Second number : %d”, number2);printf(“Second number : %d”, number2);

Use indentation.Use indentation.

Programming guidelinesProgramming guidelines

Use indentation.Use indentation.

Main()Main()

{{

printf(“welcome”);printf(“welcome”);

printf(“to C! \n”);printf(“to C! \n”);

}}

Programming guidelinesProgramming guidelines

Put an explanation at the beginning of Put an explanation at the beginning of each function.each function.

/* First program in C *//* First program in C */

Main()Main()

{{

printf(“welcome”);printf(“welcome”);

printf(“to C! \n”);printf(“to C! \n”);

}}

Programming guidelinesProgramming guidelines

Place a space after each comma to Place a space after each comma to make programs more readable.make programs more readable.

Use meaningful variable and constant Use meaningful variable and constant names (total, average, sum, etc.)names (total, average, sum, etc.)

Combine multiple-word variables like Combine multiple-word variables like “total_commission” or “total_commission” or “totalCommision” “totalCommision”

Start with a lowercase letter to a Start with a lowercase letter to a variable name.variable name.

Programming guidelinesProgramming guidelines

Do not forget that C is a case sensitive Do not forget that C is a case sensitive language.language.

Do not place variable declarations among Do not place variable declarations among executable statements.executable statements.

Separate the declarations and executable Separate the declarations and executable statements with a blank line.statements with a blank line.

Place spaces on either side of an operator.Place spaces on either side of an operator.

sum = number1 + number2;sum = number1 + number2;sum=number1+number2;sum=number1+number2;

Arithmetic operations in Arithmetic operations in CC

operationoperation operatoroperator exampleexample

Addition + a + b, 45 + 7

Subtraction - a – b, 45 – 7

Multiplication * a * b, 45 * 7

Division / a / b, 45 / 7

Modulus/remainder % a % b, 45 % 7

Arithmetic operations in Arithmetic operations in CC

Integer divisionInteger division

int result;int result;

result = 17 / 5; result = 17 / 5; result = 3result = 3

result = 7 / 4;result = 7 / 4; result = 1result = 1 Modulus /remainderModulus /remainder

result = 17 % 5;result = 17 % 5; result = 2result = 2

result = 7 % 4;result = 7 % 4; result = 3result = 3

Order of evaluation Order of evaluation (Precedence)(Precedence)

operationoperation operatoroperator

ParenthesesParentheses ()()

Multiplication, divisionMultiplication, division *, /, %*, /, %remainderremainder

Addition, subtractionAddition, subtraction +, -+, -

Order of evaluation Order of evaluation (Precedence)(Precedence)

Evalaute the order of the following Evalaute the order of the following operationsoperations

a * (b + c) + c * (d + e)a * (b + c) + c * (d + e)

y = a * x * b + c * d + ey = a * x * b + c * d + e

g = a + b / c + d % e – (f + g) + a * b / cg = a + b / c + d % e – (f + g) + a * b / c

Algorithm (example)Algorithm (example)

get (GPA)get (GPA)

if (GPA > 3.5) thenif (GPA > 3.5) thenstatus <- “full scholarship”status <- “full scholarship”

else if (GPA > 3.0) thenelse if (GPA > 3.0) then

status <- “half scholarship”status <- “half scholarship”

else else

status <- “no scholarship”status <- “no scholarship”

put (status) put (status)

DecisionDecision

get (GPA)

GPA>3.5yes

no

Status <-”full-scholarship” GPA>3.0 Status <-”half-scholarship”yes

no

Status <-“no-scholarship”

put (status)

IF StructureIF Structure

Single selection structureSingle selection structure

if (condition)if (condition)

statement;statement;

Single selection structure with Single selection structure with single statementsingle statement

if (grade > 60)if (grade > 60)

printf(“passed”);printf(“passed”);

IF StructureIF Structure

Single selection structure with Single selection structure with multiple statementsmultiple statements

if (grade > 60) {if (grade > 60) {

printf(“Passed \n”);printf(“Passed \n”);

printf(“Congratulations!”);printf(“Congratulations!”);

}}

IF StructureIF Structure

Double selections structure with single Double selections structure with single statementstatement

if (grade > 60)if (grade > 60)printf (“Passed”);printf (“Passed”);

elseelseprintf (“Failed”);printf (“Failed”);

IF StructureIF Structure Double selections structure with multiple Double selections structure with multiple

statementsstatements

if (grade > 60){if (grade > 60){ printf (“Passed”);printf (“Passed”); printf(“Congratulations!”);printf(“Congratulations!”);

} } Else {Else { printf (“Failed”);printf (“Failed”);

printf (“Sorry”);printf (“Sorry”); }}

IF StructureIF Structure Multiple selectionsMultiple selections

if (grade > 90)if (grade > 90)printf (“AA”);printf (“AA”);

else if (grade > 80)else if (grade > 80)printf (“BB”);printf (“BB”);

else if (grade > 70)else if (grade > 70)printf (“CC”);printf (“CC”);

elseelseprintf(“DD”);printf(“DD”);

Relational operatorsRelational operators

x < yx < y Is x less than y?Is x less than y? x<= yx<= y Is x less than y or equal Is x less than y or equal

to y?to y? x > yx > y Is x greater than y?Is x greater than y? x >= yx >= y Is x greater than y or Is x greater than y or

equal to y?equal to y? x != yx != y Is x unequal to y?Is x unequal to y? x ==yx ==y Is x equal to y?Is x equal to y?

Logical operatorsLogical operators

ANDAND &&&& a && ba && b OROR |||| a || ba || b NOTNOT !! !(a)!(a)

Examples:Examples:if (a > 5 && b < 10)if (a > 5 && b < 10)

printf(“condition is satisfied”);printf(“condition is satisfied”);

Logical operatorsLogical operators

Examples:Examples:if (a > 5 && b < 10)if (a > 5 && b < 10)

printf(“condition is satisfied”);printf(“condition is satisfied”);

if ( number1 == 5 || number1 == 6)if ( number1 == 5 || number1 == 6)

printf (“condition is satisfied”);printf (“condition is satisfied”);

if (!(number != 0))if (!(number != 0))

printf (“Successful”);printf (“Successful”);

Precedence of operatorsPrecedence of operators ()() !! * / %* / % + -+ - <, >, >=, <=<, >, >=, <= == !=== != &&&& |||| ==

LoopLooptotal <- 0number <- 0

Number<5

yes

no

average <-total / numberget (grade)total <- total + gradenumber <- number + 1

put (status)

““for” repetition structurefor” repetition structure

Format:Format:

for (counter = 1; counter <= 10; counter = counter + 1)for (counter = 1; counter <= 10; counter = counter + 1)

printf(“%d \n”, counter);printf(“%d \n”, counter);

keyword

Control variable

initialization

Execution condition

Increment of control variable

““for” repetition structurefor” repetition structure

Write a program whichWrite a program which Gets a decimal value from userGets a decimal value from user Does the following actions 10 times:Does the following actions 10 times:

Adds one to the number, Adds one to the number, Writes the result on the screenWrites the result on the screen

““for” repetition structurefor” repetition structure

#include <stdio.h>#include <stdio.h>int main() {int main() { int number, i;int number, i; printf(“Enter a decimal number :”);printf(“Enter a decimal number :”); scanf(“%d”, &number);scanf(“%d”, &number); for (i=1; i <= 10; i = i + 1)for (i=1; i <= 10; i = i + 1) { { number = number + 1;number = number + 1; printf(“%d \n”, number); printf(“%d \n”, number);

}} return 0;return 0;}}

““for” repetition structurefor” repetition structure

Write a program which does the Write a program which does the following operations 5 times:following operations 5 times: Gets two decimal number from userGets two decimal number from user Calculates the remainder by dividing Calculates the remainder by dividing

the first number by the second number. the first number by the second number.

““for” repetition structurefor” repetition structure#include <stdio.h>#include <stdio.h>

int main() {int main() { int num1, num2, i;int num1, num2, i;

for (i=1; i <= 5; i = i + 1)for (i=1; i <= 5; i = i + 1) { { printf(“Enter first number :”);printf(“Enter first number :”); scanf(“%d”, &num1);scanf(“%d”, &num1); printf(“Enter second number :”);printf(“Enter second number :”); scanf(“%d”, &num2);scanf(“%d”, &num2); printf(“%d \n”, num1 % num2); printf(“%d \n”, num1 % num2);

}} return 0;return 0;}}