经常遇到的10大C语言基础算法(珍藏版源码)

发表于 3年以前  | 总阅读数:521 次

算法是一个程序和软件的灵魂,作为一名优秀的程序员,只有对一些基础的算法有着全面的掌握,才会在设计程序和编写代码的过程中显得得心应手。本文是近百个C语言算法系列的第二篇,包括了经典的Fibonacci数列、简易计算器、回文检查、质数检查等算法。也许他们能在你的毕业设计或者面试中派上用场。

1、计算Fibonacci数列

Fibonacci数列又称斐波那契数列,又称黄金分割数列,指的是这样一个数列:1、1、2、3、5、8、13、21。

C语言实现的代码如下:

/* Displaying Fibonacci sequence up to nth term where n is entered by user. */
#include <stdio.h>
int main()
{
  int count, n, t1=0, t2=1, display=0;
  printf("Enter number of terms: ");
  scanf("%d",&n);
  printf("Fibonacci Series: %d+%d+", t1, t2); /* Displaying first two terms */
  count=2;    /* count=2 because first two terms are already displayed. */
  while (count<n)  
  {
      display=t1+t2;
      t1=t2;
      t2=display;
      ++count;
      printf("%d+",display);
  }
  return 0;
}

结果输出:

Enter number of terms: 10
Fibonacci Series: 0+1+1+2+3+5+8+13+21+34+

也可以使用下面的源代码:

/* Displaying Fibonacci series up to certain number entered by user. */

#include <stdio.h>
int main()
{
  int t1=0, t2=1, display=0, num;
  printf("Enter an integer: ");
  scanf("%d",&num);
  printf("Fibonacci Series: %d+%d+", t1, t2); /* Displaying first two terms */
  display=t1+t2;
  while(display<num)
  {
      printf("%d+",display);
      t1=t2;
      t2=display;
      display=t1+t2;
  }
  return 0;
}

结果输出:

Enter an integer: 200
Fibonacci Series: 0+1+1+2+3+5+8+13+21+34+55+89+144+

2、回文检查

源代码:

/* C program to check whether a number is palindrome or not */

#include <stdio.h>
int main()
{
  int n, reverse=0, rem,temp;
  printf("Enter an integer: ");
  scanf("%d", &n);
  temp=n;
  while(temp!=0)
  {
     rem=temp%10;
     reverse=reverse*10+rem;
     temp/=10;
  }  
/* Checking if number entered by user and it's reverse number is equal. */  
  if(reverse==n)  
      printf("%d is a palindrome.",n);
  else
      printf("%d is not a palindrome.",n);
  return 0;
}

结果输出:

Enter an integer: 12321
12321 is a palindrome.

3、质数检查

注:1既不是质数也不是合数。

源代码:

/* C program to check whether a number is prime or not. */

#include <stdio.h>
int main()
{
  int n, i, flag=0;
  printf("Enter a positive integer: ");
  scanf("%d",&n);
  for(i=2;i<=n/2;++i)
  {
      if(n%i==0)
      {
          flag=1;
          break;
      }
  }
  if (flag==0)
      printf("%d is a prime number.",n);
  else
      printf("%d is not a prime number.",n);
  return 0;
}

结果输出:

Enter a positive integer: 29
29 is a prime number.

4、打印金字塔和三角形

使用 * 建立三角形

*
* *
* * *
* * * *
* * * * *

源代码:

#include <stdio.h>
int main()
{
    int i,j,rows;
    printf("Enter the number of rows: ");
    scanf("%d",&rows);//微信搜索公众号【C语言中文社区】关注回复C语言,免费领取200G学习资料
    for(i=1;i<=rows;++i)
    {
        for(j=1;j<=i;++j)
        {
           printf("* ");
        }
        printf("\n");
    }
    return 0;
}

如下图所示使用数字打印半金字塔。

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

源代码:

#include <stdio.h>
int main()
{
    int i,j,rows;
    printf("Enter the number of rows: ");
    scanf("%d",&rows);
    for(i=1;i<=rows;++i)
    {
        for(j=1;j<=i;++j)
        {
           printf("%d ",j);
        }
        printf("\n");
    }
    return 0;
}

