Вы находитесь на странице: 1из 21

Introduction to C/C++ Part -1

<study notes>

Prepared by

Ahmed Sakr
Electrical Engineering Dept. Minia Univ. Communications and Electronics Section ahmed.sakr@ieee.org

13th Feb, 2012

-0-

contents :
LESSON-1 : WRITE THE FIRST PROGRAM : LESSON-2 : ESSENTIALS OF C: LESSON -3 : DATA TYPES AND NAMES IN C/C++: LESSON- 4 : READING FROM AND WRITING TO STANDARD I/O : LESSON 5 : USING OPERATORS : LESSON 6: LOOP : LESSON 7 : CONTROL STATEMENTS 2 4 6 9 12 13 18

-1-

C++ :
Lesson-1 : write the first program :
Example :
#include<stdio.h> Void main() { printf(Hello world); }

From this program : 1- The Include directive : tells the C preprocessor to look for a file and place the contents of the file in the location where the #include directive indicates. 2- <stdio.h> :

It is called header file because the #include directives are almost always placed at the head of C programs. Actually, the extension name of .h does mean "header.". It contains number of functions that will be used in the program printf is a function locates in the header file stdio.h .
3- Void main(){ } The essential and main function in the program , the program starts and ends within the main() function .Only one main() can be used for each program file. The default return type of main()is integer. 4- () ,{}, and ;

This syntax are essential and the program cant run without them , main function must be follow by () to be main() , and the double quotes are always used with words to be written by printf , the ; sign is included at the end of every command . 5- return(0): each function should return a value which may be zero or other , for main() function it is defined by the type void which means that the function returns no value.
General notes : - C/C++ are a case-sensitive programming languages , the uppercase letters are not the same as the lowercase letters, when you write Main() it is looked at as a different function than main(), and when you define A=0 as a variable it does not mean that a=0 as they are different.
-2-

- C/C++ need a compiler to convert the codes from source file into executable file (*.exe) in order to run it in your operating system and a debugger to insure that the program has no error. - C/C++ are high level programming languages, they has the readability , maintainability and portability advantages. - Exite() function is used to terminate the program .

-3-

Lesson-2 : Essentials of C:
1- Constants and variables : - Constant is a value that will never change , Variable is used to present different values and can change its value. 2- Expressions : A combination of constants, variables, functions and operators which form a computation . Ex: I*(11+3*x): 11: expression for a constant . I,x : expression for a variable. 11+x: expression for a constant plus variable. Return(0) : expression for function . - Math operators : + : Addition - :Subtraction * : Multiplication / :Division % :Remainder (or modulus) - Statement is an expression ended by semicolon (;) 3- Statement blocks : Group of statements starts with { and ends with }. Ex:
Void main() { printf(cheers ^_^ /n); printf(statement block); } //start of statement block //end of statement block

- Statement blocks are used commonly with control functions such as for,while, if ,etc. - Functions in C/C++: o Function type : The type of the data the function returns after execution. o Function name : The name of the function which is used to call it in the program , ex. Printf().

-4-

Function name cannot start with digit , asterisks , operators or dot , cannot be totally a number or include operators within the name . Examples : Add_St ,char2int, etc. o Function argument : information which is needed for the function to run , it is included in the function statement . Ex. :
printf(Hello world); // printf : function name //Hello world : function argument , the information which the function use .

o Function body : the combination of C statements and variables declaration used to achieve the task of the function . ex: //function used to add two integers
#include<stdio.h> int add_int(int x, int y) { //start of function block int result; //variable declaration statement result=x+y; //math operation statement return(result); //Return value } //end of function block

o Function calling : to use the function to get its outputs , the function must be called on the main() . ex:
//Adding two numbers #include<stdio.h> //writing the function body int add_int(int x, int y) { //start of function block int result; //variable declaration statement result=x+y; //math operation statement return(result); //Return value } //end of function block //calling the function on the main() void main() { int x; x= add_int( 11, 15); printf(11 + 15 = %d,x); }

