C language learning - day02

Posted by [uk]stuff on Tue, 01 Mar 2022 10:54:04 +0100

Learning source: station b -- Author: Little Turtle-- [C language] C language video tutorial(Lonely self-study - up master)

Array practice

Problem: input 9 integers from the keyboard (input three lines according to the form of Jiugong grid, and input three numbers in each line) and save them in the two-dimensional array. Output all the elements of the first row and the first column according to the original position of the array.

code:

#include <stdio.h>

void main()
{ 
      int i, j, a[3][3];

      for (i= 0; i < 3; i++)   /*Input array*/
      {
            for (j=0; j < 3; j++)
            {  
                  scanf("%d", &a[i][j]);
            }
      }

      for (i=0; i < 3; i++)     /*Output array*/
      {
            for (j=0; j < 3; j++)
            {
                  if (i==1 || j==1) 
                  {
                        printf("%-6d",a[i][j]);
                  }
                  else 
                  {
                        printf("%-6c",' ');
                  }
            }
		  printf("\n");
      }
}

Input: 1 2 3 4 5 6 7 8 9

result:

Half search algorithm

#define M 10
#include<stdio.h>

void main()
{
      static int a[M]={-12,0,6,16,23,56,80,100,110,115};
      int n, low, mid, high, found;
      low=0;    
      high=M-1;    
      found=0;
      scanf("%d", &n);
      
      while(low <= high)
      {
            mid = (low + high) / 2;     	

            if (n == a[mid]) 
            {
                  found = 1;
                  break;
            }

            else if (n > a[mid])
            {
                  low=mid+1;
            }
            else
            {
                  high=mid-1;
            }
      }
      
      if (found==1)
      {
            printf("The index of %d is %d\n", n, mid);
      }
      else
      {
            printf("There is not  %d\n", n);
      }
}

Input: 0

Output:

Function

Functions can call each other, but the main function cannot be called.

Definition form:

Declaration form: type identifier} function name (formal parameter list);

If the values of the shape participating arguments are different, they will be converted according to the assignment rules of different types of values in day01.

The number of real participating formal parameters should be equal and the types should match. The arguments and formal parameters correspond in order and transfer data one by one.

Arrays can be used as parameters of functions for data transfer. Arrays can be used as function arguments in two forms. One is to use array elements (subscript variables) as arguments (when considering general parameters); The other is to use the array name as the formal parameter and argument of the function. Note: when the array name is used as a function parameter, the transmission is only the transmission of address, that is, the first address of the argument array is given to the shape parameter group name. After the n-shaped parameter group name obtains the first address, it is equal to having a real array. In fact, the formal parameter array and the argument array are the same array and share a section of memory space.

Standard functions (i.e. library functions)

This is provided by the system. Users do not have to define these functions themselves, but can use them directly.

User defined functions

To meet the special needs of users.

From the form of function, the function is divided into nonparametric function and parametric function

Nonparametric function

When calling a parameterless function, the calling function does not pass data to the called function. Parameterless functions are generally used to perform a specified set of operations.

Parametric function

When calling a function, the calling function passes data to the called function through parameters when calling the called function. Generally, a function value will be obtained when executing the called function for use by the calling function.  

Function return value (return)

return statement returns a certain value in the called function to the calling function.

The function type specified when defining a function should generally be consistent with the expression type in the return statement. If the type of the function value is inconsistent with the value of the expression in the return statement, the function type shall prevail. For numerical data, type conversion can be carried out automatically,

For example:

#include <stdio.h>

void main()
{
      int max(float x, float y);
      float a, b;
      int c;

      scanf("%f,%f", &a, &b);
      c = max(a, b);
      printf("Max is %d\n", c);
}

int max(float x, float y)
{
      float z;
      z = x > y ? x : y;

      return z;
}

Input: 1,2

result:

If the function type is void, the return statement cannot appear in the function body.

Multiple required values can be returned through the structure,

For example:

#include<stdio.h>
	
typedef struct Fx{//structural morphology
	int a;
	int b;
}Fx; 
	
Fx fun()
{
	Fx m = {8,5};
	return m;
}
int main()
{
	Fx m = fun();
	printf("%d %d",m.a,m.b);
	return 0;
}

Results:

There are three methods of function call according to the position of the function in the program

Function statement

Take the function call as a statement. Only the function is required to complete certain operations.