用 * 打印半金字塔

* * * * *
* * * *
* * * 
* *
*

源代码:

#include <stdio.h>
int main()
{
    int i,j,rows;
    printf("Enter the number of rows: ");
    scanf("%d",&rows);
    for(i=rows;i>=1;--i)
    {
        for(j=1;j<=i;++j)
        {
           printf("* ");
        }
    printf("\n");
    }
    return 0;
}

用 * 打印金字塔

        *
      * * *
    * * * * *
  * * * * * * *
* * * * * * * * *

源代码:

#include <stdio.h>
int main()
{
    int i,space,rows,k=0;
    printf("Enter the number of rows: ");
    scanf("%d",&rows);
    for(i=1;i<=rows;++i)
    {
        for(space=1;space<=rows-i;++space)
        {
           printf("  ");
        }
        while(k!=2*i-1)
        {
           printf("* ");
           ++k;
        }
        k=0;
        printf("\n");
    }
    return 0;
}

用 * 打印倒金字塔

* * * * * * * * *
  * * * * * * *
    * * * * *
      * * *
        *

源代码:

#include<stdio.h>
int main()
{
    int rows,i,j,space;
    printf("Enter number of rows: ");
    scanf("%d",&rows);
    for(i=rows;i>=1;--i)
    {
        for(space=0;space<rows-i;++space)
           printf("  ");
        for(j=i;j<=2*i-1;++j)
          printf("* ");
        for(j=0;j<i-1;++j)
            printf("* ");
        printf("\n");
    }
    return 0;
}

5、简单的加减乘除计算器

源代码:

/* Source code to create a simple calculator for addition, subtraction, multiplication and division using switch...case statement in C programming. */

# include <stdio.h>
int main()
{
    char o;
    float num1,num2;
    printf("Enter operator either + or - or * or divide : ");
    scanf("%c",&o);
    printf("Enter two operands: ");
    scanf("%f%f",&num1,&num2);
    switch(o) {
        case '+':
            printf("%.1f + %.1f = %.1f",num1, num2, num1+num2);
            break;
        case '-':
            printf("%.1f - %.1f = %.1f",num1, num2, num1-num2);
            break;
        case '*':
            printf("%.1f * %.1f = %.1f",num1, num2, num1*num2);
            break;
        case '/':
            printf("%.1f / %.1f = %.1f",num1, num2, num1/num2);
            break;
        default:
            /* If operator is other than +, -, * or /, error message is shown */
            printf("Error! operator is not correct");
            break;
    }
    return 0;
}

结果输出:

Enter operator either + or - or * or divide : -
Enter two operands: 3.4
8.4
3.4 - 8.4 = -5.0

6、检查一个数能不能表示成两个质数之和

源代码:

#include <stdio.h>
int prime(int n);
int main()
{
    int n, i, flag=0;//微信搜索公众号【C语言中文社区】关注回复C语言,免费领取200G学习资料
    printf("Enter a positive integer: ");
    scanf("%d",&n);
    for(i=2; i<=n/2; ++i)
    {
        if (prime(i)!=0)
        {
            if ( prime(n-i)!=0)
            {
                printf("%d = %d + %d\n", n, i, n-i);
                flag=1;
            }

        }
    }
    if (flag==0)
      printf("%d can't be expressed as sum of two prime numbers.",n);
    return 0;
}
int prime(int n)      /* Function to check prime number */
{
    int i, flag=1;
    for(i=2; i<=n/2; ++i)
       if(n%i==0)
          flag=0;
    return flag;
}

结果输出:

Enter a positive integer: 34
34 = 3 + 31
34 = 5 + 29
34 = 11 + 23
34 = 17 + 17

7、用递归的方式颠倒字符串

源代码:

/* Example to reverse a sentence entered by user without using strings. */

#include <stdio.h>
void Reverse();
int main()
{
    printf("Enter a sentence: ");
    Reverse();
    return 0;
}
void Reverse()
{
    char c;
    scanf("%c",&c);
    if( c != '\n')
    {
        Reverse();
        printf("%c",c);
    }
}

结果输出:

Enter a sentence: margorp emosewa
awesome program

8、实现二进制与十进制之间的相互转换