-5-

Lesson -3 : Data types and names in C/C++:


1- C Keywords : words used by the C language with specified functions , ex. for, while ,char , int, void , main , etc. 2- Data type : a. Char data type : The object represents a single character of the character set used by the computer , ex. A , a , C ,c , X, ..etc. Because computers can only store numbers , characters are encoded into numbers , one standard for encoding characters is the ASCII code . Char declaration : char <variable name> ; or : char <Variable name_1>,<Variable name_2>; Passing variables : Char X; X = A ; Escape characters : Special characters starts with (\) then a character , each escape char has a specified function to do . ex. : \n : Writing a new line. \b : Backspace char, moves the cursor on char to left . Ex.
// printing char value : #include<stdio.h> void main() { char c1 = a; char c2 = A; printf(the value of c1 is : %c .\n,c1); printf(The value of c2 is : %c.\n,c2); }

//output :
the value of c1 is : a the value of c2 is : A

Converting number from 0 to 255 into Char: //converting number to char :


#include <stdio.h>

-6-

void main() { char X1 = char X2 = printf(X1 = printf(X2 = }

60; 90; %c \n,X1); %c \n,X2);

//output :
X1 = < X2 = Z

b. int data type (integer ) : used with integer variables with value between 2147483647 and -2147483647 . Declaration of int data type : int <variable name>; //or int <variable name 1>,<variable name 2>; //or int <variable name > = <integer>; c. float data type : used with variables with a decimal point (friction) from -1037 to 1037. Declaration : float <variable name>; Example : // printing integer/float division result : #include <stdio.h> void main() { //declaration of variables :
int x1,x2,x3; float x1_f ,x2_f,x3_f; x1 = 32/11; x1_f= 32/11; x2= 32.0/11; x2_f= 32.0/11; x3=32/11.0; x3_f=32/11.0; //getting the output in int/float formats : printf("int of 32/11 : %d\n",x1); printf("float of 32/11 : %f\n",x1_f); printf("int of 32.0/11 : %d\n",x2);

-7-

printf("float of 32.0/11 : %f\n",x2_f); printf("int of 32/11.0 : %d\n",x3); printf("float of 32/11.0 : %f\n",x3_f);

} //output : int of 32/11 : 2 float of 32/11 : 2.000000 int of 32.0/11 : 2 float of 32.0/11 : 2.909091 int of 32/11.0 : 2 float of 32/11.0 : 2.909091 d. double data type : used with real numbers in the same way as the float data type , but with precision of 10 digits. Declaration : double <variable name>;

-8-

Lesson- 4 : Reading from and writing to standard I/O :


Receiving and writing data from and to user . One byte contains 8-bits , and stream consists of a group of bytes . File streams : o stdin : standard input for reading . o stdout : standard output for writing , used in printf function. o stderr : standard error for writing error messages . Usually , stdin is linked to keyboard , stdout and stderr are linked to the screen . a. getc() function : used to get character from user and store it as integer (ascii ). ex.
#include "stdafx.h" #include <stdio.h> void main() { int i; printf("enter any char\n"); i=getc(stdin); printf("you have entered : %d\n",i); getc(stdin); } //output enter any char j you have entered : j

b. getchar() function : equal to getc(stdin) ex.


#include "stdafx.h" #include <stdio.h> void main() { int i; printf("enter any char\n"); i=getchar(); printf("\n you have entered : %c\n",i); }

-9-

//output enter any char j you have entered : j

c. putc() : write a char to the specified file stream . ex.


#include "stdafx.h" #include <stdio.h> void main() { int i; printf("enter any char\n"); i=getchar(); printf("\n you have entered : "); putc(i,stdout); } //output enter any char j you have entered : j