Function expression

This expression is called a function. At this time, the function is required to bring back a determined value to participate in the operation of the expression.

Function parameters

As an argument of a function, function call is essentially a form of function expression call.

Using function to realize pow function

#include <stdio.h>

double power(double x, double y);

void main()
{
      double x = 2.0, y = 5.0, z;
      
      z = power(x, y);
      
      printf("%.1f to the power of %.1f is %.1f\n", x, y, z);
}

double power(double x, double y)
{
      double z = x;

      while(--y)
      {
            z *= x;
      }

      return z;
}

result:

Recursive call

In the process of calling a function, the function itself is called directly or indirectly, which is called recursive call of function.

Problem: achieve s = 2 ²! + three ²!

#include <stdio.h>

long square(long x);
long factorial(long a);
void main()
{
      long x = 2, y = 3, z;
      
      z = square(x)+square(y);
      
      printf("result is %ld\n", z);
}

long square(long x)
{
    long z = x*x;    
    z = factorial(z);
    return z;
}

long factorial(long a)
{
    long result = -1;
    if(a < 0)
    {
        printf("error\n")
    }
    else if(a == 1 || a == 0)
    {
        result = 1;
    }
    else
    {
        result =  a*factorial(a-1);
    }
    return result;
}

result:

Problem: judge the value of each element in an integer array a[10]={1, 2, 3, 4, -1, -2, -3, -4, 2, 3}. If it is greater than 0, the value will be output. If it is less than or equal to 0, the value will be output. (an example is the use of array elements to pass parameters)

#include <stdio.h>

void test(int v);

void main()
{
      int a[10] = {1, 2, 3, 4, -1, -2, -3, -4, 2, 3};
      int i;
      
      for(i=0; i < 10; i++)
      {
            test(a[i]);
      }
      
      printf("\n");
}

void test(int v)
{
      if(v>0)
      {
            printf("%d ", v);
      }
      else
      {
            printf("%d ", 0);
      }
}

result:

Problem: write a function -- output array. Each element int a[10] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20} (for example, pass parameters by array name)

#include <stdio.h>

void test(int b[10]);

void main()
{
      int a[10] = {1,2,3,4,5,6,7,8,9,10};
      test(a);

      putchar('\n');
}

void test(int b[10])
{
      int i = 0;
      for( ; i < 10; i++ )
      {
            printf("%d ", b[i]);
      }
}

result:

Problem: calculate the average of all values in an array (pass parameters by array name)

#include <stdio.h>

double average(double array[]); 

void main()
{
 
      double score[10] = {5,5,7,9,8,8,4,5,7,10}, result;

      result = average(score);
      printf("average is %5.2lf\n", result);

      putchar('\n');
}

double average(double array[])
{
      double result = 0;
      int i = 0;
      
      for( i=0; i < 10; i++ )
      {
            result += array[i];
      }
      result /= 10;

      return result;
}

result:

Global and local variables

Note:

(1) the variables defined in the main function are only valid in the main function, not in the whole file or program because they are defined in the main function. The main function cannot use variables defined in other functions.

(2) variables with the same name can be used in different functions. They represent different objects and do not interfere with each other.

(3) within a function, variables can be defined in a compound statement. These variables are only valid in this compound statement. This compound statement is also called "sub program" or "program block",

For example:

#include <stdio.h>


void main()
{
	int a = 1, b = 2;
	{
		int c = a+b;
		a = 2;
		printf("c = %d\n", c);
	}
	printf("a = %d,b = %d\n",a,b);
}

result:

Question: n enter the length, width and height of the cube l,w,h. Find the volume and the area of three faces x*y,x*z,y*z.

#include <stdio.h>

int s1,s2,s3;

int vs( int a,int b,int c)
{
    int v;
	
    v = a*b*c;
    s1 = a*b;
    s2 = b*c;
    s3 = a*c;
	
    return v;
}

void main()
{
	 int v,l,w,h;
	 
	 scanf("%d %d %d",&l,&w,&h);
 
	 v = vs(l,w,h);
	 printf("\nv=%d, s1=%d, s2=%d, s3=%d\n",v,s1,s2,s3);
}

Input: 2 2 3

result:

Today's summary: I practiced the problem of array, reviewed some precautions of function and made some questions. I will review the rest of function tomorrow, and then review the contents of pointer and structure.

Topics: C