/* C programming source code to convert either binary to decimal or decimal to binary according to data entered by user. */

#include <stdio.h>
#include <math.h>
int binary_decimal(int n);
int decimal_binary(int n);
int main()
{
   int n;
   char c;
   printf("Instructions:\n");
   printf("1. Enter alphabet 'd' to convert binary to decimal.\n");
   printf("2. Enter alphabet 'b' to convert decimal to binary.\n");
   scanf("%c",&c);
   if (c =='d' || c == 'D')
   {
       printf("Enter a binary number: ");
       scanf("%d", &n);
       printf("%d in binary = %d in decimal", n, binary_decimal(n));
   }
   if (c =='b' || c == 'B')
   {
       printf("Enter a decimal number: ");
       scanf("%d", &n);
       printf("%d in decimal = %d in binary", n, decimal_binary(n));
   }
   return 0;
}

int decimal_binary(int n)  /* Function to convert decimal to binary.*/
{
    int rem, i=1, binary=0;
    while (n!=0)
    {
        rem=n%2;
        n/=2;
        binary+=rem*i;
        i*=10;
    }
    return binary;
}

int binary_decimal(int n) /* Function to convert binary to decimal.*/
{
    int decimal=0, i=0, rem;
    while (n!=0)
    {
        rem = n%10;
        n/=10;
        decimal += rem*pow(2,i);
        ++i;
    }
    return decimal;
}

结果输出:

9、使用多维数组实现两个矩阵的相加

源代码:

#include <stdio.h>
int main(){
    int r,c,a[100][100],b[100][100],sum[100][100],i,j;
    printf("Enter number of rows (between 1 and 100): ");
    scanf("%d",&r);
    printf("Enter number of columns (between 1 and 100): ");
    scanf("%d",&c);
    printf("\nEnter elements of 1st matrix:\n");

/* Storing elements of first matrix entered by user. */

    for(i=0;i<r;++i)
       for(j=0;j<c;++j)
       {
           printf("Enter element a%d%d: ",i+1,j+1);
           scanf("%d",&a[i][j]);
       }

/* Storing elements of second matrix entered by user. */

    printf("Enter elements of 2nd matrix:\n");
    for(i=0;i<r;++i)
       for(j=0;j<c;++j)
       {
           printf("Enter element a%d%d: ",i+1,j+1);
           scanf("%d",&b[i][j]);
       }

/*Adding Two matrices */

   for(i=0;i<r;++i)
       for(j=0;j<c;++j)
           sum[i][j]=a[i][j]+b[i][j];

/* Displaying the resultant sum matrix. */

    printf("\nSum of two matrix is: \n\n");
    for(i=0;i<r;++i)
       for(j=0;j<c;++j)
       {
           printf("%d   ",sum[i][j]);
           if(j==c-1)
               printf("\n\n");
       }

    return 0;
}

结果输出:

10、矩阵转置

源代码:

#include <stdio.h>
int main()
{
    int a[10][10], trans[10][10], r, c, i, j;
    printf("Enter rows and column of matrix: ");
    scanf("%d %d", &r, &c);

/* Storing element of matrix entered by user in array a[][]. */
    printf("\nEnter elements of matrix:\n");
    for(i=0; i<r; ++i)
    for(j=0; j<c; ++j)
    {
        printf("Enter elements a%d%d: ",i+1,j+1);
        scanf("%d",&a[i][j]);
    }
/* Displaying the matrix a[][] */
    printf("\nEntered Matrix: \n");
    for(i=0; i<r; ++i)
    for(j=0; j<c; ++j)
    {
        printf("%d  ",a[i][j]);
        if(j==c-1)
            printf("\n\n");
    }

/* Finding transpose of matrix a[][] and storing it in array trans[][]. */
    for(i=0; i<r; ++i)
    for(j=0; j<c; ++j)
    {
       trans[j][i]=a[i][j];
    }

/* Displaying the transpose,i.e, Displaying array trans[][]. */
    printf("\nTranspose of Matrix:\n");
    for(i=0; i<c; ++i)
    for(j=0; j<r; ++j)
    {
        printf("%d  ",trans[i][j]);
        if(j==r-1)
            printf("\n\n");
    }
    return 0;
}