d. putchar() function : the same as putc(int I, stdout ) e. printf() format specifiers : %c The character format specifier. %d The integer format specifier. %i The integer format specifier (same as %d). %f The floating-point format specifier. %e The scientific notation format specifier (note the lowercase e). %E The scientific notation format specifier (note the uppercase E). %g Uses %f or %e, whichever result is shorter. %G Uses %f or %E, whichever result is shorter. %o The unsigned octal format specifier. %s The string format specifier. %u The unsigned integer format specifier. %x The unsigned hexadecimal format specifier (note the lowercase x). %X The unsigned hexadecimal format specifier (note the uppercase X). %p Displays the corresponding argument that is a pointer.
- 10 -

%n Records the number of characters written so far. %% Outputs a percent sign (%).

- 11 -

Lesson 5 : Using operators :


operators in C are : Math operators : ( + , - , * , / , %). Logic operators : o (==) : Equal operator o (!=) : Not equal . o (&&) : AND operator . o (||) : OR operator . Arthimatic assignment operators : o (+=) : Addition ( x+=y) == (x=x+y). o (-=) : Subtraction (x-=y)==(x=x-y). o (*=) : Multiplication (x*=y)==(x=x*y). o (/=) : Division : (x/=y)== (x=x/y). o (%=): Remainder : (x%=y)==(x=x%y). o (++) : (X++)==(X=X+1). o (--) : (X--)==(X=X-1). Compairing operators : o (==) , (!=) : Equal , Not equal . o < : Less than o > : Greater than. o <= : Less than or equal. o >=: Greater than or equal . cast operator : To change data type to another type (data type)<variable> ex:
char x; int i = 10; x=(char) I; printf((char) i = %c,x);

- 12 -

Lesson 6: Loop :
A method to repeat the statement more than one time . 1- looping using for : for(<counter> ; <Condition> ; <Step>) { statement _1; statement_2; statement_N; } ex:
//program to convert numbers from 0:10 to char using ascii code #include <stdio.h> void main() { printf("i = \t;\t (char)i \n"); for(int i=0;i<10;i++) { printf("i = %d \t;\t (char)i = %c\n",i,i); } }

//output : i= ; (char)i 0 ; 1 ; 2 ; 3 ; 4 ; 5 ; 6 ; 7 ; 8 ; 9 ;

Multiple expressions with for


for(<counter_1>,<counter_2>; <Cond_1>,<Cond_2>;<step_1>,<step_2>)

ex:
#include <stdio.h> void main() { printf("i + j = i+j \t i\tj\ti+j\n"); int i,j;

- 13 -

for( i=60, j=70;i<70,j>60;i++,j--) { printf("%d + %d = %d \t %c\t%c\t%c\n",i,j,i+j,i,j,i+j); } }

//output
i + j = i+j i 60 + 70 = 130 61 + 69 = 130 62 + 68 = 130 63 + 67 = 130 64 + 66 = 130 65 + 65 = 130 66 + 64 = 130 67 + 63 = 130 68 + 62 = 130 69 + 61 = 130 j < = > ? @ A B C D E i+j F E D C B A @ ? > =

Infinite looping : Code will be repeated for infinite time . for( ; ; ) { <statements>} 2- Looping using while : while(<Condition>) { statement_1; statement_2 ; statement_N; } ex:
#include <stdio.h> void main() { int i=0; printf("i\ti^2\n"); printf("-------------------\n"); while(i<=10) { printf("%d\t%d\n",i,i*i); i++; } }

//output
i i^2 ------------------0 0 1 1 2 4

- 14 -

3 4 5 6 7 8 9 10

9 16 25 36 49 64 81 100

infinite looping using while : while(1) {statements; } 3- Looping using do while() do { <statements> } while(<Condition>); In this method , the statement block run for at least one time. ex:
#include <stdio.h> void main() { int i=0; printf("i\ti^2\n"); printf("-------------------\n"); do { printf("%d\t%d\n",i,i*i); i++; } while(i<=5);

