Upload
aleesha-benson
View
214
Download
0
Embed Size (px)
Citation preview
Sales person receive RM200/week plus Sales person receive RM200/week plus 9% of their gross sales for that week. 9% of their gross sales for that week. Write an algorithms to calculate the sales Write an algorithms to calculate the sales person’s earning from the input of gross person’s earning from the input of gross salarysalary
Input the first salesperson’s sales in dollarsInput the first salesperson’s sales in dollars
While the input is not -1 While the input is not -1
Calculate the salesperson’s wages for the Calculate the salesperson’s wages for the weekweek
Print the salesperson’s wages for the weekPrint the salesperson’s wages for the week
Input the next salesperson’s sales in dollarsInput the next salesperson’s sales in dollars
end whileend while
Input the first salesperson’s sales in dollarsInput the first salesperson’s sales in dollars
While the input is not -1 While the input is not -1
//Calculate the salesperson’s wages for the //Calculate the salesperson’s wages for the weekweek
Wages = RM200 + (Sales * 9%)Wages = RM200 + (Sales * 9%)
Print the salesperson’s wages for the weekPrint the salesperson’s wages for the week
Input the next salesperson’s sales in dollarsInput the next salesperson’s sales in dollars
end whileend while
Write an algorithms that inputs a series of 10 Write an algorithms that inputs a series of 10 numbers, and determines and prints the largest numbers, and determines and prints the largest of the numbers with 3 variable of the numbers with 3 variable COUNTER- a counter to count to 10, keep track COUNTER- a counter to count to 10, keep track the numberthe numberNUMBER - current input numberNUMBER - current input numberLARGEST - largest number found so farLARGEST - largest number found so far
Input the first number directly into the variable Input the first number directly into the variable largestlargest
Increment counter to 2Increment counter to 2
While counter is less than or equal to 10While counter is less than or equal to 10
input a new variable into the variable numberinput a new variable into the variable number
If number is greater than largestIf number is greater than largest
replace largest with numberreplace largest with number
Increment counterIncrement counter
Print the value of largestPrint the value of largest
Annual Interest = principal * rate * days /365Annual Interest = principal * rate * days /365Develop an algorithm using pseudocode will input Develop an algorithm using pseudocode will input principal, rate, and days for several loans, and will principal, rate, and days for several loans, and will calculate and display simple interest for each loan, calculate and display simple interest for each loan, using the formulausing the formula
Input the first loan principal in dollarsInput the first loan principal in dollars
While the input is not -1 While the input is not -1 Input the interest rateInput the interest rate
input the term of the loan in daysinput the term of the loan in days
calculate the simple interest for the loancalculate the simple interest for the loan
Print the simple interest for the loanPrint the simple interest for the loan
Input the loan principal for the next loanInput the loan principal for the next loan
The factorial of nonnegative integer n is written n! and The factorial of nonnegative integer n is written n! and defined as n!=n*(n-1)*(n-2)*…*1 for n greater than or defined as n!=n*(n-1)*(n-2)*…*1 for n greater than or equal to 1 and n!=1 for n=0. Write an algorithms that equal to 1 and n!=1 for n=0. Write an algorithms that read a non read a non -ve integer and computes and prints it factorial-ve integer and computes and prints it factorial
DoDo
Input number positiveInput number positive
while number is negativewhile number is negative
While number >=0While number >=0
if number = 0 thenif number = 0 then
factorial = 1factorial = 1
elseelse
factorial = factorial * nfactorial = factorial * n
end ifend if
n=n-1n=n-1
end whileend while
What wrong with this pseudocode ?
Introduction to CIntroduction to C
C language character set C language character set & tokens& tokens
Reserved wordsReserved words IdentifiersIdentifiers ConstantsConstants String constantsString constants PunctuatorsPunctuators OperatorsOperators
Reserved wordsReserved words– keywords that identify language keywords that identify language
entities, such as statements, data entities, such as statements, data types, and language element types, and language element attributesattributes
– they have a special meaning to they have a special meaning to compilercompiler
– must appear in the correct locationmust appear in the correct location– C reserved word must be typed fully C reserved word must be typed fully
in lowercasein lowercase– const, double, intconst, double, int
IdentifiersIdentifiers– when writing a program, we must come up with when writing a program, we must come up with
additional words to represent and reference certain additional words to represent and reference certain program entities.program entities.
– Needed for program variables, functions, and other Needed for program variables, functions, and other program constructsprogram constructs
– Rules for constructing identifiersRules for constructing identifiers can consist of the capital letters A and Z, the lowercase can consist of the capital letters A and Z, the lowercase
letters a to z, the digits 0 to 9, and the underscore letters a to z, the digits 0 to 9, and the underscore charactercharacter
first character must be a letter or an underscorefirst character must be a letter or an underscore virtually no length limitation, compiler only recognize first virtually no length limitation, compiler only recognize first
32 character as significant32 character as significant reserved word cannot be used reserved word cannot be used case sensitive case sensitive
ConstantsConstants
Four types of constants ; integer, Four types of constants ; integer, floating point, character, and floating point, character, and enumerationenumeration
Integer can be +ve or -ve numbers Integer can be +ve or -ve numbers and can be decimal, octal or and can be decimal, octal or hexadecimalhexadecimal
/*File Name : prog1_1.cDefinition : A simple program that displays a message.
*/# include <stdio.h>int main(){
printf(“This is my first C program.\n”);return 0;}
Output This is my first C program.
Parts of A C ProgramParts of A C Program Comments LinesComments Lines
– /*……..*//*……..*/– is used to comment your program while writing itis used to comment your program while writing it
Library FileLibrary File– # include <stdio.h># include <stdio.h>– # indicates a preprocessor command# indicates a preprocessor command– file with extension .hfile with extension .h– stdio.h is a library file that contains standard I/O stdio.h is a library file that contains standard I/O
functionsfunctions
Main() FunctionMain() Function– indicates the logical beginning of the programindicates the logical beginning of the program– consist of function header and function bodyconsist of function header and function body– Function Header int main()Function Header int main()
int indicates the function returns an integer value.int indicates the function returns an integer value.
– Function BodyFunction Body {{
printf(“This is my first c program.\n”);printf(“This is my first c program.\n”);
return 0;return 0;
}}
Statement format, Statement format, – every statement will end with ;every statement will end with ;
output function, printf()output function, printf() Escape character, \nEscape character, \n
– \b, back space\b, back space– \r, carriage return\r, carriage return– \\, backslash\\, backslash– \”, double quotation\”, double quotation– \t, tab\t, tab
ExamplesExamples
Printf(“\\ Hello \\ \t “ Good bye \” \n Printf(“\\ Hello \\ \t “ Good bye \” \n “);“);
OUTPUTOUTPUT
\ Hello \ “ Good bye “\ Hello \ “ Good bye “
Data Types in CData Types in C
Basic Data TypeBasic Data Type– charactercharacter charchar– integer numberinteger number intint– floating-point numberfloating-point number floatfloat– double precision numberdouble precision number doubledouble– typeless/valuelesstypeless/valueless voidvoid
Class of DataClass of Data
Character constantsCharacter constants string constantsstring constants Integer constantsInteger constants floating-point constantsfloating-point constants
Displaying NumbersDisplaying Numbers
Printf(“control string”, arg1, arg2,Printf(“control string”, arg1, arg2,…);…);
exampleexampleprintf(“A Simple Control String”);printf(“A Simple Control String”);
Output : A Simple Control StringOutput : A Simple Control String
printf(“The sum of 1 and 2 is printf(“The sum of 1 and 2 is %d%d), ), 1+2);1+2); Conversion specification
argument
Conversion SpecificationConversion Specification%c - single character%c - single character
printf(“%c”,’A’);printf(“%c”,’A’); AA
%d - signed decimal integer%d - signed decimal integer
printf(“%d”,10);printf(“%d”,10); 1010
%f - floating-point num.,decimal notation%f - floating-point num.,decimal notation
printf(“%f”,5.6);printf(“%f”,5.6); 5.6000005.600000
%e%e - floating-point num., e notation - floating-point num., e notation
printf(“%e”,52.6);printf(“%e”,52.6); 5.26e15.26e1
Conversion SpecificatiomConversion Specificatiom
%o octal%o octal printf(“%o”,100) 120printf(“%o”,100) 120
%d decimal %d decimal 100 100
%x hexadecimal%x hexadecimal 64 64
Floating point numbersFloating point numbers
printf(“[ 10.3f ]”, 21.12); printf(“[ 10.3f ]”, 21.12);
[ 21.120 ][ 21.120 ]
10.3 = display the number in a total field of 10 10.3 = display the number in a total field of 10 and 3 digit to the right of the decimal point. and 3 digit to the right of the decimal point.
Conversion Specification Conversion Specification FlagsFlags
- (minus sign) left justify- (minus sign) left justify
+ display the + or - sign of the number+ display the + or - sign of the number
blank display blank if +ve and - if -veblank display blank if +ve and - if -ve
ExampleExampleprintf(“This number is : %+.2f \n”, 123.456);printf(“This number is : %+.2f \n”, 123.456);
printf(“Next number is : %+d \n”, -123);printf(“Next number is : %+d \n”, -123);
OUTPUTOUTPUTThis number is : +123.45This number is : +123.45
Next number : is -123Next number : is -123
DISPLAYING CHARACTERSDISPLAYING CHARACTERS
The character representationThe character representation
StorageStorage 0 1 0 0 0 0 0 10 1 0 0 0 0 0 1
““%c”%c” AA
““%d”%d” 6565
Displaying Formatted Displaying Formatted StringsStrings
printf(“[%-20s]”,”Pure C”); [Pure C ]printf(“[%-20s]”,”Pure C”); [Pure C ]
[%20.4s][%20.4s] [ Pure] [ Pure]
[-%20.4][-%20.4] [Pure ] [Pure ]
[%.4s][%.4s] [Pure] [Pure]
#include <stdio.h>#include <stdio.h>
int main()int main()
{{
printf(“[30s] \n”, “Universiti Malaysia Sarawak”);printf(“[30s] \n”, “Universiti Malaysia Sarawak”);
printf(“[%-30s] \n”, “Universiti Malaysia Sarawak”);printf(“[%-30s] \n”, “Universiti Malaysia Sarawak”);
printf(“[%15.6s] \n”, “Universiti Malaysia Sarawak”);printf(“[%15.6s] \n”, “Universiti Malaysia Sarawak”);
printf(“[%.6s] \n”, “Universiti Malaysia Sarawak”);printf(“[%.6s] \n”, “Universiti Malaysia Sarawak”);
printf(“[%5s|] \n”, “Universiti Malaysia Sarawak”);printf(“[%5s|] \n”, “Universiti Malaysia Sarawak”);
return 0;return 0;
}}
[ Universiti Malaysia Sarawak][ Universiti Malaysia Sarawak]
[Universiti Malaysia Sarawak ][Universiti Malaysia Sarawak ]
[ Univer][ Univer]
[Univer][Univer]
[Universiti Malaysia Sarawak] [Universiti Malaysia Sarawak]
VariablesVariables
Variable type declarationVariable type declaration
variable type variable list;variable type variable list;
variable type - must be valid C data variable type - must be valid C data typetype
variable list - consists of one of more variable list - consists of one of more variable names separate by variable names separate by commascommas
Common ErrorsCommon Errors
Forgetting to declare variables Forgetting to declare variables before using thembefore using them
placing variable declaration in the placing variable declaration in the middle of the programmiddle of the program
forgetting the data type or forgetting the data type or declaring a wrong data typedeclaring a wrong data type
forgetting the ; at the end of the forgetting the ; at the end of the statementstatement
Variable initializationsVariable initializations
It is possible to assign an initial value to a It is possible to assign an initial value to a variable when it is declared.variable when it is declared.
int I, x;int I, x;
char ch = ‘A’char ch = ‘A’
float f _number = 10.00;float f _number = 10.00;
C does not automatically initialize declared C does not automatically initialize declared variablesvariables
Variable Names/identifierVariable Names/identifier
1st character must be a letter or an 1st character must be a letter or an underscore, rest can be combination of underscore, rest can be combination of letters, underscores, or digit.letters, underscores, or digit.
Case sensitiveCase sensitive number of character is compiler-dependentnumber of character is compiler-dependent whitespace character and special character whitespace character and special character
(!,$,()) is not allowed within a name(!,$,()) is not allowed within a name no keyword and reserved wordno keyword and reserved word
Data Type ModifierData Type Modifier
Integer modifiers - usually is 2 bytesInteger modifiers - usually is 2 bytes Data Type Data Type Max Max MinMin
short/short intshort/short int 127127 -128-128
intint 3276732767 -32768-32768
long/long intlong/long int 2147483647 -2147483647 -21474836482147483648
unsigned shortunsigned short 255255 00
unsigned or unsigned int unsigned or unsigned int 6553565535 00
unsigned long or unsigned unsigned long or unsigned
long intlong int 4294967295 4294967295 00
Data Type ModifierData Type Modifier
Floating-Point modifiers - usually is 8 Floating-Point modifiers - usually is 8 bytesbytes– only one modifier, long doubleonly one modifier, long double
long double long_double; /* declare a long long double long_double; /* declare a long double double type type variable */variable */
Declaration & Initialization Declaration & Initialization StatementStatement
long int LongNumber;long int LongNumber;
long Lnum = 100L; /* 100 is fit in short but with this long Lnum = 100L; /* 100 is fit in short but with this declaration declaration
will forces to store in 4 bytes */will forces to store in 4 bytes */
long A_Long = 5l;long A_Long = 5l;
unsigned positive=35353U;unsigned positive=35353U;
unsigned long count1;unsigned long count1;
short counter;short counter;
long double Dlarge;long double Dlarge;
long double LD=1.1e+3000long double LD=1.1e+3000
What You Have Learn ?What You Have Learn ?
/* */ /* */ comment linecomment line #include directive#include directive preprocessor commandpreprocessor command int main ()int main () {{ declaration statementsdeclaration statements initialization statementsinitialization statements statementsstatements return 0;return 0; }}
OperatorsOperators
A symbol performs a specific mathematical A symbol performs a specific mathematical or logical operation.or logical operation.
Arithmetic OperatorsArithmetic Operators
+ + additionaddition
-- substractionsubstraction
** MultipleMultiple
// DivisionDivision
%% RemainderRemainder
Mixed OperandMixed Operand
If all operand are integer type, then the result is an If all operand are integer type, then the result is an integerinteger
If any operand is a floating-point or double If any operand is a floating-point or double precision type, then the result ia a double precisionprecision type, then the result ia a double precision
ExamplesExamplesprintf(%.2f”, 10.0/5);printf(%.2f”, 10.0/5); float/intfloat/int floating pointfloating point
2.002.00
printf(%.2f”, 10/5.0);printf(%.2f”, 10/5.0); int/floatint/float floating pointfloating point2.002.00
printf(%.2f”, 10.0-5);printf(%.2f”, 10.0-5); float-intfloat-int floating pointfloating point5.005.00
Assignment OperatorAssignment Operator
Lvalue = RvalueLvalue = Rvalue
• Variable• Constant• Expression
• Variableint x, y, z;char ch;float fnumx = 10;ch = ‘C’;fnum = 100.55;y = x*2z = y;
Thanks…will continue on Thanks…will continue on next lecturenext lecture