结果输出:

本文由哈喽比特于3年以前收录,如有侵权请联系我们。
文章来源:https://mp.weixin.qq.com/s/abA_G55n4lXXYQj_SJK73A

 相关推荐

刘强东夫妇:“移民美国”传言被驳斥

京东创始人刘强东和其妻子章泽天最近成为了互联网舆论关注的焦点。有关他们“移民美国”和在美国购买豪宅的传言在互联网上广泛传播。然而,京东官方通过微博发言人发布的消息澄清了这些传言,称这些言论纯属虚假信息和蓄意捏造。

发布于:7月以前  |  808次阅读  |  详细内容 »

博主曝三大运营商,将集体采购百万台华为Mate60系列

日前,据博主“@超能数码君老周”爆料,国内三大运营商中国移动、中国电信和中国联通预计将集体采购百万台规模的华为Mate60系列手机。

发布于:7月以前  |  770次阅读  |  详细内容 »

ASML CEO警告:出口管制不是可行做法,不要“逼迫中国大陆创新”

据报道,荷兰半导体设备公司ASML正看到美国对华遏制政策的负面影响。阿斯麦(ASML)CEO彼得·温宁克在一档电视节目中分享了他对中国大陆问题以及该公司面临的出口管制和保护主义的看法。彼得曾在多个场合表达了他对出口管制以及中荷经济关系的担忧。

发布于:7月以前  |  756次阅读  |  详细内容 »

抖音中长视频App青桃更名抖音精选,字节再发力对抗B站

今年早些时候,抖音悄然上线了一款名为“青桃”的 App,Slogan 为“看见你的热爱”,根据应用介绍可知,“青桃”是一个属于年轻人的兴趣知识视频平台,由抖音官方出品的中长视频关联版本,整体风格有些类似B站。

发布于:7月以前  |  648次阅读  |  详细内容 »

威马CDO:中国每百户家庭仅17户有车

日前,威马汽车首席数据官梅松林转发了一份“世界各国地区拥车率排行榜”,同时,他发文表示:中国汽车普及率低于非洲国家尼日利亚,每百户家庭仅17户有车。意大利世界排名第一,每十户中九户有车。

发布于:7月以前  |  589次阅读  |  详细内容 »

研究发现维生素 C 等抗氧化剂会刺激癌症生长和转移

近日,一项新的研究发现,维生素 C 和 E 等抗氧化剂会激活一种机制,刺激癌症肿瘤中新血管的生长,帮助它们生长和扩散。

发布于:7月以前  |  449次阅读  |  详细内容 »

苹果据称正引入3D打印技术,用以生产智能手表的钢质底盘

据媒体援引消息人士报道,苹果公司正在测试使用3D打印技术来生产其智能手表的钢质底盘。消息传出后,3D系统一度大涨超10%,不过截至周三收盘,该股涨幅回落至2%以内。

发布于:7月以前  |  446次阅读  |  详细内容 »

千万级抖音网红秀才账号被封禁

9月2日,坐拥千万粉丝的网红主播“秀才”账号被封禁,在社交媒体平台上引发热议。平台相关负责人表示,“秀才”账号违反平台相关规定,已封禁。据知情人士透露,秀才近期被举报存在违法行为,这可能是他被封禁的部分原因。据悉,“秀才”年龄39岁,是安徽省亳州市蒙城县人,抖音网红,粉丝数量超1200万。他曾被称为“中老年...

发布于:7月以前  |  445次阅读  |  详细内容 »

亚马逊股东起诉公司和贝索斯,称其在购买卫星发射服务时忽视了 SpaceX

9月3日消息,亚马逊的一些股东,包括持有该公司股票的一家养老基金,日前对亚马逊、其创始人贝索斯和其董事会提起诉讼,指控他们在为 Project Kuiper 卫星星座项目购买发射服务时“违反了信义义务”。

发布于:7月以前  |  444次阅读  |  详细内容 »

苹果上线AppsbyApple网站,以推广自家应用程序

据消息,为推广自家应用,苹果现推出了一个名为“Apps by Apple”的网站,展示了苹果为旗下产品(如 iPhone、iPad、Apple Watch、Mac 和 Apple TV)开发的各种应用程序。