//output :
i i^2 ------------------0 0 1 1 2 4 3 9 4 16 5 25

ex 2:
#include <stdio.h> void main()

- 15 -

{ int i=0; printf("i\ti^2\n"); printf("-------------------\n"); do { printf("%d\t%d\n",i,i*i); i++; } while(i>1);

//output
i i^2 ------------------0 0

Nested loop: By putting a loop inside another loop , the inside loop will run one time per loop of the external loop . ex:
#include <stdio.h> void main() { int i=0; for(int i=0;i<5;i++) { for(int j=0;j<10;j++) { printf("*"); } printf("\n"); } }

//output :
********** ********** ********** **********

4- Data modifiers : Sign control modifiers : The signed modifier : Enables the sign digit for numeric variables (int and char) , (enable positive and negative values for variables. signed char ch; Now, ch can take any value from -128 to 127 . The unsigned modifier : Disable the sign digit for numeric variables. Data size control modifiers :
- 16 -

short Modifier : change int data size from 32 bit to 16 bit to save memory used. It is signed by defult. short X; unsigned short Y; long Modifier : Increases the size of int data to 32 bits. It is signed by defult. - Math functions in C : Mathematical functions such as sin() , cos() , tan() , etc are included in a header file named <math.h> which should be included in the code before using any of this functions. ex:
#include <math.h> void main() { double theta,theta_ ; printf("theta sin cos\n"); for(theta=0;theta<=360;theta+=90) { theta_=theta*3.14/180.0; //convert to radian printf("%f %f %f\n",theta,sin(theta_),cos(theta_)); } }

//output :
theta sin 0.000000 90.000000 180.000000 270.000000 360.000000 cos 0.000000 1.000000 0.001593 -0.999997 -0.003185 1.000000 0.000796 -0.999999 -0.002389 0.999995

- Other Math functions : o pow(): #include math.h double pow(double x, double y); o sqrt() double sqrt(double x ); //sqrt(x) sqrt(x)==pow(x,0.5)

// x^y

- 17 -

Lesson 7 : control statements


- Control statements are used to control the execution of the statement block/s under control , if the condition is true then the statements is executed , if it is false , they are not executed . As you guess , the widest control statement in use is if which we had to use in the last statements . if
if (<condition>) { statements ; }

if the condition is true , the compiler run the code in the statement block , if not , the compiler wont see this code and will overcome it . ex.
#include <stdio.h> #include <math.h> void main() { //numbers from 0 to 10 that can be divided by 2 for (int i =0; i<10;i++) { if(i%2==0) printf("%d\n",i); } }

output :
0 2 4 6 8

if else statement :
if (<Condition>) { statements if true ; } else { statements if false; }

- 18 -

else is used here to control the statements which will be executed when the condition of the if statement is FALSE . Nested if statement : using if statement inside other if conditioning statements .
#include <stdio.h> #include <math.h> void main() { char c; printf("Plz enter Y or N or Q to exit\n"); c=getchar(); if(c!='Q') { if (c=='Y') printf("you have entered Y\n"); if(c=='N') printf("you have entered N\n"); } else printf("you have entered Q"); }

Switch statement : used when dealing with large number of conditions . - Declaration : switch (<Variable>) { case value_1 : //occurs if <variable> = Value_1 statement_1; case value_2: statement_2; .. .. case value_N: statement_N; default : statement_Default ; //occurs if no case is met } The break statement : - used in end of case statements to end the switch statement block when the case is met .

- 19 -

- used with loop like for or while or infinite loop to end it . The continue statement : - used with loop when it is needed to skip some statements without ending the loop and continue the next roll of it . The goto statement : - used to make a loop in a deferent way or to control the flow of the statements . Declaration : <label name>: statement_1; statement_2; statement_n; goto <label name>; where label name is an optional name for the loop .

- 20 -

Вам также может понравиться