After learning C and python or more languages, if you don’t use it for a period of time, you will confuse the basic flow control statements, but the essence is the same, but the form is different. Here is a summary of the basic flow control of several languages The difference in writing.
table of Contents
1 Conditional judgment
The point is to distinguish the difference in writing, we use the simplest example to illustrate.
1.1 if else
C
int x = 5;
if(x>0){
x = 1;
}else if(x<0){
x = -1;
}else{
x = 0;
};
printf("%d",x);
python
x = 5
if x>0:
x = 1
elif x<0:
x=-1
else :
x = 0
print(x)
R and C are the same
x = 5
if(x>0){
x = 1;
}else if(x<0){
x = -1;
}else{
x = 0;
};
print(x)
1.2 switch case
C, case is to locate the current statement, not to select one like if else, so there is no need to add break after execution.
int i = 14;
switch(i){
case 1:
printf("yi");
break;
case 2 :
printf("er");
break;
default:
printf("what?");
break;
}
Python does not support switch case, because elif can be used all the time, and dictionary can also be used
i = 1
def switch_case(value):
switcher = {
1: "yi",
2: "er"
}
return switcher.get(value,"what?")
print(switch_case(1))
In R, the switch forces i to be converted to an integer, which matches the unpositioned afterwards. There is no default available, which is not very useful. It is better to directly if else.
i <-1
print(switch(i , "yi","er" ))
"yi"
2 loop
2.1 for
C
int i;
for(i=0;i<5;i++){
printf("%d\n",i);
}
return 0;
python
for i in range(5):
print(i)
R
for( i in seq(1:5)){
print(i);
}
2.2 while
int i;
while(i<5){
printf("%d\n",i);
i++;
};
i = 0
while i<5:
print(i);
i = i + 1
R
i <- 0
while (i < 5) {
print(i);
i = i + 1;
}
2.3 do while
C
int i = 0;
do{
printf("%d\n",i);
i++;
}while(i<5); // 不满足条件退出
Python does not support do while, break can be used instead, pay attention to the different termination conditions
i = 0
while True: #无限循环...
print(i);
i = i+1;
if i>4:
break
R does not have a do while, and supports repeat break;
i <- 0
repeat {
print(i);
i = i+1;
if(i>4) {
break;
}
}
3 Define the function
c is a typed language, define functions strictly, and declare input and output types.
int testfunc(int x){
x = x+1 ;
return x ;
}
printf("%d",testfunc(1));
Python is relatively simple
def testfunc(x):
x = x+1;
return x;
print(testfunc(1))
Brackets for return in r
testfunc<-function(x){
x <- x+1;
return(x)
}
print(testfunc(1));