发布于:7月以前  |  442次阅读  |  详细内容 »

特斯拉美国降价引发投资者不满:“这是短期麻醉剂”

特斯拉本周在美国大幅下调Model S和X售价,引发了该公司一些最坚定支持者的不满。知名特斯拉多头、未来基金(Future Fund)管理合伙人加里·布莱克发帖称,降价是一种“短期麻醉剂”,会让潜在客户等待进一步降价。

发布于:7月以前  |  441次阅读  |  详细内容 »

光刻机巨头阿斯麦:拿到许可,继续对华出口

据外媒9月2日报道,荷兰半导体设备制造商阿斯麦称,尽管荷兰政府颁布的半导体设备出口管制新规9月正式生效,但该公司已获得在2023年底以前向中国运送受限制芯片制造机器的许可。

发布于:7月以前  |  437次阅读  |  详细内容 »

马斯克与库克首次隔空合作:为苹果提供卫星服务

近日,根据美国证券交易委员会的文件显示,苹果卫星服务提供商 Globalstar 近期向马斯克旗下的 SpaceX 支付 6400 万美元(约 4.65 亿元人民币)。用于在 2023-2025 年期间,发射卫星,进一步扩展苹果 iPhone 系列的 SOS 卫星服务。

发布于:7月以前  |  430次阅读  |  详细内容 »

𝕏(推特)调整隐私政策,可拿用户发布的信息训练 AI 模型

据报道,马斯克旗下社交平台𝕏(推特)日前调整了隐私政策,允许 𝕏 使用用户发布的信息来训练其人工智能(AI)模型。新的隐私政策将于 9 月 29 日生效。新政策规定,𝕏可能会使用所收集到的平台信息和公开可用的信息,来帮助训练 𝕏 的机器学习或人工智能模型。

发布于:7月以前  |  428次阅读  |  详细内容 »

荣耀CEO谈华为手机回归:替老同事们高兴,对行业也是好事

9月2日,荣耀CEO赵明在采访中谈及华为手机回归时表示,替老同事们高兴,觉得手机行业,由于华为的回归,让竞争充满了更多的可能性和更多的魅力,对行业来说也是件好事。

发布于:7月以前  |  423次阅读  |  详细内容 »

AI操控无人机能力超越人类冠军

《自然》30日发表的一篇论文报道了一个名为Swift的人工智能(AI)系统,该系统驾驶无人机的能力可在真实世界中一对一冠军赛里战胜人类对手。

发布于:7月以前  |  423次阅读  |  详细内容 »

AI生成的蘑菇科普书存在可致命错误

近日,非营利组织纽约真菌学会(NYMS)发出警告,表示亚马逊为代表的电商平台上,充斥着各种AI生成的蘑菇觅食科普书籍,其中存在诸多错误。

发布于:7月以前  |  420次阅读  |  详细内容 »

社交媒体平台𝕏计划收集用户生物识别数据与工作教育经历

社交媒体平台𝕏(原推特)新隐私政策提到:“在您同意的情况下,我们可能出于安全、安保和身份识别目的收集和使用您的生物识别信息。”

发布于:7月以前  |  411次阅读  |  详细内容 »

国产扫地机器人热销欧洲,国产割草机器人抢占欧洲草坪

2023年德国柏林消费电子展上,各大企业都带来了最新的理念和产品,而高端化、本土化的中国产品正在不断吸引欧洲等国际市场的目光。

发布于:7月以前  |  406次阅读  |  详细内容 »

罗永浩吐槽iPhone15和14不会有区别,除了序列号变了

罗永浩日前在直播中吐槽苹果即将推出的 iPhone 新品,具体内容为:“以我对我‘子公司’的了解,我认为 iPhone 15 跟 iPhone 14 不会有什么区别的,除了序(列)号变了,这个‘不要脸’的东西,这个‘臭厨子’。

发布于:7月以前  |  398次阅读  |  详细内容 »
 相关文章
Android插件化方案 5年以前  |  236872次阅读
vscode超好用的代码书签插件Bookmarks 1年以前  |  6877次阅读
 目录